Video in progress

Strong Junior 🧵 Concurrency

Why should you always call wait() inside a while loop, not an if?

A thread can wake up even without a notify (a spurious wakeup), or by the time it wakes up, another thread has already changed the condition. while re-checks the condition after waking up.

📖 Answer

A simple bounded buffer:

class Buffer<T> {
    private final Deque<T> items = new ArrayDeque<>();
    private final int capacity = 10;

    public synchronized void put(T item) throws InterruptedException {
        while (items.size() == capacity) {
            wait();
        }
        items.addLast(item);
        notifyAll();
    }

    public synchronized T take() throws InterruptedException {
        while (items.isEmpty()) {
            wait();
        }
        T item = items.removeFirst();
        notifyAll();
        return item;
    }
}

What happens with if: two consumers are sitting in wait(), and a producer puts in one element and calls notifyAll(). Both wake up. The first takes the element, and when the second gets the monitor the queue is empty again, but if doesn't re-check, and removeFirst() throws a NoSuchElementException.

Why notifyAll() and not notify(): both producers and consumers are waiting on the same monitor. If notify() wakes a thread of the wrong kind, everyone can end up asleep.

You need to know this code to learn the topic, but on prod ArrayBlockingQueue is ready-made and battle-tested.