Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Condition vs wait notify mechanism

What is the advantage of using Condition interface/implementations over the conventional wait notify mechanism? Here I quote the comments written by Doug Lea:

Condition factors out the Object monitor methods (wait, notify and notifyAll) into distinct objects to give the effect of having multiple wait-sets per object, by combining them with the use of arbitrary Lock implementations. Where a Lock replaces the use of synchronized methods and statements, a Condition replaces the use of the Object monitor methods.

I see this is a more Object Oriented way of implementing wait/notify mechanism. But is there a sound advantage over the former?

like image 883
userx Avatar asked May 01 '12 08:05

userx


People also ask

What is the difference between wait () notify () and notifyAll ()?

The wait() method causes the current thread to wait until another thread invokes the notify() or notifyAll() methods for that object. The notify() method wakes up a single thread that is waiting on that object's monitor. The notifyAll() method wakes up all threads that are waiting on that object's monitor.

Why wait () notify () and notifyAll () methods have to be called from synchronized method or block?

Calling notify() or notifyAll() methods issues a notification to a single or multiple threads that a condition has changed and once the notification thread leaves the synchronized block, all the threads which are waiting for fight for object lock on which they are waiting and lucky thread returns from wait() method ...

What is the difference between notify and notify all method?

In case of multiThreading notify() method sends the notification to only one thread among the multiple waiting threads which are waiting for lock. While notifyAll() methods in the same context sends the notification to all waiting threads instead of single one thread.

Can we use wait and notify without synchronized?

If you need to call wait(), notify(), or notifyAll() from within a non-synchronized method, then you must first obtain a lock on the object's monitor. If you don't, an exception will be generated when an attempt is made to call the method in question.


1 Answers

The biggest problem is that wait/notify is error prone for new developers. The main problem is not knowing how to handle them correctly can result is obscure bug.

  • if you call notify() before wait() it is lost.
  • it can be sometimes unclear if notify() and wait() are called on the same object.
  • There is nothing in wait/notify which requires a state change, yet this is required in most cases.
  • wait() can return spuriously

Condition wraps up this functionality into a dedicated component, however it behaves much the same.

There is a question regarding wait/nofity posted minutes before this one and many, many more Search [java]+wait+notify

like image 63
Peter Lawrey Avatar answered Sep 19 '22 20:09

Peter Lawrey