Home » Java and J2EE » Multithreading in Java

Multithreading in Java

Multithreading

Usually a program has logic to execute and some objects or data to modify. In a single threaded system program executes in a sequence line by line. Multithreaded system can allow multiple threads to execute a program parallel in multiple instances. If there is any part of code dealing with the object data modification, there is no guarantee that it will not be attempted any more than one thread at a time.

Now there a need to make sure that such kind of code should be executed exclusively. To achieve this in Java we a concept of LOCK. Using Lock mechanism thread holds complete hold on an object and object is also can not be access any other thread except the thread holding that lock. Lock is an object level control and one thread only can hold it at a time.

Synchronized: We have to specify about the piece of code in a program which should be run exclusively. It could be a code segment or a complete function. Synchronised can be used in following ways:

Function level synchronise will fetch a lock on the object, this function is defined in.

1)  synchronised function updateTotal(){
       // some code
    }

2)  a block of code can also be defined as synchronised with an specified object, to capture a lock control on.

function updateTotal(){
     // some code 
     Synchronised(this){
     //some code
     }
}

Thread Sates or Life cycle. Thread follwos a life cycle, which starts from the threation till it is destroyed.

multith

  •  A thread can be in one of the following states:

    • NEW
      A thread that has not yet started is in this state.  This is the first state when thread object is created. Thread will be in this state until the run method is not called of.
    • RUNNABLE
      A thread executing in the Java virtual machine is in this state. Once the run method is called, thread goes in the runnble state.  While it is in a runnable state it is eligible to get process time to execute its part. Process though will keep distributing the time among all the active threads. Thread can also move to waiting state due to two reasons. 1 Timed waiting 2: Object waiting. Threads not in runnable states do not get process time.
    • BLOCKED
      A thread that is blocked waiting for a monitor lock is in this state.
    • WAITING
      A thread that is waiting indefinitely for another thread to perform a particular action is in this state.Some time a thread need a lock on a object and that object is being used bus another prohram or thread, in this case thread will wait for this object untill the object is not free. Some time this can cause a deadlock schenario if there is a possiblility that threads are using same objects in multiple situations and if the program is not designed properly.
    • TIMED_WAITING
      A thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state. Tread is forced to wait for some period of time may be by using Thread.sleep method. It will automatically come back to runnable state once specifiled time is over.
    • TERMINATED
      A thread that has exited is in this state.

    A thread can be in only one state at a given point in time. These states are virtual machine states which do not reflect any operating system thread states. Ref :  http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.State.html

 

Inter Thread Communication: When threads are trying to access a common object and that is bieng used by another thread. Theres has to be some way to notify the waiting threads once that object becomes free. This is achieved by wait,notify, notifyAll machanism. Wait and Notify is a machanism by which we can send signals between the thread when some specific condition is met.

Lets understand by the example of >> Producer and Consumer Problem in Java
======================================

import java.util.ArrayList;
import java.util.Random;
//Shared resource
class Pool{
   ArrayList pool = new ArrayList();
   int maxSize=10;
   public synchronized String popItem(){
   if(this.pool.size() = maxSize){
     System.out.println("List Full !" + this.pool.size());
     try {
      wait();
     } catch (InterruptedException e) {
      LOG.error("Interrup has occured");
      e.printStackTrace();
     }
   }
   notify();
   pool.add(item);
 }
}

//Supplier Thread
class Supplier extends Thread{
  Pool poolSet;
  public Supplier(Pool poolSet) {
     this.poolSet = poolSet;
     this.setName("Supplier");
  }

 public void run() {
   while(true){
   String rand = new Random().toString();
   System.out.println(this.getName()+" Adding " + rand);
   poolSet.pushItem(rand);
   try {
     Thread.sleep(1000);
   } catch (InterruptedException e) {
      LOG.error("Interrupt has occurred");
      e.printStackTrace();
   }
 }
}
}

//Consumer Thread
class Consumer extends Thread{
  Pool poolSet;
  public Consumer(Pool poolSet) {
   this.poolSet = poolSet;
   this.setName("Consumer");
  }
 public void run() {
 while(true){
    System.out.println(this.getName()+" Read: " + poolSet.popItem());
    try {
       Thread.sleep(10000);
    } catch (InterruptedException e) {
       e.printStackTrace();
    }
    }
  }
}

//Test case
public class TestThread {
   public static void main(String[] args){
   Pool mypool = new Pool();
   Supplier sup = new Supplier(mypool);
   Consumer con = new Consumer(mypool);
   con.start();
   sup.start();
 }
}

======================================

Above Example demonstrate three classes Pool , Consumer and Supplier as all are part defined under the main program so that class Consumer and Supplier have direct access to the object of Class Pool.

Otherwise if they are we can also pass PoolC class object to Consumer and Supplies class constructor if they are not under a same class.

Notify() and NotifyAll(): It’s a good question to ask that what’s difference between notify() and notifyAll() methos. Notify() method will send a signal to one of the thread waiting for the same object (this may depend on any criteria like thread priprity or it can also be random). Whereas notifyAll() will send signal to all the threads who are waiting for that object and then it is upto the processor which therads it allows to execute.

Sleep() method: Sleep method is a static method and called from the Thread class directly. Thread.sleep(100) and it throws intereuptException, so you have to catch it also.

wait() method: Wait is the method of Object class and should always be called from the synchronised block of code. Advised to use wait(long timeOut)

Thread Interruption: Each thread has a boolean property associated with it which represents its interrupt status. When a thread is interrupted by some other thread by calling its Thread.interrupt() method then one of the two things happen

a) If a thread is executing low level incorruptible method like sleep() wait() pr join() then it unblocks them and throws InterruptedException.

b) Otherwise interrupt() just sets the internal flag value of the interrupted thread to true, that why is is recommended to check its status by calling isInterrupted() in threads normal business. When isInterrupted() returns true that means it is signal to stop the thread execution.

Advertisements

4 Comments

  1. Rahul says:

    Excellent article, very useful!
    Thanks
    Rahul

  2. Rob says:

    Its really a simple but very explanetry writup. Thanks for explaning the concept so well.
    Thanks
    Rob Millan

  3. Hariuday says:

    Good Article..Thanks!

  4. ronee steave says:

    simple and clean explanation …thanks for the note.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: