Skip to main content

Posts

Showing posts with the label Thread Coordination

Wait/Notify Idiom

Some times threads need some condition to be realized by other threads to continue execution. Until this condition is realized a thread should make continues wait and check. But this means waste of resources and since thread probably owns lock that is needed by other threads to realize this condition, may lead to deadlocks. Java has a better alternative.  Java Object class has wait/notify/notifyAll methods to deal with such situations.  A complete example of wait/notify idiom is given below. class ProducerConsumer {     List dataList = new ArrayList ();     boolean empty = true ;     synchronized void produce () {         dataList . add ( new Object ());         empty = false ;         notifyAll ();// notify waiting threads     }     synchronized void consume ...