75

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?

5 Answers 5

37

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

14
  • 3
    You can have multiple conditions which share the same lock. e.g. docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/… wait/notify only has one "wait set" i.e. you can only notify any waiter, not a specific group. May 1, 2012 at 9:31
  • 7
    I'm not sure how Condition helps with anything but the third point. Calls to signal are lost if called before await, await can still return early, nothing in the interface indicates that state has to change. May 1, 2012 at 22:29
  • 1
    @Peter Lawrey if you call notify() before wait() it is lost. I don't understand. What does it mean? Apr 25, 2014 at 21:30
  • 2
    @gstackoverflow notify() only notifies a waiting thread. If you wait() after notify(), the wait doesn't know you called notify earlier. Apr 26, 2014 at 9:35
  • 4
    @PeterLawrey "a Condition is stateful and remembers the state change until it is consumed" I believe this is not correct: A Condition's signal() is also lost if called before await(), just like an Object's notify() is lost if called before wait(). I'd suggest to add to the answer some clarification that Conditions don't help with points 1 and 4 (yet they are "better" in the sense that they are more general - see also this answer) Aug 10, 2015 at 22:06
36

When you use Condition: await()/signal() you can distinguish which object or group of objects/threads get a specific signal. Here is a short example where some threads, the producers, will get the isEmpty signal while the consumers will get the isFull signal:

private volatile boolean usedData = true;//mutex for data
private final Lock lock = new ReentrantLock();
private final Condition isEmpty = lock.newCondition();
private final Condition isFull = lock.newCondition();

public void setData(int data) throws InterruptedException {
    lock.lock();
    try {
        while(!usedData) {//wait for data to be used
            isEmpty.await();
        }
        this.data = data;
        isFull.signal();//broadcast that the data is now full.
        usedData = false;//tell others I created new data.          
    }finally {
        lock.unlock();//interrupt or not, release lock
    }       
}

public void getData() throws InterruptedException{
    lock.lock();
    try {
        while(usedData) {//usedData is lingo for empty
            isFull.await();
        }
        isEmpty.signal();//tell the producers to produce some more.
        usedData = true;//tell others I have used the data.
    }finally {//interrupted or not, always release lock
        lock.unlock();
    }       
}
7
  • - Thanks, I went through your post after posting stackoverflow.com/questions/10407708/…
    – userx
    May 2, 2012 at 4:29
  • Great example! Shouldn't you be setting usedData=true/false before signaling ? May 19, 2014 at 20:21
  • 2
    When you use wait()/notify() you don't decide which waiting objects/threads are notified: You do. Jun 18, 2014 at 1:16
  • @AfterWorkGuinness > Shouldn't you be setting usedData=true/false before signaling After signal code go until end of lock block and release it, so order doesn't matter Sep 11, 2016 at 15:47
  • 1
    @kasavbere so Even if I have used same Condition for await and notify in both method it would have worked? The different names are just for logical separation.?
    – garg10may
    Mar 3, 2017 at 0:13
27

There are many advantages like mentioned above about Condition Interface some important are as follows:

Condition interface comes with Two extra methods that are:

1)boolean awaitUntil(Date deadline)throws InterruptedException : Causes the current thread to wait until it is signalled or interrupted, or the specified deadline elapses.

2)awaitUninterruptibly() : Causes the current thread to wait until it is signalled.

If the current thread's interrupted status is set when it enters this method, or it is interrupted while waiting, it will continue to wait until signalled. When it finally returns from this method its interrupted status will still be set.

The above two methods are not present in default monitor that is in object class,in some situations we want to set the deadline for thread to wait then we are able to do that by Condition interface.

In some situations we don't want thread to be interrupted and want current thread to wait until it is signaled then we can go for awaitUninterruptibly method present in Condition Interface.

For more information Condition Interface Java Documentation:

http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/locks/Condition.html#awaitUntil%28java.util.Date%29

1
  • 3
    The behavior of awaitUntil(Date deadline) would change if the System clock changes whereas it may not for wait(long timeInMilliseconds) Jun 18, 2014 at 1:10
5

To specifically address why having multiple waitsets is an advantage:

With wait/notify if there are different things that threads are waiting for (the common example is a fixed size blocking queue, with some threads putting things in the queue and blocking when the queue is full, and other threads taking from the queue and blocking when the queue is empty) then if you use notify, causing the scheduler to pick one thread from the wait set to notify, you can have corner cases where the chosen thread isn't interested in being notified for a particular situation. For instance the queue will notify for adding something to the queue, but if the chosen thread is a producer and the queue is full then it can't act on that notification, which you would rather have gone to a consumer. With intrinsic locking you have to use notifyAll in order to make sure that notifications don't get lost.

But notifyAll incurs churn with every call, where every thread wakes up and contends for the lock, but only one can make progress. The other threads all bump around contending for the lock until, one at a time, they can acquire the lock and most likely go back to waiting. It generates a lot of contention for not much benefit, it would be preferable to be able to use notify and know only one thread is notified, where the notification is relevant to that thread.

This is where having separate Conditions to wait on is a big improvement. The queue can invoke signal on a condition and know it will wake up only one thread, where that thread is specifically waiting for the condition.

The API doc for Condition has a code example that shows using multiple conditions for a bounded buffer, it says:

We would like to keep waiting put threads and take threads in separate wait-sets so that we can use the optimization of only notifying a single thread at a time when items or spaces become available in the buffer.

2
  • Good contribution to the subject. I would maybe point out at the top that if you have only 1 thread waiting, Condition probably doesn't give you much advantage (and no "churn" with notifyAll())
    – Robert
    May 6, 2022 at 12:57
  • @Robert: thanks. you know it's always a judgment call to decide how much to include. And this post is on the long side anyway. May 6, 2022 at 13:08
1

In addition to other well accepted answers - since Condition is associated with Lock object you can have arbitrary sets of Lock objects (reawrite, read, write) in your class and have specific condition associated with that. Then you can use those set of condition to synchronize different parts of your class according to your implementation semantics. This gives more flexibility and explicit behavior then wait-notify imo

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.