Multithreading - Interthread communication

Generally, when one thread has acquired a lock, then other threads need to wait for the lock to get released. So other threads keep on polling to see if the lock has been released and that they can acquire it. This results in a waste of CPU cycles.

Java comes with a elegant solution to this. It provides wait(), notify() and notifyAll() methods that can be used for interthread communication without the need of polling.

wait() - tells the calling thread to give up the monitor and go to sleep until some other thread calls                    notify() or notifyAll() method.
notify() - wakes up the thread that called the wait() method on the object.
notifyAll() - wakes up all the threads that called the wait() method on the object. One of them will get                      access.

All the three methods are present in the Object class, hence are available to all the classes. These methods can be called from synchronized context only. In case, you try to call it outside synchronized context, an IllegalMonitorStateException is thrown.

MyInterThread t1 = new MyInterThread(arrayList, "S");t1.start();synchronized (t1) {
    t1.wait();}

private void removeElements() throws InterruptedException {
    synchronized (arrayList) { //remove this synchronized block to see concurrentmodificaitonexception        Iterator it = arrayList.iterator();
        while (it.hasNext()) {
            String s = (String) it.next();
            if (s.contains(strToRemove)) {
                it.remove();                System.out.println("Removed element : " + s);            }
        }
        arrayList.notify();    }
}

An example for interthreadcommunication can be found here

In addition to the example, Producer/Consumer problem is the best example for interthread communication. Producer thread is responsible for producing items while consumer threads waits for the items to be produced and consume items.

So consumer calls the wait method and producer calls the notify method.x`

Comments

Popular posts from this blog

Collection Framework - HashSet And LinkedHashSet class

Collection Framework - Cursors in Java

Hashed data structures