Sub topic 16
Coordinating Threads with wait and notifyAll
Sometimes one thread must wait for another. A consumer thread is a thread that takes data. It cannot take an item until a producer thread, a thread that makes data, has put one in place. Java lets threads wait for each other on an intrinsic lock using three methods: wait, notify, and notifyAll.
The three methods
Every Java object has these methods. You may only call them while you hold that object's lock, which means inside a synchronized method or block on that object.
| Method | What it does |
|---|---|
| `wait()` | Releases the lock and pauses the thread until another thread wakes it |
| `notify()` | Wakes one waiting thread, chosen by the JVM |
| `notifyAll()` | Wakes every waiting thread |
A woken thread does not run at once. It must first get the lock back.
A one-item slot
A guarded wait is a wait that only happens while a condition is false. Here a slot holds at most one item. put waits while the slot is full. take waits while it is empty.
public class SingleSlot<T> {
private T item;
public synchronized void put(T value) throws InterruptedException {
while (item != null) {
wait();
}
item = value;
notifyAll();
}
public synchronized T take() throws InterruptedException {
while (item == null) {
wait();
}
T value = item;
item = null;
notifyAll();
return value;
}
public static void main(String[] args) throws InterruptedException {
SingleSlot<Integer> slot = new SingleSlot<>();
Thread producer = new Thread(() -> {
try {
for (int i = 1; i <= 3; i++) {
slot.put(i);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
producer.start();
for (int i = 0; i < 3; i++) {
System.out.println("Took " + slot.take());
}
producer.join();
}
}The program prints Took 1, Took 2, and Took 3. The producer never overwrites an item that has not been taken yet.
Two rules to follow
- Always wait in a
whileloop, never anif. A thread can wake up even when the condition is still false. This is called a spurious wakeup. Another thread may also grab the item first. The loop checks the condition again after every wakeup. - Prefer
notifyAllovernotify. In this slot, producers and consumers wait on the same lock.notifymight wake the wrong kind of thread, and then every thread could end up waiting forever.notifyAllwakes them all, and each one checks its own condition.
Exercise
Why does take() use "while (item == null)" instead of "if (item == null)" before calling wait()?
Show answer
A thread can wake up while the slot is still empty, either from a spurious wakeup or because another consumer took the item first. The while loop checks the condition again after every wakeup, so take() never returns a null item.
Exercise
What happens to the lock when a thread calls wait()?
Show answer
The thread releases the lock while it waits, so other threads can enter synchronized code on that object. When it wakes, it must get the lock back before it continues.