Locks, conditions and AQS question 39 of 180 mid
What does Condition give you that wait/notify does not?
- Nothing, it is the same API with different names
- Correct: Several independent wait queues on one lock, so you can signal exactly the waiters that can make progress
- It avoids spurious wakeups
- It does not require holding the lock
A monitor has exactly one wait set, so a bounded buffer with producers and consumers waiting on the
same object has to use notifyAll() and wake everyone. A Lock can create as many Condition
objects as you have reasons to wait:
final Condition notFull = lock.newCondition();
final Condition notEmpty = lock.newCondition();
Now signal() on notEmpty wakes a consumer and only a consumer. That is a targeted wakeup with no
thundering herd, and it is what ArrayBlockingQueue does internally.
Everything else carries over unchanged: await() must be in a while loop for the same two reasons,
and you must hold the lock to call await or signal, or you get IllegalMonitorStateException.
Quiz yourself on Locks, conditions and AQS Suggest a correction