Reputation: 3773
1) Yesterday only I asked this question Condition vs wait notify mechanism
2) I wanted to edit the same and add a few ifs to my question, but because it could have become cumbersome and contained enough text to disinterest and baffle the reader, I thought of asking a new question here.
3) With context of my post whose url is given in point number 1), consider a case of 4 threads, P1,T1 and P2,T2 acting on a single data structure 'S'.
4) I am trying to again draw the advantages of using Condition interface over wait notify.
5) Consider the code
final Lock lock = new ReentrantLock();
Condition c1 = lock.newCondition();
Condition c2 = lock.newCondition();
Condition c3 = lock.newCondition();
Condition c4 = lock.newCondition();
6) Consider P1,T1 making use of c1,c2 (in a standard await()/signalAll() manner). Consider P2,T2 making use of c3,c4 (in a standard await()/signalAll() manner) in let's say put,take,put1,take1 methods respectively.
7) When I do c1.signalAll(), will only the threads waiting on/because of condition1 will recieve signal. Do I make sense ?
8) Consider a wait/notify mechanism to implement the same say,
private static final Object lock= new Object();
synchronized(lock)
Consider put,take,put1,take1, so if any thread does a lock.notifyAll() on any one of the condition fulfillment, even the threads waiting for/on because of other conditions will recieve a notification. Is that true ?. Is that something we can count as a disadvantage of using wait/notify over Condition mechanism ?
Upvotes: 4
Views: 6273
Reputation: 29523
Yes, you are right. The Condition
class is a generalization of intrinsic condition queues (the ones which are controlled through Object.wait
, Object.notify
and Object.notifyAll
).
I will quote Brian Goetz`s Java Concurrency in Practice [p.306-307]
Intrinsic condition queues have several drawbacks. Each intrinsic lock can have only one associated condition queue, which means that in classes like BoundedBuffer multiple threads might wait on the same condition queue for different condition predicates, and the most common pattern for locking involves exposing the condition queue object. Both of these factors make it impossible to enforce the uniform waiter requirement for using notifyAll. If you want to write a concurrent object with multiple condition predicates, or you want to exercise more control over the visibility of the condition queue, the explicit Lock and Condition classes offer a more flexible alternative to intrinsic locks and condition queues.
A Condition is associated with a single Lock, just as a condition queue is associated with a single intrinsic lock; [...] And just as Lock offers a richer feature set than intrinsic locking, Condition offers a richer feature set than intrinsic condition queues: multiple wait sets per lock, interruptible and uninterruptible condition waits, deadline-based waiting, and a choice of fair or nonfair queueing.
Upvotes: 9