Java: How threads communicate with each other

Threads communicate with each other with the help of 3 Object class methods

1. wait()
2. notify()
3. notifyAll()

Lets look at a simple example, Consider we have 2 threads, one is mail delivery thread and another is mail-processing thread. The mail-processing thread has to keep checking to see if there's any mail to process. The mail processing thread checks for any new mail for every 2 seconds. This is truly waste of time & cpu processing power.

Instead of that using wait&notify mechanism, when the mail-delivery thread puts a mail in mailbox & notifies mail-processing thread, so that it processes new mail.

Key Points:

1. wait(), notify() & notifyAll() must be called from within a synchronized context. A thread cannot invoke a wait or notify method on an object unless it owns that object's lock.

2. If the thread calling wait() does not own the lock, it will throw an IllegalMonitorStateException. This exception is not a checked exception. But a waiting thread can be interrupted in the same way as a sleeping thread, so you have to take care of the exception.

try
{
   wait();
} catch(InterruptedException ie)
{
    ie.printStackTrace();
}

3. when the wait() method is invoked on an object, the thread executing that code gives up its lock on the object immediately.
4. However, when notify() is called, that doesn't mean the thread gives up its lock at that moment. If the thread is still completing synchronized code, the lock is not released until the thread moves out of synchronized code. So just because notify() is called, this doesn't mean the lock becomes available at that moment.
5. notifyAll() - notifies all the waiting threads on that object.    

 Big point to remember while using wait(), notify(), notifyAll():

 while using wait(), notify(), notifyAll(), you should almost always have a while loop around the wait() that checks a condition and forces continued waiting until the condition is met. And you should also make use of the requried synchronization for the wait() & notify() calls to protect whatever other data you're sharing between threads.





Comments