wait and notify
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)wait(), notify() and notifyAll() let a thread sleep until another thread changes some shared data and tells it so. They are methods of Object, they work together with synchronized, and four rules decide whether code that uses them is correct.
wait() must be called while holding the lock
wait makes a thread release a lock and sleep until another thread calls notify or notifyAll on the same object; both must be called while holding that lock.
wait() puts the current thread to sleep until another thread calls notify() or notifyAll() on the same object. You may call it only while you hold that object's lock, that is, inside synchronized (obj) or inside a synchronized method of obj.
Example 1 · wait and notifyAll on one lock object
public class ResultWaitDemo { private static final Object lock = new Object(); private static String result = null;
public static void main(String[] args) throws InterruptedException { Thread student = new Thread(() -> { synchronized (lock) { while (result == null) { try { lock.wait(); // sleep until someone calls lock.notifyAll() } catch (InterruptedException e) { return; } } System.out.println("Student: my result is " + result); } }, "student");
Thread server = new Thread(() -> { try { Thread.sleep(100); // results take time to process } catch (InterruptedException e) { return; } synchronized (lock) { result = "Roll 21: 88/100"; System.out.println("Server: results published"); lock.notifyAll(); // wake everyone waiting on lock } }, "server");
student.start(); server.start(); student.join(); server.join(); }}Server: results published Student: my result is Roll 21: 88/100
What this code does
- Both threads lock the same object,
lock, and the student callslock.wait()on that same object. The fieldresultis the condition:nullmeans "not yet". - The server changes
resultand callslock.notifyAll()while holding the lock. The student wakes, takes the lock back, findsresultset and leaves the loop. - The order of the two lines is fixed: the student can read the result only after the server's
synchronizedblock has finished, and the server prints inside that block.
- Lock an object, check the condition, and call
wait()on that same object. - Change the shared data and call
notifyAll()while holding that same lock. - The waiting side and the changing side must use one and the same object.
All three are methods of Object, so any object can be the meeting point. Each object has a wait set: the threads currently waiting on it. notifyAll() wakes every thread in the wait set; notify() wakes just one (the next lesson compares them).
IllegalMonitorStateException
IllegalMonitorStateException is the runtime exception Java throws when a thread calls wait, notify or notifyAll on an object whose lock it does not hold. A lock is also called a monitor, which is where the name comes from.
Example 2 · IllegalMonitorStateException: three ways to get it
public class IllegalMonitorDemo { public static void main(String[] args) { Object lock = new Object(); Object other = new Object();
try { lock.wait(); // no lock held at all } catch (IllegalMonitorStateException | InterruptedException e) { System.out.println("1. wait without the lock: " + e); }
try { lock.notifyAll(); // no lock held at all } catch (IllegalMonitorStateException e) { System.out.println("2. notifyAll without the lock: " + e); }
synchronized (lock) { try { other.notify(); // holds lock, not other } catch (IllegalMonitorStateException e) { System.out.println("3. notify on a different object: " + e); } lock.notifyAll(); System.out.println("4. notifyAll on the locked object: OK"); } }}1. wait without the lock: java.lang.IllegalMonitorStateException: current thread is not owner 2. notifyAll without the lock: java.lang.IllegalMonitorStateException: current thread is not owner 3. notify on a different object: java.lang.IllegalMonitorStateException: current thread is not owner 4. notifyAll on the locked object: OK
What this code does
- All three mistakes compile. Java checks at run time whether the current thread owns the object's lock, and throws
IllegalMonitorStateExceptionif it does not. On Java 17 and 21 the message is "current thread is not owner". - Case 3 is the sneaky one: the thread holds a lock, just not the lock of the object it calls
notify()on. The lock you hold and the object you callwait/notifyon must be the same object. - Calling
notifyAll()when nobody is waiting is allowed and does nothing (case 4).
- Calling
wait()ornotifyAll()with nosynchronizedaround it. - Holding one lock and calling
notify()on another object. - Writing plain
wait()insidesynchronized (lock)in a normal method: plainwait()meansthis.wait(), notlock.wait().
The compiler cannot catch this mistake, so the code compiles and fails only when that line runs.
wait() releases the lock, sleep() does not
When a thread calls wait(), it releases the lock of that object and sleeps. Before wait() returns, the woken thread must take the lock back, so it may sit in the BLOCKED state for a while.
Example 3 · sleep keeps the lock, wait releases it
public class SleepVersusWaitDemo { private static final Object lock = new Object(); private static boolean aLeft; private static boolean bDone;
static void sleepVersion() throws InterruptedException { aLeft = false; Thread b = new Thread(() -> { synchronized (lock) { System.out.println(" B got the lock. Has A left its block? " + aLeft); } }, "B"); Thread a = new Thread(() -> { synchronized (lock) { b.start(); try { Thread.sleep(100); // sleeps WITH the lock } catch (InterruptedException e) { return; } System.out.println(" A woke from sleep, still holding the lock"); aLeft = true; } }, "A"); a.start(); a.join(); b.join(); }
static void waitVersion() throws InterruptedException { aLeft = false; bDone = false; Thread b = new Thread(() -> { synchronized (lock) { System.out.println(" B got the lock. Has A left its block? " + aLeft); bDone = true; lock.notifyAll(); } }, "B"); Thread a = new Thread(() -> { synchronized (lock) { b.start(); try { while (!bDone) { lock.wait(); // releases the lock while waiting } } catch (InterruptedException e) { return; } System.out.println(" A woke from wait and has the lock again"); aLeft = true; } }, "A"); a.start(); a.join(); b.join(); }
public static void main(String[] args) throws InterruptedException { System.out.println("With sleep:"); sleepVersion(); System.out.println("With wait:"); waitVersion(); }}With sleep: A woke from sleep, still holding the lock B got the lock. Has A left its block? true With wait: B got the lock. Has A left its block? false A woke from wait and has the lock again
What this code does
- In both versions A takes the lock first and starts B from inside its block, so B always has to fight A for the lock.
- With
sleep, A keeps the lock for the whole 100 ms, so B gets in only after A has left its block. Withwait, A gives the lock away, B gets in while A is still inside its block, and A continues only after B has finished and released the lock.
Example 4 · notifyAll does not hand over the lock at once
public class NotifyKeepsLockDemo { private static final Object lock = new Object(); private static boolean ready = false; // guarded by lock
public static void main(String[] args) throws InterruptedException { Thread waiter = new Thread(() -> { synchronized (lock) { while (!ready) { try { lock.wait(); } catch (InterruptedException e) { return; } } System.out.println("Waiter: running again"); } }, "waiter");
Thread notifier = new Thread(() -> { try { Thread.sleep(50); } catch (InterruptedException e) { return; } synchronized (lock) { ready = true; lock.notifyAll(); System.out.println("Notifier: called notifyAll, still inside the block"); try { Thread.sleep(100); // still holding the lock } catch (InterruptedException e) { return; } System.out.println("Notifier: leaving the block"); } }, "notifier");
waiter.start(); notifier.start(); waiter.join(); notifier.join(); }}Notifier: called notifyAll, still inside the block Notifier: leaving the block Waiter: running again
What this code does
notifyAll()only marks the waiting threads as ready to run. They still need the lock, and the notifier keeps it until the end of itssynchronizedblock.- So the waiter prints its line only after
Notifier: leaving the block, 100 ms later. Keep the code afternotifyAll()short, or move it outside the block.
notify() and notifyAll() do not release the lock either: the woken threads run only after the notifying thread leaves its synchronized block. Thread.sleep() also pauses a thread, but it keeps every lock the thread holds.
wait(): a method ofObject, needs the lock, releases it while waiting, ends on a notify, a timeout or an interrupt.Thread.sleep(ms): a static method ofThread, needs no lock, keeps any lock it holds, ends when the time is up or on an interrupt.wait(ms)is the timed version ofwait(): it also returns when the time is up, with no notify.- Both throw the checked
InterruptedExceptionif the thread is interrupted while it sleeps or waits.
Always wait inside a while loop
Always call wait() inside while (!condition), never inside if. When a thread wakes up, the condition it waited for may be false again, and the loop makes it check before it goes on.
Example 5 · if versus while: one seat, two bookers
class SeatCounter { private int seats = 0; private int booked = 0;
synchronized void bookWithIf() throws InterruptedException { if (seats == 0) { // checked only once wait(); } seats--; booked++; notifyAll(); }
synchronized void bookWithWhile() throws InterruptedException { while (seats == 0) { // checked again after every wake-up wait(); } seats--; booked++; notifyAll(); }
synchronized void release() { seats++; notifyAll(); }
synchronized void awaitBooked(int n) throws InterruptedException { while (booked < n) { wait(); } }
synchronized String report() { return "booked " + booked + ", seats left " + seats; }}
public class IfVersusWhileDemo { static void run(String label, boolean useWhile) throws InterruptedException { SeatCounter hall = new SeatCounter(); boolean[] gaveUp = new boolean[2]; Thread[] bookers = new Thread[2]; for (int i = 0; i < 2; i++) { int idx = i; bookers[i] = new Thread(() -> { try { if (useWhile) { hall.bookWithWhile(); } else { hall.bookWithIf(); } } catch (InterruptedException e) { gaveUp[idx] = true; } }, "booker-" + (i + 1)); bookers[i].start(); }
waitUntilWaiting(bookers); hall.release(); // one cancelled seat comes back if (useWhile) { hall.awaitBooked(1); for (Thread t : bookers) { t.interrupt(); } } for (Thread t : bookers) { t.join(); } int stopped = (gaveUp[0] ? 1 : 0) + (gaveUp[1] ? 1 : 0); System.out.println(label + hall.report() + ", gave up " + stopped); }
static void waitUntilWaiting(Thread[] threads) throws InterruptedException { for (Thread t : threads) { while (t.getState() != Thread.State.WAITING) { Thread.sleep(5); } } }
public static void main(String[] args) throws InterruptedException { run("With if: ", false); run("With while: ", true); }}With if: booked 2, seats left -1, gave up 0 With while: booked 1, seats left 0, gave up 1
What this code does
- Both bookers wait for a seat.
release()adds one seat and callsnotifyAll(), which wakes both of them, but only one can have it. - With
if, each woken booker goes straight toseats--without checking again, so both book and the hall ends at -1 seats. Withwhile, the second booker checks again, sees 0 seats and goes back to waiting; main then interrupts it so the program can end. waitUntilWaitingonly makes the demo repeatable by starting the release after both bookers are asleep. Real code never needs it.
- Another thread may get the lock first and use up what you were woken for, such as the last seat.
notifyAll()also wakes threads that wait for other conditions.- The Java spec allows a thread to wake up with no notify at all (a spurious wakeup, covered in the next lesson).
Find the bug
Find the wait and notify bug
Click the line that is wrong in each snippet.
Wait until an item is available.
Round 1 of 4wait() again. while does that for free; if lets a thread act on something that is no longer true.Next step
Check your understanding
12 quick questions