Showing posts with label thread notify. Show all posts
Showing posts with label thread notify. Show all posts

Sunday, 2 March 2014

Why Wait and Notify is in Object Class

In java, we are acquiring locks on the resources. Every Object treated as a resource in java. Since Java is multi threaded, there is a possibility for resource corruption, if multiple threads are working on the same resource. There should be a mechanism, to safely update the resource. Here the monitor concept came to picture.

While performing any update on the resource, a thread must acquire a lock on the resource. Then the thread which acquires lock on the resource, update the resource, remaining all threads which want to work on this resource must wait until it finishes. Once the the thread finishes its updation with the resource, it asks the resource, to notify remaining threads to update. Same procedure like acquiring lock, releasing lock, notifying other threads repeats.

Since in java every resource considers to be an object, so that wait, notify and notifyAll kept in Object class.


Thread States                                                 Dead Lock                                                 Home

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

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