Difficulty: Intermediate
How do wait(), notify() and notifyAll() work? Why must they be called inside synchronized, and why is wait always used in a loop?
Threads often need to coordinate, not just protect data. One thread produces work, another consumes it, and the consumer must sleep until something is available. Wait and notify are Java's built-in low-level tools for that, and interviewers use them to see if you really understand monitors.
Every Java object has a monitor, and every object also has a wait set. The three methods wait, notify and notifyAll are defined in Object, not Thread, because they operate on the object's monitor. A thread calling obj.wait() must already own that object's monitor (be inside synchronized(obj)). The call does two things atomically: it releases the monitor and puts the thread into the wait set of obj, moving it to the WAITING state. Another thread that later enters synchronized(obj) may call notify, which picks one waiting thread arbitrarily and moves it out of the wait set, or notifyAll, which wakes all of them. The notified thread does not run immediately; it must first reacquire the monitor, which is only possible after the notifier leaves its synchronized block.
Why must they be inside synchronized? Because otherwise there would be a race between checking a condition and going to sleep. Imagine the consumer sees the queue is empty, and just before it waits, the producer adds an item and calls notify; the notification is lost and the consumer sleeps forever. Holding the monitor makes the check and the wait atomic with respect to the notifier. If you call these methods without owning the monitor, you get IllegalMonitorStateException.
Why a while loop and not an if? Three reasons. Spurious wakeups: the JVM spec allows a waiting thread to wake without any notify. Multiple consumers: with notifyAll, several consumers wake up, but only the first may find an item; the rest must re-check the condition and go back to waiting. And the state might have changed between the notification and the moment the thread reacquired the lock. So the pattern is always: synchronized(lock) { while (!condition) lock.wait(); act; lock.notifyAll(); }.
Notify versus notifyAll: notify is an optimization that is only safe when all waiters are equivalent and any one can make progress. Otherwise you risk waking the wrong thread (say a producer instead of a consumer) and getting stuck. In interviews, saying prefer notifyAll unless you can prove otherwise is a safe answer.
Difference from sleep: sleep is a Thread static method, keeps holding any locks and simply waits for time to pass; wait belongs to Object, releases the monitor and waits for a notification (or a timeout). The related join is implemented using wait internally.
In practice, hand-written wait and notify code is error-prone. Prefer BlockingQueue implementations such as ArrayBlockingQueue or LinkedBlockingQueue, whose put and take handle all the coordination for you, or use Lock and Condition, which allow several separate wait sets per lock. Still, expect to write a tiny producer-consumer with wait and notify on a whiteboard.
public class Handoff {
static class Box {
private String item;
synchronized void put(String s) throws InterruptedException {
while (item != null) {
wait();
}
item = s;
notifyAll();
}
synchronized String take() throws InterruptedException {
while (item == null) {
wait();
}
String result = item;
item = null;
notifyAll();
return result;
}
}
public static void main(String[] args) throws InterruptedException {
Box box = new Box();
Thread producer = new Thread(() -> {
try {
for (String s : new String[] {"A", "B", "C"}) {
box.put(s);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
producer.start();
for (int i = 0; i < 3; i++) {
System.out.println("Got " + box.take());
}
}
}
The box holds one item. put waits while the slot is full and take waits while it is empty, each inside a while loop, and both call notifyAll after changing the state.
wait, notify, Monitor, Producer-Consumer, Spurious Wakeup