Sub topic 16
Coordinating Threads with wait and notifyAll
So far, locks have kept threads from getting in each other's way. Sometimes threads also need to work together. One thread has to wait until another thread has done something. This chapter shows how Java threads wait for each other using wait, notify, and notifyAll.
Why threads need to wait for each other
Picture a bakery with one shelf that holds a single cake. The baker puts a cake on the shelf. A customer takes it. The baker cannot add a cake while the shelf is full. The customer cannot take a cake while the shelf is empty.
In code, the baker is a producer, a thread that makes data. The customer is a consumer, a thread that uses data. The shelf is shared state. Each thread has to wait until a condition, a true-or-false fact about the shared state, becomes true. For the baker, the condition is "the shelf is empty." For the customer, it is "the shelf has a cake."
The wrong way: busy waiting
A first attempt might loop and check the condition over and over:
public class BusyShelf {
private volatile String cake;
public void takeBusy() {
while (cake == null) {
// spin and check again
}
cake = null;
}
}This is called busy waiting. The thread keeps the CPU busy and does no useful work. It also has a race: two customers could both see a cake and both take it. We need a way to sleep until the condition might have changed, and we need to stay safe while we check it.
The three methods
Every Java object has these methods, inherited from Object:
| Method | What it does |
|---|---|
| `wait()` | Releases the object's lock and puts the thread to sleep until another thread wakes it. |
| `notify()` | Wakes one thread that is waiting on this object. You cannot choose which one. |
| `notifyAll()` | Wakes every thread that is waiting on this object. |
They work with the object's intrinsic lock, the built-in lock that synchronized uses. There is one firm rule: you must hold the object's lock when you call any of these methods. If you don't, Java throws IllegalMonitorStateException.
The guarded-wait pattern
Here is a one-item shelf that any type of item can go on:
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;
}
}Each method follows the same steps, known as the guarded-wait pattern:
- Take the lock. Here,
synchronizedon the method does it. - Check the condition in a
whileloop. - If the condition is false, call
wait(). - When the condition is true, change the state.
- Call
notifyAll()so waiting threads can check again.
Why the check must be a while loop
Beginners often write if (item == null) wait();. That looks fine, but it is a bug. The loop is needed for three reasons.
- Spurious wakeups. A spurious wakeup happens when a thread returns from
wait()even though no one called notify. The Java documentation allows this. The loop checks again and goes back to sleep. - Another thread got there first. Say two consumers are waiting and one item arrives.
notifyAll()wakes both. The first one takes the item. When the second one gets the lock, the slot is empty again. Withif, it would takenull. - Mixed waiters. With
notifyAll(), producers and consumers both wake up. A producer woken by another producer must see that the slot is still full and wait again.
notify versus notifyAll
notify() wakes only one waiting thread, and Java picks which. In SingleSlot, producers and consumers wait on the same object. Suppose a consumer takes the item and calls notify(), and Java wakes another consumer instead of a producer. That consumer sees an empty slot and waits again. The producer stays asleep. Every thread can end up waiting forever.
notifyAll() avoids this because every waiter wakes up and checks its own condition. It costs a bit more, but it is correct. As a beginner, use notifyAll(). Use notify() only when every waiter waits for the same condition and any one of them can do the work.
A complete runnable example
Put this in SlotDemo.java next to SingleSlot.java:
public class SlotDemo {
public static void main(String[] args) throws InterruptedException {
SingleSlot<Integer> slot = new SingleSlot<>();
Thread producer = new Thread(() -> {
try {
for (int i = 1; i <= 5; i++) {
slot.put(i);
System.out.println("Put " + i);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
Thread consumer = new Thread(() -> {
try {
for (int i = 1; i <= 5; i++) {
int value = slot.take();
System.out.println("Took " + value);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
producer.start();
consumer.start();
producer.join();
consumer.join();
System.out.println("Done");
}
}Compile and run it with javac SingleSlot.java SlotDemo.java and then java SlotDemo. The "Put" and "Took" lines may come out in a different order on each run, because println happens outside the lock. Even so, the consumer always gets 1, 2, 3, 4, 5 in order, and no item is lost or taken twice.
Handling InterruptedException
wait() can throw InterruptedException. An interrupt is a polite request from one thread asking another thread to stop what it is doing. If a thread is interrupted while it waits, wait() throws instead of returning.
SingleSlot passes the exception on to its caller by declaring throws InterruptedException. The demo catches it and calls Thread.currentThread().interrupt(). That sets the interrupt flag again, so code further up can still see that a stop was requested. Don't catch the exception and ignore it.
Common mistakes
| Mistake | What goes wrong | Fix |
|---|---|---|
| Calling `wait()` without the lock | `IllegalMonitorStateException` | Call it inside `synchronized` on the same object |
| Waiting on one object, notifying another | Waiters never wake | Use the same object for both |
| `if` instead of `while` | Acts on a false condition | Always loop |
| Using `notify()` with mixed waiters | Threads can sleep forever | Use `notifyAll()` |
| Changing state without notifying | Waiters sleep forever | Call `notifyAll()` after every state change |
Exercises
Exercise
Why does wait() release the lock while the thread sleeps?
Show answer
If the waiting thread kept the lock, no other thread could enter a synchronized method to change the state, so the condition could never become true and the program would freeze.
Exercise
Two consumers wait in take() on an empty SingleSlot. A producer puts one item and calls notifyAll(). What happens to each consumer, and why does the while loop matter?
Show answer
Both wake up. One gets the lock first, sees the item, takes it, and sets the slot to null. The second then gets the lock, and the while loop finds the slot empty again, so it calls wait() again. With an if, it would return null.
Exercise
What happens if you call slot.notifyAll() from a method that is not synchronized on slot?
Show answer
Java throws IllegalMonitorStateException, because the thread does not hold the slot's intrinsic lock.
Exercise
Change SingleSlot so put() uses notify() instead of notifyAll(). Describe a case with two producers and one consumer where a thread can wait forever.
Show answer
The slot is full and both producers are waiting. The consumer takes the item and calls notifyAll(), and producer A puts an item and calls notify(). If that notify wakes producer B instead of a waiting consumer, B sees a full slot and waits again. Now the consumer that later calls take() works, but in runs where the consumer is already waiting, the one wake-up signal can go to the wrong thread, and nobody is left to wake the consumer. Using notifyAll() wakes every waiter, so the right one always gets a chance.