Monday, October 7, 2013

Inter thread communication showing the usage of notifyAll() method.

Lets start with the methods that facilitates Inter Thread Communication in Java . All these methods are present in java.lang.Object class .

wait()
wait() method is used to instruct the current thread to release the object's lock and get suspended until some other thread invokes notify() or notifyAll() method for the same monitor.

notify()
notify() method is used to wake up a thread that is suspended by the wait() method.

notifyAll()
notifyAll() method is used to wake up all the threads that are suspended by wait() method.

Lets come to our topic . notifyAll() method is important when several threads are waiting on one object. For example there is a class that performs a calculation and many readers are waiting to read the computed calculation.

class Calculator extends Thread {
    private int total;
    private boolean isCalcDone;

    @Override
    public void run() {
        synchronized (this) {
            for (int i = 0; i < 10000; i++) {
                total += i;
            }
            isCalcDone = true; // ------------ (3)
            notifyAll();       // ------------ (4)
        }
    }

    public int getTotal() {
        return total;
    }

    public boolean isCalcDone() {
        return isCalcDone;
    }
}

class CalcReader extends Thread {
    Calculator calculator;

    public CalcReader(Calculator calculator) {
        this.calculator = calculator;
    }

    @Override
    public void run() {
        synchronized (calculator) {
            //Reader threads waits for the Calculator to complete its calculation by calling wait().
            while (!calculator.isCalcDone()) {  // ------------ (1) 
                System.out.println("Waiting for calculator");
                try {
                    calculator.wait();          // ------------ (2)
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("Total is :" + calculator.getTotal());
        }
    }

}

public class NotifyAllExample {
    public static void main(String[] args) {
        Calculator calculator = new Calculator();
        new CalcReader(calculator).start();
        new CalcReader(calculator).start();
        new CalcReader(calculator).start();
        calculator.start();
    }
}

In the above example :
1. We have created three CalcReader threads sharing a common Calculator instance.
2. At (1) , Threads checks if Calculator has completed the  calculation , if not , calls wait() at (2) , releases the lock and waits for the Calculator to complete its calculation.
3. When Calculator completes its calculation , sets isCalcDone to true at (3) and notifies all the waiting threads at (4). 

No comments :

Post a Comment