Java Concurrency Interview

Locks, conditions and AQS question 39 of 180 mid

What does Condition give you that wait/notify does not?

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.

locks condition

Quiz yourself on Locks, conditions and AQS Suggest a correction