notify versus notifyAll
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)notify() wakes one waiting thread and notifyAll() wakes all of them. The choice looks small, but notify() used in the wrong place can wake a thread that cannot use the signal, and the program hangs with no error at all.
notify wakes one waiting thread, notifyAll wakes all
notify() wakes one thread from the object's wait set. The JVM chooses which one, and the Java spec makes no promise about the order.
Example 1 · notify wakes one, notifyAll wakes all
import java.util.function.BooleanSupplier;
class PassBoard { private int passes = 0; private int wakeUps = 0; private int taken = 0;
synchronized void takePass() throws InterruptedException { while (passes == 0) { wait(); wakeUps++; } passes--; taken++; }
synchronized void addPass(boolean wakeAll) { passes++; if (wakeAll) { notifyAll(); } else { notify(); } }
synchronized int wakeUps() { return wakeUps; } synchronized int taken() { return taken; }}
public class NotifyVersusNotifyAllDemo { public static void main(String[] args) throws InterruptedException { PassBoard board = new PassBoard(); Thread[] students = new Thread[3]; for (int i = 0; i < 3; i++) { students[i] = new Thread(() -> { try { board.takePass(); } catch (InterruptedException e) { return; } }, "student-" + (i + 1)); students[i].start(); } for (Thread s : students) { pauseUntil(() -> s.getState() == Thread.State.WAITING); }
board.addPass(false); // notify() pauseUntil(() -> board.taken() == 1); System.out.println("After notify(): woken " + board.wakeUps() + ", passes taken " + board.taken());
board.addPass(true); // notifyAll() pauseUntil(() -> board.taken() == 2 && board.wakeUps() == 3); System.out.println("After notifyAll(): woken " + (board.wakeUps() - 1) + ", passes taken " + (board.taken() - 1));
board.addPass(false); // last pass for (Thread s : students) { s.join(); } System.out.println("All done: total wake-ups " + board.wakeUps() + ", passes taken " + board.taken()); }
static void pauseUntil(BooleanSupplier done) throws InterruptedException { while (!done.getAsBoolean()) { Thread.sleep(5); } }}After notify(): woken 1, passes taken 1 After notifyAll(): woken 2, passes taken 1 All done: total wake-ups 4, passes taken 3
What this code does
- Three students wait for a pass.
notify()wakes exactly one of them, which takes the pass; the other two never even wake up. notifyAll()wakes both remaining students for a single pass. One takes it; the other checkspasses == 0again in itswhileloop and goes back to waiting. That wasted wake-up is the cost ofnotifyAll().pauseUntilis only there to make the demo repeatable; it is not part of the pattern.
notifyAll() wakes every thread in the wait set; they then take the lock one by one, and each checks its own condition. It is the safe default. Its cost is extra wake-ups: threads that find their condition still false go straight back to waiting.
The wrong thread woken and a program that hangs
When threads wait on one object for different conditions, notify() may wake a thread whose condition is still false. That thread waits again, and the one signal is used up. The thread that could have gone on is never woken.
Example 2 · Wrong thread woken: notify with two kinds of waiters
class Counter { private boolean ticketReady = false; private boolean refundReady = false;
synchronized void awaitTicket() throws InterruptedException { while (!ticketReady) { wait(); } }
synchronized void awaitRefund() throws InterruptedException { while (!refundReady) { wait(); } }
synchronized void ticketDone(boolean wakeAll) { ticketReady = true; if (wakeAll) { notifyAll(); } else { notify(); } }}
public class WrongThreadWokenDemo { public static void main(String[] args) throws InterruptedException { Counter counter = new Counter();
Thread refundWaiter = new Thread(() -> { try { counter.awaitRefund(); } catch (InterruptedException e) { return; } }, "refund-waiter"); Thread ticketWaiter = new Thread(() -> { try { counter.awaitTicket(); } catch (InterruptedException e) { return; } }, "ticket-waiter"); refundWaiter.setDaemon(true); ticketWaiter.setDaemon(true);
refundWaiter.start(); waitUntilWaiting(refundWaiter); ticketWaiter.start(); waitUntilWaiting(ticketWaiter);
counter.ticketDone(false); // notify(): wakes ONE waiter ticketWaiter.join(300); System.out.println("After notify(): ticket waiter done? " + !ticketWaiter.isAlive());
counter.ticketDone(true); // notifyAll(): wakes both ticketWaiter.join(); System.out.println("After notifyAll(): ticket waiter done? " + !ticketWaiter.isAlive()); System.out.println("Refund waiter still waiting? " + refundWaiter.isAlive()); }
// Demo helper only: let a thread reach wait() before going on. static void waitUntilWaiting(Thread t) throws InterruptedException { while (t.getState() != Thread.State.WAITING) { Thread.sleep(5); } }}After notify(): ticket waiter done? false After notifyAll(): ticket waiter done? true Refund waiter still waiting? true
What this code does
- Two threads wait on the same counter for different things. The ticket becomes ready and
notify()wakes one waiter, chosen by the JVM. On HotSpot it usually picks the thread that has waited longest, here the refund waiter, but the Java spec promises no order. - The refund waiter checks its own condition, finds it false and waits again. The signal meant for the ticket waiter is used up, so the ticket waiter would wait forever; the daemon flag and
join(300)only let the demo end. On a run where the JVM picks the ticket waiter, the first line saystrue, which is why such bugs come and go. notifyAll()wakes both. Each checks its own condition: the ticket waiter goes on, the refund waiter waits again. Nothing is lost.
Nothing crashes and nothing is printed: the program just stops making progress. Whether it happens depends on which thread the JVM picks, so the bug can stay hidden in testing and appear later under real load.
Missed signals
A missed signal (or lost notification) happens when notify() or notifyAll() is called before the other thread starts waiting. A notify is not stored anywhere; with nobody in the wait set, it does nothing, and a thread that waits later may sleep forever.
Example 3 · Missed signal: notify before anyone waits
public class MissedSignalDemo { private static final Object lock = new Object(); private static boolean resultsOut = false;
public static void main(String[] args) throws InterruptedException { // Broken: the waiter waits for "a notify", not for a condition. synchronized (lock) { lock.notifyAll(); // sent before anyone waits: lost } Thread broken = new Thread(() -> { synchronized (lock) { try { lock.wait(); } catch (InterruptedException e) { return; } } }, "broken-waiter"); broken.setDaemon(true); broken.start(); broken.join(300); System.out.println("Without a flag: still waiting after 300 ms? " + broken.isAlive());
// Fixed: the change is stored in a field, and the waiter checks it first. synchronized (lock) { resultsOut = true; lock.notifyAll(); } Thread fixed = new Thread(() -> { synchronized (lock) { while (!resultsOut) { try { lock.wait(); } catch (InterruptedException e) { return; } } } }, "fixed-waiter"); fixed.start(); fixed.join(); System.out.println("With a flag: waiter finished? " + !fixed.isAlive()); }}Without a flag: still waiting after 300 ms? true With a flag: waiter finished? true
What this code does
- A notify is not stored anywhere. If no thread is in the wait set at that moment, it does nothing, so the broken waiter that arrives later sleeps forever (it is a daemon thread only so the demo can end).
- The fix is to wait for a condition, not for a notify.
resultsOut(guarded bylock) remembers that the change happened, so a late waiter seestrueand never callswait()at all.
The fix is to never wait for "a notify". Store the change in shared data (a flag, a counter or a queue), and wait only while that data says "not yet". A late thread then sees the stored change and never calls wait().
Spurious wakeups
A spurious wakeup is a return from wait() with no notify(), notifyAll(), timeout or interrupt behind it. The Java spec allows it because some operating systems can do it. It is rare, but correct code must not break when it happens.
Example 4 · Unexpected wake-ups: if reads stale data, while is safe
import java.util.function.BooleanSupplier;
class TicketDesk { private String ticket; private int wakeUps = 0;
synchronized String awaitWithIf() throws InterruptedException { if (ticket == null) { wait(); wakeUps++; } return ticket; }
synchronized String awaitWithWhile() throws InterruptedException { while (ticket == null) { wait(); wakeUps++; } return ticket; }
synchronized void ping() { notifyAll(); }
synchronized void issue(String t) { ticket = t; notifyAll(); }
synchronized int wakeUps() { return wakeUps; }}
public class UnexpectedWakeUpDemo { static void run(String label, boolean useWhile) throws InterruptedException { TicketDesk desk = new TicketDesk(); String[] got = new String[1]; Thread student = new Thread(() -> { try { got[0] = useWhile ? desk.awaitWithWhile() : desk.awaitWithIf(); } catch (InterruptedException e) { got[0] = "interrupted"; } }, "student"); student.start();
pauseUntil(() -> student.getState() == Thread.State.WAITING); desk.ping(); // wake-up 1: no ticket yet pauseUntil(() -> desk.wakeUps() == 1); if (useWhile) { desk.ping(); // wake-up 2: still no ticket pauseUntil(() -> desk.wakeUps() == 2); desk.issue("Hall ticket A-117"); // wake-up 3: the real one } student.join(); System.out.println(label + "read " + got[0] + " after " + desk.wakeUps() + " wake-up(s)"); }
static void pauseUntil(BooleanSupplier done) throws InterruptedException { while (!done.getAsBoolean()) { Thread.sleep(5); } }
public static void main(String[] args) throws InterruptedException { run("With if: ", false); run("With while: ", true); }}With if: read null after 1 wake-up(s) With while: read Hall ticket A-117 after 3 wake-up(s)
What this code does
ping()wakes the student although no ticket was issued. To the student, that looks exactly like a spurious wakeup:wait()returned and the condition is still false.- With
if, the student goes on after the first wake-up and returnsnull(the ticket staysnulluntil it is issued), a bug that could crash the caller much later. Withwhile, it checks again, waits again twice, and returns the real ticket.pauseUntilonly keeps the output the same on every run.
A notifyAll() sent for some other reason looks the same to a waiting thread: it wakes up and its condition is still false. The while (!condition) wait(); loop handles both cases.
Choosing between notify and notifyAll
Use notifyAll() unless all of the points below are true; then notify() is safe and avoids extra wake-ups.
Example 5 · Using notify safely: identical riders, one order each
import java.util.ArrayDeque;import java.util.ArrayList;import java.util.Collections;import java.util.List;import java.util.Queue;
class OrderBoard { private final Queue<String> orders = new ArrayDeque<>(); private final List<String> delivered = new ArrayList<>();
synchronized void addOrder(String id) { orders.add(id); notify(); // one new order: one rider is enough }
synchronized void deliverOne() throws InterruptedException { while (orders.isEmpty()) { wait(); } delivered.add(orders.remove()); }
synchronized List<String> delivered() { List<String> copy = new ArrayList<>(delivered); Collections.sort(copy); return copy; }}
public class SafeNotifyDemo { public static void main(String[] args) throws InterruptedException { OrderBoard board = new OrderBoard(); Thread[] riders = new Thread[3]; for (int i = 0; i < 3; i++) { String name = "rider-" + (i + 1); riders[i] = new Thread(() -> { try { board.deliverOne(); board.deliverOne(); // every rider delivers exactly 2 orders } catch (InterruptedException e) { return; } }, name); riders[i].start(); }
for (int n = 1; n <= 6; n++) { board.addOrder("ORD-" + n); } for (Thread r : riders) { r.join(); } System.out.println("Delivered: " + board.delivered()); }}Delivered: [ORD-1, ORD-2, ORD-3, ORD-4, ORD-5, ORD-6]
What this code does
- Here
notify()is safe: every waiter waits for the same condition (an order in the queue), any rider can handle any order, and each new order lets exactly one rider go on. - Even a notify sent while all riders are busy is harmless, because the order stays in the queue and the next rider sees it before it calls
wait(). The queue is the stored condition that prevents missed signals.
- Every waiting thread waits for the same condition.
- Any one waiting thread can handle the change.
- Each change lets at most one waiting thread go on, such as one new item in a queue.
- If you are unsure, use
notifyAll(). The Locks module showsConditionobjects, which give each kind of waiter its own wait set.
Next step
Check your understanding
12 quick questions