Lesson · Multithreading Fundamentals
wait() and notify(): release, wait, re-check
15 min readwait(), notify(), notifyAll()
wait() gives up the monitor and parks until someone changes the condition; notify() moves a parked thread back into the queue for the lock. Every bug in this corner of the language is a violation of one clause of that protocol.
Waiting without stealing the CPU
A consumer that needs an item it does not have has three bad options: poll in a loop and burn a core, sleep for a guessed interval and add latency, or hold the lock and check forever. The third one is worse than it looks, because the thing it waits for cannot happen while it waits: the producer needs the same monitor.
That is the design problem wait() solves, and it does something no other method can: while the thread is parked, the monitor is free. The producer can enter, change the state, and wake the waiter up.
synchronized (box) { while (box.isEmpty()) { // busy-wait: still holding the monitor, so put() can never run } }
The protocol, in order
Four moves, and the order is the contract: hold the monitor, test the condition, wait while it is false, and start again from the test when wait() returns.
wait() does two things as one atomic step: it releases the monitor and parks the thread in the wait set, where its state is WAITING. notify() completes the other half: it moves one waiter from the wait set to the entry set, still BLOCKED until the notifier releases the monitor. The waiter reacquires the lock, and only then does wait() return.
The diagram below traces that round trip on a monitor ownership bar: who holds the lock at each moment, and which queue each thread sits in while it does not.
- Acquire the monitor: a synchronized block or a synchronized method.
- Test the condition. If it already holds, do the work and leave.
- If it does not hold, call wait(). The monitor is released and the thread is parked in the wait set as WAITING.
- Another thread acquires the same monitor, changes the state and calls notify() or notifyAll(), then releases. The waiter leaves the wait set, competes for the monitor in the entry set (BLOCKED), and reacquires it. Only then does wait() return.
- Re-test and repeat. Leave the loop only when the condition holds while holding the monitor.
wait and notify protocol
one waiter, one notifier, one monitor
- 1
Acquire and test
P holds the monitor and tests the condition: false. Holding the lock is what makes the check safe to act on.
- 2
wait(): release, then park
P calls wait(): the monitor is released and P moves to the wait set as WAITING. Nothing holds the lock while P is parked.
- 3
Notifier acquires and changes state
C acquires the monitor, free because wait() released it, and changes the state: the condition P was waiting for is now true.
- 4
notifyAll(): wait set to entry set
C calls notifyAll(). P leaves the wait set and lands in the entry set, BLOCKED: C still owns the monitor, so P cannot run yet.
- 5
C releases, P reacquires
C leaves the synchronized block. The monitor passes to the next contender in the entry set, which is P.
- 6
Re-check and proceed
wait() returns with the monitor held. The while loop tests the condition again, finds it true, and only then does P proceed.
The bar is the point of the protocol: phases 2 and 4 are the only moments the lock is free or about to be handed over, and both are created by methods, not by luck.
Wait in a while, never in an if
The loop is not defensive style. It is the only correct shape, and the reasons are in the specification rather than in anyone's implementation luck.
An if does something subtly different: it treats the first wakeup as proof that the condition now holds. wait() promises nothing except that the thread will run again with the monitor held.
- Spurious wakeups are permitted. wait() may return with no notify, no interrupt and no timeout. An if has already committed to a condition that nobody promised.
- One signal can wake several waiters. notifyAll wakes everyone, and the first thread to reacquire the monitor can consume the item the others were woken for.
- The state can change before you reacquire. Between the notify and your turn to run, another thread can take the item, so the wakeup arrives already stale.
Wait in a while, never in an if. The loop turns every wakeup, wanted or not, into a fresh check of the condition under the monitor.
One-slot box · wait and notifyAll
monitor owner
Inside the synchronized method right now.
wait set
Parked in wait() as WAITING: no CPU, no lock, needs a signal.
entry set
BLOCKED behind the monitor: signalled, but still queued for the lock.
buffer slot
capacity 1: null means empty, so put and take take turns.
about to call put(10)
about to call take()
Start: one slot, empty. P and C both run, and the box has a single monitor guarding the slot. Two queues come with that monitor, and they are not the same place: the wait set and the entry set.
accent = producer · violet = consumer · amber = parked or blocked · the entry set means blocked, the wait set means waiting
The signal nobody heard
notify() is not a message. It sets no flag, it cannot be queued, and with an empty wait set it does nothing at all: the signal is dropped, and the thread that later calls wait() waits for a wakeup that already happened.
The fix is ordering, and every part of it happens under the monitor: change the condition first, then notify. A waiter then either sees the changed state after it reacquires the lock, or it is already parked in the wait set when the notify arrives. There is no third possibility, because both threads run those steps with the same lock.
That is also why a boolean flag outside synchronization cannot replace wait/notify. A flag can record that something happened; a parked thread still needs a call that moves it back into the running world.
Change the state, then notify, both under the same lock. A notify that arrives before anyone waits is not stored, it is gone.
Why these methods live on Object
Every object has a monitor, so the methods that operate on a monitor are instance methods on Object: wait(), notify() and notifyAll() are declared there, final, and inherited by everything, arrays included.
Calling any of them without holding that object's monitor is a runtime error rather than a compile error: IllegalMonitorStateException is thrown at the call site, because only the object can tell whether the calling thread owns it. That is the friendliest kind of failure: it happens immediately, loudly and every time, not once in a thousand runs.
Thread.sleep is the contrast that keeps the two straight. sleep is static on Thread, it never touches a monitor, and a sleeping thread keeps every lock it holds for the whole nap. wait() is the only one of the two that gives the lock up.
| Thread.sleep(ms) | obj.wait() | |
|---|---|---|
| Declared on | Thread (static) | Object (instance, final) |
| Monitor | keeps every monitor it holds | releases its monitor, reacquires it before returning |
| Thread state | TIMED_WAITING | WAITING, or TIMED_WAITING with a timeout |
| Returns when | the timer expires | notified, interrupted, timed out, or woken spuriously |
| Must hold a lock | no | yes, or IllegalMonitorStateException |
| Interruptible | yes | yes |
sleep holds the monitor; wait releases it. That single difference is the reason wait exists at all.
notify, notifyAll, and two conditions on one monitor
notify() wakes one waiter, and which one is arbitrary: not the longest waiting, not the first in line, not the one whose condition is closest to true. With a single condition and a single waiter that is harmless. With two conditions sharing one monitor it is a trap, because the signal can land on a thread that cannot use it.
The woken thread re-tests, finds its own condition still false, and parks again, and the signal it consumed is gone. If the thread that could have made progress was never woken, both sides now sit in their wait sets and the program is deadlocked with no lock held by anyone.
notifyAll() removes the whole class of problem: every waiter wakes, re-tests, and the ones whose condition still fails go back to sleep. The price is a burst of wakeups for one item, and Condition objects remove that: one ReentrantLock can hand out several Condition instances (notFull, notEmpty) whose signal() targets exactly the waiters whose condition changed. The locks lesson covers the API; the protocol is identical.
notify() picks one thread and hopes; notifyAll() wakes everyone and lets the loops sort it out. Precision comes from Condition objects, not from a lucky notify.
Timed waits and the deadline
wait(timeout) bounds how long the thread stays parked, which is what you want when the condition may never become true. It is still a wait: the timer expiring is not evidence that the condition holds, so the loop stays, and the timeout normally exits through a break with a decision about what to do next.
Compute the deadline once, before the loop, then pass the remaining time to each call. System.nanoTime() is monotonic and is the right clock for elapsed intervals; System.currentTimeMillis() follows the wall clock, which can jump backwards on an adjustment and quietly extend or shorten the wait.
long deadline = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(500); synchronized (lock) { while (!ready) { long remaining = deadline - System.nanoTime(); if (remaining <= 0) { break; // timed out: decide what that means here } TimeUnit.NANOSECONDS.timedWait(lock, remaining); // same protocol, bounded return } }
notify() moves a thread, it does not hand over the lock
The call moves a waiter from the wait set to the entry set and returns. The notifier still owns the monitor until its synchronized block exits, so a notify followed by more work (a loop, a log line, a blocking call) keeps every woken thread parked. Change the state, notify, and leave the critical section. If you cannot leave it, the woken thread cannot run, and the handoff you thought you made has not happened yet.
Interview angles
Why must wait() be called inside a loop?+
Because a wakeup is not proof that the condition holds. Spurious wakeups are permitted by the specification, notifyAll wakes threads for each other, and the state can change again between the notify and the moment you reacquire the monitor. Loop, re-check, and wait again.
What does wait() do that sleep() does not?+
It releases the monitor. A sleeping thread keeps every lock it holds; a waiting thread lets others into the guarded region, which is the entire point of waiting for them to change something.
What is the difference between BLOCKED and WAITING?+
A BLOCKED thread is competing for a monitor in the entry set. A WAITING thread has given the monitor up and needs a notify, an interrupt or a timeout before it can even start competing again. A thread dump shows the difference in one column.
notify() or notifyAll()?+
notifyAll by default, unless every waiter waits for the same condition and exactly one of them can proceed. With two conditions on one monitor, notify can deliver the signal to the wrong waiter, which consumes it and can stall the system. Condition objects give the targeted signal without the herd.
Common misconception: notify() wakes the thread that has been waiting the longest.
Why are wait() and notify() methods on Object?+
Because they operate on a monitor, and every object has one. That is also why calling them without holding the monitor throws IllegalMonitorStateException: the monitor, not the thread, defines where a wait can legally happen.
What happens to a waiting thread when it is interrupted?+
wait() is interruptible: the thread leaves the wait set, comes back through the queue for the monitor, and then wait() throws InterruptedException with the interrupt status cleared. A caller that must keep the flag restores it with Thread.currentThread().interrupt() and lets the outer code decide.