Saturday, 26 October 2013

How to avoid deadlock in Java Threads

What is deadlock ?

 When two or more threads waiting for each other to release lock and get stuck for infinite time , situation is called deadlock . it will only happen in case of multitasking.

How do you detect deadlock in Java ?
 
if nested synchronized block or calling one synchronized method from other or trying to get lock on different object then there is good chance of deadlock if developer is not very careful.

write code which will result in deadlock ?

public void method1(){
synchronized(String.class){
System.out.println("Aquired lock on String.class object");

synchronized (Integer.class) {
System.out.println("Aquired lock on Integer.class object");
}
}
}

public void method2(){
synchronized(Integer.class){
System.out.println("Aquired lock on Integer.class object");

synchronized (String.class) {
System.out.println("Aquired lock on String.class object");
}
}
}

How to avoid deadlock in Java ?
 
public void method1(){
synchronized(Integer.class){
System.out.println("Aquired lock on Integer.class object");

synchronized (String.class) {
System.out.println("Aquired lock on String.class object");
}
}
}

public void method2(){
synchronized(Integer.class){
System.out.println("Aquired lock on Integer.class object");

synchronized (String.class) {
System.out.println("Aquired lock on String.class object");
}
}
}


 

Now there would not be any deadlock because both method is accessing lock on Integer and String object in same order . so if thread A acquires lock on Integer object , thread B will not proceed until thread A releases Integer lock , same way thread A will not be blocked even if thread B holds String lock because now thread B will not expect thread A to release Integer lock to proceed further.

 

Sunday, 20 October 2013

Java Memory Types

Java has only two types of memory when it comes to JVM.

Heap memory and Non-heap memory.

Heap Memory

Class instances and arrays are stored in heap memory. Heap memory is also called as shared memory. As this is the place where multiple threads will share the same data.

Non-heap Memory

It comprises of ‘Method Area’ and other memory required for internal processing. So here the major player is ‘Method Area’.

Method Area

As given in the last line, method area is part of non-heap memory. It stores per-class structures, code for methods and constructors. Per-class structure means run time constants and static fields.


Memory Pool

Memory pools are created by JVM memory managers during run time. Memory pool may belong to either heap or non-heap memory.

Runtime Constant Pool

A run time constant pool is a per-class or per-interface run time representation of the constant_pool table in a class file. Each run time constant pool is allocated from the Java virtual machine’s method
area.
jvm memory

Saturday, 19 October 2013

Abstract class vs Interface

Abstract class:
  • cannot be instantiated.
  • is a special type of class in which you can have members without implementation.
  • as we know in C#/VB/Java, a class can only inherit from 1 class. This also applies for Abstract Class.
  • normally used for framework-type library classes: providing default behavior for some of its class members, but forcing the developer to implement others.
  • is believed to be faster in Java,
  • the aim: making sure something is *eventually* implemented.
  • A class can inherit an abstract class without implementing all its abstract method.
    However only a class that has all its method implemented can be instantiated to an object.
  • IS-A relationship.
  • e.g. Student IS A Person, Employee IS A Person.
// 'framework library' for a person
// a person can enrol and submit
// however, the class that consume this framework library
// need to provide 'where' the paperwork need to be sent
public abstract Person
{
    public abstract SendPaperWork(string paperwork)

    public void Enrol()
    {
        SendPaperWork("enrolment");
    }

    public void Submit()
    {
        SendPaperWork("report");
    }
}

// by inheriting Person abstract class
// we are enabling student to enrol and submit
// however, SendPaperWork need to be implemented
// because we need to tell it explicitly 'where' 
// to send the enrolment/ submission
public class Student : Person
{
    public override SendPaperWork(string paperwork)
    {
        School.Send(paperwork);
    }
}

// an employee send the paperwork to a different 'place' than student
public class Employee : Person
{
    public override SendPaperWork(string paperwork)
    {
        Company.Send(paperwork);
    }
}
Interface:
  • cannot be instantiated.
  • is a special type of abstract class in which all the members do not have any implementations.
  • enables polymorphism. A class can implement more than 1 Interfaces.
  • normally used for application classes: providing contract for ensuring interactibility.
  • the aim: making sure something is interchangeable.
  • A class that implements an Interface need to contain all the implementation, otherwise the compiler will throw an error.
  • CAN-DO relationship.
  • e.g. Student CAN enrol, Student CAN submit assignment.
public interface ICanEnrol
{
    void Enrol();
}

public interface ICanSubmit
{
    void Submit();
}

public class Student : ICanEnrol, ICanSubmit
{
    public void Enrol()
    {
        School.Send("enrolment");
    }

    public void Submit()
    {
        School.Send("report");
    }
}

public class Employee : ICanEnrol, ICanSubmit
{
    public void Enrol()
    {
        Company.Send("enrolment");
    }

    public void Submit()
    {
        Company.Send("report");
    }
}

public class MailServer
{
    public void SendAllSubmissions()
    {
        // AllSubmitters is a collection of students and employees
        foreach (ICanSubmit submitter in AllSubmitters)
        {
            // The MailServer does not care if 
            // the submitter is a student
            // or an employee, as long as it can submit
            submitter.Submit()
        }
    }
}

Why use abstract class and not interface?

Class which provides some of the functionality required by derived classes, but each derived class additionally requires differing implementation of other functionality, then an abstract class provides a means of defining the common implementation, while leaving the specific behaviors required by derived classes to be made specific to each derived class. 

You can not extends more than one class but you can implements more than one interface

Abstract Class

  • Allows you to leverage the power of using constructors and constructor overriding
  • Restrict the class having multiple inheritance(This is particularly useful if you are designing a complicated API)
  • Instance variables and method implementations
  • Leverage the power of method super calling(Use super to call the parent abstract class's implementation)

Interface

  • Enables multiple inheritance - you can implement n number of interfaces
  • Allows to represent only conceptual methods (No method bodies)
Abstract classes do have a few advantages:
  • they allow you to specify abstract methods with package/protected modifiers
  • they facilitate code re-use
  • via the use of abstract methods and final methods on the super class they allow you to restrict the manner in which your class is subclassed, which can be useful in a wide variety of circumstances
  • code that references classes is generally easier to follow in an IDE (clicking "open declaration" on an abstract class type parameter is usually more useful than on an interface type parameter)

Generally use Interfaces for '-able' clause(as in functionality). Eg:-
  1. Runnable
  2. Observable
Use abstract classes for something like is-a(evolution format). Eg:-
  1. Number
  2. Graphics

Friday, 11 October 2013

Biggest of 3 numbers using conditional operator witout using && || !=


Program
---------
import java.util.Scanner;
class demo
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
int a,b,c,big;
System.out.println("Enter 3 numbers");
a=s.nextInt();
b=s.nextInt();
c=s.nextInt();
big= a>b ? (a>c ? a : c) : (b>c ? b : c);
System.out.println(big);
}
}

Amicable Numbers Program

Amicable number are pairs of numbers each of whose divisors add to the other
number


Example 
------------
import java.util.Scanner;
class Amicable
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
int i,j,n,sum_i=0,sum_j=0; 
System.out.println("Enter 2 Numbers");
i=s.nextInt();
j=s.nextInt();
for(n=1;n<i;n++)
{
if(i%n==0)
sum_i += n;
}
for(n=1;n<j;n++)
{
if(j%n==0)
sum_j += n;
}
if( (sum_j == i)&& (sum_i==j))
System.out.println("Amicable");
else
System.out.println("Not Amicable");
}
}


 

Tuesday, 8 October 2013

Thread

A THREAD is a single sequential flow of control within a program. 

  •  All Java programs have at least one thread, known as the main thread, which is created by the JVM at the program’s start, when the main() method is invoked with the main thread
PROCESS vs THREAD

A process runs independently and isolated of other processes. It cannot directly access shared data in other processes. The resources of the process, e.g. memory and CPU time, are allocated to it via the operating system.
A thread is a so called lightweight process. It has its own call stack but can access shared data of other threads in the same process. Every thread has its own memory cache. If a thread reads shared data it stores this data in its own memory cache. A thread can re-read the shared data.

Example:

The HotJava Web browser is an example of a multithreaded application. Within the HotJava browser you can scroll a page while it's downloading an applet or image, play animation and sound concurrently, print a page in the background while you download a new page, or watch three sorting algorithms race to the finish.


How to Create a Thread!

  1. creating a thread is accomplished by implementing an interface and extending a class. 
  2. Every Java thread is created and controlled by the java.lang.Thread class. 
  3. When a thread is created, it is assigned a priority. 
  4. The thread with higher priority is executed first, followed by lower-priority threads.
The JVM stops executing threads under either of the following conditions:

  • If the exit method has been invoked and authorized by the security manager.
  • All the daemon threads of the program have died.
Types

Multithread
Java is a multithreaded application that allows multiple thread execution at any particular time.
Single Thread
In a single-threaded application, only one thread is executed at a time because the application or program can handle only one task at a time. 

Properties

  • Thread id
  • Each thread has a unique ID (int value) which is provided by either the runtime or the OS; this is very helpful when you want to get the actual reference by.
  • Thread name
  • A name for the thread, it could be the same through many threads, also could be empty. It's useful to categorize threads belonging to a specific module or task.
  • Thread State
  • The current state of the thread. The state of a thread is determined by the State enumeration, and a thread state could be one of the following:
  1. Runnable: indicates that the thread has started and is running its task.
  2. New: indicates the thread has been created, but hasn't invoked (started) yet; when you just create an instance of the thread and haven't attempted invoke the start().
  3. Blocked: when a thread is in running state and is blocked because it is waiting for locking a resource which has been locked by another thread.
  4. Waiting: when the thread is idle and is waiting for a signal (notify).
  5. Timed_Waiting: when the thread is sleeping for an amount of time or is waiting for a signal from any another thread with timeout.
  6. Terminated: when a thread either has finished its job, note that a terminated thread would not start over from the beginning, and it's ready for finalizing.
  7. Interrupted: this indicates if an interrupt signal has been sent to the thread or not, note that this is not an actual state, a thread would get interrupted when it's in either running or waiting states (not in new and terminated states). You cannot get the interrupt state by the State enumeration.
  8. Dead: when thread A is waiting for a signal from thread B, where thread B is waiting for thread A too, or maybe thread B has sent the signal just before thread A attempts to wait for it (this is the actual dead lock), here there is nothing left behind to signal the waiting thread. You need to just program your application in such a way that you ensure there is no dead state. Note that there is no property or method to determine if a thread is in dead state or not.
  •  Thread Priority

    It indicates the priority of the thread, a higher priority causes more process attention (context switch) to the thread, that could be one of the following:
    • MAX_PRIORITY
    • MIN_PRIORITY
    • NORM_PRIORITY (default value)
 Daemon mode:
this one is used for setting that a thread should run in Daemon (background) mode or not. When a thread is in daemon mode, it means it runs until any other user thread (non-daemon) is alive in the application. Whenever there is no user-thread alive, then JVM kills the daemon threads by force (silently). You cannot even get any exception about the exit signal. These kinds of threads are useful when your application needs to have a background-service thread or an event-handler. These threads are usually run in lower priority. Once again, these threads are running within your process, but JVM does not look at them as user threads for checking the life of the process

Thread's Behaviors

  • Start (simultaneously): when the thread needs to run simultaneously with another thread(s), this operation is done by the thread start() method.
  • Sleep: whenever a thread needs to sleep for a particular of time Thread.sleep(time in ms) would help, note that there is no warranty about the exact time, it could get more, the sleep process (reminded time) could get skipped if another thread Interrupts the sleeping thread.
  • Interrupt: it's used when a thread needs to interrupt another thread where it is in either wait (and join()), sleep, or even runnable states. For example, thread A is waiting for a signal, then thread B interrupts thread A, here the interrupt message:
    1. wakes up the target thread if it's either in wait (wait/join) or sleep state
    2. throws InterruptedException to the target thread to notify it about the interrupt signal
    3. sets the interrupted flag to true if and only if the thread was in running state.
      Note that when a thread is in sleep, join, and wait states:
  1. every sleep, join, or wait operation should be surrounded with a try-catch block because of any interruption signal (exception)
  2. the interruption is just like a signal, it doesn't force the thread to shutdown
  •  Getting the current thread: you would access the current thread by Thread.currentThread(). It returns a reference to the currently executing thread object, but outside the thread you may need to check all the threads or have a references of the thread.
  • Join: it means as it says, when thread A joins thread B, it means thread A has to wait until thread B is finished (termination).
  • Yield: a thread calls yield it means the OS can switch to another thread but the first thread still needs to work. 
  • wait()

    It releases the synchronized (locked) object, and waits until another thread notifies (notify, stop, or interrupt) it, then after it gets notified (if by notify) tries to acquire the lock again and continues its work. Note that a waiting thread has to acquire its lock again on the related object.

    sleep()

    ID doesn't release any locked object, and sleeps for a specified amount of time, it could get canceled (wake up) by either stop or interrupt signals.

Tuesday, 1 October 2013

Computing Technology

Different types of computing --

Grid, Cloud, Utility, Distributed and Cluster computing

Cloud Computing 
  • Cloud computing is a computing paradigm shift where computing is moved away from personal computers or an individual application server to a “cloud” of computers. Users of the cloud only need to be concerned with the computing service being asked for, as the underlying details of how it is achieved are hidden. This method of distributed computing is done through pooling all computer resources together and being managed by software rather than a human.
  • The services being requested of a cloud are not limited to using web applications, but can also be IT management tasks such as requesting of systems, a software stack or a specific web appliance.


Grid Computing 
  • Multiple independent computing clusters which act like a “grid” because they are composed of resource nodes not located within a single administrative domain. (formal)
  • Offering online computation or storage as a metered commercial service, known as utility computing, computing on demand, or cloud computing.
  • The creation of a “virtual supercomputer” by using spare computing resources within an organization.


 Utility Computing
  • Conventional Internet hosting services have the capability to quickly arrange for the rental of individual servers, for example to provision a bank of web servers to accommodate a sudden surge in traffic to a web site.
  • “Utility computing” usually envisions some form of virtualization so that the amount of storage or computing power available is considerably larger than that of a single time-sharing computer. Multiple servers are used on the “back end” to make this possible. These might be a dedicated computer cluster specifically built for the purpose of being rented out, or even an under-utilized supercomputer. The technique of running a single calculation on multiple computers is known as distributed computing.


Distributed Computing 
  • A method of computer processing in which different parts of a program are run simultaneously on two or more computers that are communicating with each other over a network. Distributed computing is a type of segmented or parallel computing, but the latter term is most commonly used to refer to processing in which different parts of a program run simultaneously on two or more processors that are part of the same computer. While both types of processing require that a program be segmented—divided into sections that can run simultaneously, distributed computing also requires that the division of the program take into account the different environments on which the different sections of the program will be running. For example, two computers are likely to have different file systems and different hardware components.



Cluster Computing 
  • A computer cluster is a group of linked computers, working together closely so that in many respects they form a single computer. The components of a cluster are commonly, but not always, connected to each other through fast local area networks. Clusters are usually deployed to improve performance and/or availability over that provided by a single computer, while typically being much more cost-effective than single computers of comparable speed or availability. 

Web Services

Web Services can convert your applications into Web-applications.

A web service is a method of communication between two electronic devices over the World Wide Web. A web service is a software function provided at a network address over the web or the cloud; it is a service that is "always on" as in the concept of utility computing.

  • Web services are application components
  • Web services communicate using open protocols
  • Web services are self-contained and self-describing
  • Web services can be discovered using UDDI
  • Web services can be used by other applications
  • XML is the basis for Web services

The basic Web services platform is XML + HTTP.
XML provides a language which can be used between different platforms and programming languages and still express complex messages and functions.

The HTTP protocol is the most used Internet protocol.

Web services platform elements:
  • SOAP (Simple Object Access Protocol)
  • UDDI (Universal Description, Discovery and Integration)
  • WSDL (Web Services Description Language)
 Uses
  1. Reusable application-components.
  2. Connect existing software.