Sunday, 2 March 2014

Thread notify

public final void notify()
Wakes up a single thread that is waiting on this object's monitor. Suppose more than one thread is waiting on this object's monitor, then only one thread gets notified, the way the thread chosen is totally implementation dependent.

public final void notifyAll()
Wakes up all threads that are waiting on this object's monitor. A thread waits on an object's monitor by calling one of the wait methods. Now all the awakened threads also in competition for the resource.

Thread wait: release resources                                                 Thread states                                                 Home

Thread wait

wait method causes current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object.

Object class has 3 overloaded variations of wait method.

public final void wait() throws InterruptedException
Causes current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object. To call the wait(), current thread must get Objects monitor, other wise IllegalMonitorStateException thrown.

When wait called on particular object, The thread releases ownership of this monitor and waits until another thread notifies threads waiting on this object's monitor to wake up either through a call to the notify method or the notifyAll method.

public final void wait(long timeout) throws InterruptedException
Causes current thread to wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed.

public final void wait(long timeout, int nanos)throws InterruptedException

Causes current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object, or some other thread interrupts the current thread, or a certain amount of real time has elapsed.



Producer Consumer Problem                                                 Notify thread                                                 Home

Producer Consumer Problem

The wait/notify mechanism allows one thread to wait for a notification from another thread to proceed.

For Example consider producer-consumer problem, producer produces the items, and consumer consumes the items produced by the producer

Basic scenarios to be considered in producer consumer problem.

1. Consumer can't consume the items, if the items are not produced by producer. So consumer must wait until the producer produces items. So consumer calls the wait method of the producer object.

2. Once the consumer consumes the items, he must notify the producer, so producer produce the items.

3. Producer must wait until the consumer consumes the items.

4. Once the producer produces the items, then he must tell the consumer, Please consume the items. So he must notify the consumer.

Solving a Producer-Consumer Problem
class Queue{
 int noItems;
 boolean flag = true;

 void produce()throws Exception{
  if(flag){
   noItems++;
   System.out.println("Produced " + noItems);
   flag = false;
   notify();
  }
  else{
   wait();
  }
 }

 void consume()throws Exception{
  if(!flag){
   System.out.println("Consumed " + noItems);
   flag = true;
   notify();
  }
  else{
   wait();
  }
 }
}

class Producer implements Runnable{
 Queue q;
 public void run(){
  while(true){
   try{
    q.produce();
   }
   catch(Exception e){
   }
  }
 }

 Producer(Queue q){
  this.q = q;
 }
}

class Consumer implements Runnable{
 Queue q;

 public void run(){
  while(true){
   try{
    q.consume();
   }
   catch(Exception e){
   }
  }
 }

 Consumer(Queue q){
  this.q = q;
 }
}

class Test{
 public static void main(String args[]){
  Queue q = new Queue();

  Producer prod = new Producer(q);
  Consumer con = new Consumer(q);

  Thread t1 = new Thread(prod);
  Thread t2 = new Thread(con);

  t1.start();
  t2.start();
 }
}
   
Sample Output
Produced 1
Consumed 1
Produced 2
Consumed 2
Produced 3
Consumed 3
Produced 4
Consumed 4
Produced 5
Consumed 5
Produced 6
Consumed 6
Produced 7
Consumed 7
......
......

Explanation
There are four classes
    Queue Class
    Producer class
    Consumer class
    Test class

Queue class
Queue class object is the shared resource that is shared between producer and consumer. It has two methods, produce(), consume().

If flag is true,  producer start producing the items. The same logic implemented in produce().After producing the items, producer sets the flag to false, and notifies the consumer. So consumer consumes the item, sets the flag to true, and notifies the producer.

Producer class
Producer class calls the produce(), infinitely.

Consumer class
Consumer class calls the consume(), infinitely.

Test class
Test class tests the application of producer and consumer.   



Thread Join                                                 Thread wait: Release resources                                                 Home

Thread join

Suppose you divided a big problem into small tasks, lets say one big problem is divided into 5 small tasks. So to solve the whole problem. All the 5 tasks must be completed, one task may finishes immediately, other takes 5 minutes, and other may take 1 hour etc., Your program must wait until all the tasks finishes its execution. Here the join method comes into picture.

The join() method of Thread can be used to cause the current thread to block waiting for the specified thread to die.

Example
class JoinEx implements Runnable{
 public void run(){
  try{
   Thread.currentThread().sleep(1000);
   System.out.println(Thread.currentThread().getName() + " Finishes execution");
  }
  catch(Exception e){
   System.out.println(e);
  }
 }

 public static void main(String args[])throws Exception{
  JoinEx obj1 = new JoinEx();
  JoinEx obj2 = new JoinEx();
  JoinEx obj3 = new JoinEx();
  JoinEx obj4 = new JoinEx();
  JoinEx obj5 = new JoinEx();

  Thread task1 = new Thread(obj1);
  Thread task2 = new Thread(obj1);
  Thread task3 = new Thread(obj1);
  Thread task4 = new Thread(obj1);
  Thread task5 = new Thread(obj1);

  task1.start();
  task2.start();
  task3.start();
  task4.start();
  task5.start();

  task1.join();
  task2.join();
  task3.join();
  task4.join();
  task5.join();

  System.out.println("All tasks completed successfully");
 }
}
  
Sample Output
Thread-2 Finishes execution
Thread-1 Finishes execution
Thread-3 Finishes execution
Thread-4 Finishes execution
Thread-0 Finishes execution
All tasks completed successfully

Overloaded methods of join
public final void join(long millis) :Waits at most millis milliseconds for this thread to die. A timeout of 0 means to wait forever.

public final void join(long millis, int nanos) : Waits at most millis milliseconds plus nanos nanoseconds for this thread to die.

Join method throws InterruptedException, when the thread interrupted.


Inter Thread Communication                                                 producer Consumer problem                                                 Home

Inter Thread Communication

Inter thread provides a way that multiple threads communicate each other in consistent way.

Java provides 4 methods that makes the inter thread communication possible.

Those are:
   join()
   wait()
   notify()
   notifyAll()



static synchronized blocks                                                 Thread Join                                                 Home

static Synchronized blocks

synchronized blocks used to take a lock on object, where as static synchronized blocks are used to take a lock on class.

Syntax
synchronized ( ClassName.class ) {
    // body
}

Example
class ClassLockEx implements Runnable{
 static void printMethod(){
  synchronized(ClassLockEx.class){
   for(int i=0; i < 5; i++){
    try{
     Thread.currentThread().sleep(1000);
    }
    catch(Exception e){
     System.out.println(e);
    }
    System.out.println(Thread.currentThread().getName() + " " + i);
   }
  }
 }

 public void run(){
  printMethod();
 }

 public static void main(String args[])throws Exception{
  ClassLockEx obj1 = new ClassLockEx();
  ClassLockEx obj2 = new ClassLockEx();
  Thread t1 = new Thread(obj1);
  Thread t2 = new Thread(obj2);
  t1.start();
  t2.start();
 }
}
 
Output
Thread-0 0
Thread-0 1
Thread-0 2
Thread-0 3
Thread-0 4
Thread-1 0
Thread-1 1
Thread-1 2
Thread-1 3
Thread-1 4
  

static synchronized methods                                                 Inter Thread Communication                                                 Home

static Synchronized methods

synchronized methods acquires a lock on object where as static synchronized methods acquire a lock on class. Only one object of particular class can enter into the static synchronized method at a time. One class has one class lock with it.

Syntax
   static synchronized returnType methodName(parameters){

   }

Example: without synchronization for static method    
class ClassLockEx implements Runnable{
 static void printMethod(){
  for(int i=0; i < 5; i++){
   try{
    Thread.currentThread().sleep(1000);
   }
   catch(Exception e){
    System.out.println(e);
   }
   System.out.println(Thread.currentThread().getName() + " " + i);
  }
 }

 public void run(){
  printMethod();
 }

 public static void main(String args[])throws Exception{
  ClassLockEx obj1 = new ClassLockEx();
  ClassLockEx obj2 = new ClassLockEx();
  Thread t1 = new Thread(obj1);
  Thread t2 = new Thread(obj2);
  t1.start();
  t2.start();
 }
}
    
Sample Output    
Thread-0 0
Thread-1 0
Thread-0 1
Thread-1 1
Thread-0 2
Thread-1 2
Thread-0 3
Thread-1 3
Thread-0 4
Thread-1 4

As you see run method calling the“ printMethod”, which is static, so both the objects obj1, obj2 has access to the static method. So both are running parallelly. By using static synchronized method, Only one object can run the method at a time.

Use of static synchronized method
class ClassLockEx implements Runnable{
 static synchronized void printMethod(){
  for(int i=0; i < 5; i++){
   try{
    Thread.currentThread().sleep(1000);
   }
   catch(Exception e){
    System.out.println(e);
   }
   System.out.println(Thread.currentThread().getName() + " " + i);
  }
 }

 public void run(){
  printMethod();
 }

 public static void main(String args[])throws Exception{
  ClassLockEx obj1 = new ClassLockEx();
  ClassLockEx obj2 = new ClassLockEx();
  Thread t1 = new Thread(obj1);
  Thread t2 = new Thread(obj2);
  t1.start();
  t2.start();
 }
} 

Output    

Thread-0 0
Thread-0 1
Thread-0 2
Thread-0 3
Thread-0 4
Thread-1 0
Thread-1 1
Thread-1 2
Thread-1 3
Thread-1 4
   
With the help of static synchronization, until one object finishes it's execution with the static synchronized method, other objects must wait to run the same or other static synchronization methods of the same class.


Synchronized block                                                 static synchronized blocks                                                 Home