Video in progress

Strong Middle 🧵 Concurrency

How does Condition differ from wait/notify, and what do multiple Conditions on one lock give you?

Condition gives one lock several wait queues and works with ReentrantLock, while wait/notify gives a monitor a single queue. The condition is checked in a while loop, because of spurious wakeups and because another thread can break the condition again.

📖 Answer

A classic bounded buffer has two kinds of waiting: for "space to free up" and for "an item to arrive". With wait/notify both share one queue, so notifyAll() wakes everyone and most of them go back to waiting for nothing. With Condition they're separated:

private final Lock lock = new ReentrantLock();
private final Condition notFull = lock.newCondition();
private final Condition notEmpty = lock.newCondition();

public void put(T item) throws InterruptedException {
    lock.lock();
    try {
        while (queue.size() == capacity) {
            notFull.await();          // only producers wait here
        }
        queue.add(item);
        notEmpty.signal();            // wake only a consumer
    } finally {
        lock.unlock();
    }
}

Why while and not if:

  • spurious wakeup: the JVM and the OS may wake a thread without any signal, and the spec says so openly;
  • before the woken thread reacquires the lock, another thread can get in and break the condition again.

Code written with if works in tests, but in prod under load it gives you an IndexOutOfBounds or an overfilled buffer.

Other differences: Condition.await has a variant that ignores interrupts (awaitUninterruptibly) and one with an exact deadline (awaitUntil). wait(), on the other hand, can only be called inside synchronized, otherwise you get IllegalMonitorStateException.