Programming Tutorials

Comment on Tutorial - wait(), notify() and notifyAll() in Java - A tutorial By Jagan



Comment Added by : Mladen Covic

Comment Added at : 2013-03-28 15:08:04

Comment on Tutorial : wait(), notify() and notifyAll() in Java - A tutorial By Jagan
Unfortunatelly this a BAD example of to communicate between Threads. In general, it is a bad idea to use wait and notify to communicate between Threads ONLY relying on wait and notify. The reason is very simple: nothing guaranties that object waiting will receive the proper notification. In other words it might either :

A) receive notification sent from someone else and NOT Producer.

just add this in main method at the end
synchronized(q)
{
q.notify();
}

or

B) Consumer never receives the notification and hangs

just add in the main method:

synchonized(q)
{
...
// do something forever without releasing the lock on q
}

In general, communication between threads should be done either through Events and (synchronized) EventMulticasters or anchored around VERY protected (encapsulated) synchronized object with with wait and notify only called on that object. Even then there is a pssibkity of messing that object's monitor.


View Tutorial