Skip to content
Tutorials Center
My learning

Topics

Lesson 128 of 201 ยท Concurrency

Inter-Thread Communication: wait and notify

Learn how Java threads cooperate with wait, notify and notifyAll - the guarded-block pattern, a producer-consumer buffer, spurious wakeups and common mistakes.

Synchronization stops threads from trampling on each other's data. But threads often need more than mutual exclusion: they need to wait for each other. A consumer must wait until there's something to consume; a producer must wait until there's room; a worker must wait until its configuration has loaded.

Waiting by checking a flag in a loop (while (!ready) { }) burns a CPU core doing nothing, and sleeping between checks makes the program slow to react. Java's built-in answer is a trio of methods on Object: wait(), notify() and notifyAll(). They let a thread sleep efficiently until another thread tells it that something has changed.

These methods are low-level, and most modern code uses the higher-level tools built on the same idea (BlockingQueue, CountDownLatch, Condition). But they're the foundation of all of them, they appear constantly in interviews and older code, and understanding them makes the rest of the concurrency chapter easy.

The three methods

All three are final methods of Object, so every object can be used to coordinate threads. They work together with that object's monitor (its intrinsic lock):

Method What it does
wait() releases the monitor and puts the current thread to sleep (WAITING) until it's notified or interrupted, then re-acquires the monitor before returning
wait(millis) the same, but also wakes up after the timeout (TIMED_WAITING)
notify() wakes one thread waiting on this object (which one is unspecified)
notifyAll() wakes all threads waiting on this object

The key rule: you may call these methods only while holding the object's monitor, that is, inside synchronized (obj) or a synchronized method of obj. Otherwise you get an exception:

Java wait() needs the monitor

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The first call fails on purpose with IllegalMonitorStateException. The requirement isn't arbitrary: the waiting thread must check a condition and go to sleep atomically, and the notifying thread must change the condition under the same lock. Without the lock, a notification could slip in between the check and the wait and be lost forever.

The guarded-block pattern

Every correct use of wait follows the same shape, called a guarded block: hold the lock, and while the condition you need is false, wait. The thread that changes the condition does so under the same lock and then notifies.

Java
// Waiting side
synchronized (lock) {
    while (!conditionHolds()) {     // ALWAYS a loop, never an if
        lock.wait();
    }
    // the condition is true here, and we hold the lock
    doTheWork();
}

// Signaling side
synchronized (lock) {
    changeTheState();               // make the condition true
    lock.notifyAll();
}

Here it is with a real condition. A worker can't start until the configuration is loaded:

Java Waiting until a condition becomes true

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Notice the worker calls a synchronized method and then wait() inside it, but publish can still enter a synchronized method on the same object. That's because wait() releases the monitor while the thread sleeps. When the worker is notified, it moves to BLOCKED until it can take the monitor back, and only then does wait() return. That's why the condition is still guarded when the loop re-checks it.

Why while and not if

Using if (condition) wait(); instead of while is the classic bug. There are three reasons a thread can wake up while the condition is still (or again) false:

  1. Another thread got there first. With notifyAll, all waiters wake up, but only one may find the item it was waiting for.
  2. The notification was for a different condition. Producers and consumers often wait on the same object for opposite conditions.
  3. Spurious wakeups. The specification allows wait() to return even though nobody called notify, because some operating systems' primitives behave that way. They are rare, but legal.

This example puts two consumers to sleep on an empty queue, then adds one item and calls notifyAll(). Both wake; only one gets the item:

Java if versus while after waking up

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

With if, the reader that loses the race doesn't re-check the condition and calls removeFirst() on an empty deque. With while, it notices the mailbox is empty, goes back to sleep, and later receives the second message. Which reader wins varies between runs; the outcome doesn't.

Producer-consumer with a bounded buffer

The most famous use of wait/notify is a bounded buffer: producers add items, consumers remove them, producers wait when it's full and consumers wait when it's empty. It smooths out speed differences between the two sides while keeping memory use capped.

Java A bounded buffer with wait and notifyAll

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Because the consumer is slower, the producer fills the buffer, then has to wait, and from then on the two sides alternate. The exact interleaving of the "produced" and "consumed" lines varies between runs, but two things are guaranteed: there are never more than 3 orders in the buffer, and the consumer receives them in exactly the order they were produced.

The poison pill (DONE) is a common way to tell a consumer that no more items will come. With several consumers, the producer sends one pill per consumer.

notify or notifyAll?

notify() wakes just one waiter, which sounds more efficient. But in the buffer above, producers and consumers wait on the same object for different conditions. If a consumer's notify() happens to wake another consumer instead of a waiting producer, that consumer re-checks, finds the buffer still empty, and waits again; the producer that could make progress keeps sleeping, and with unlucky timing every thread ends up waiting forever.

The safe default is notifyAll(). Use notify() only when all of these hold:

  • all waiting threads wait for the same condition,
  • any one of them can handle the change, and
  • each notification lets at most one thread proceed.

notifyAll costs some extra wakeups. If that matters, the real solution is ReentrantLock with separate Condition objects for "not full" and "not empty", so each signal reaches the right kind of thread (Locks and Conditions).

Waiting with a timeout

wait(millis) returns when notified or when the time is up, and it doesn't tell you which. To wait for a condition with a deadline, keep track of the remaining time yourself:

Java Waiting for a result with a deadline

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The first call gets its answer; the second gives up after 300 ms. Recomputing the remaining time on every loop matters: after a spurious or irrelevant wakeup, waiting the full timeout again would stretch the deadline.

Rules and pitfalls

  • Always hold the monitor of the object you call wait/notify on, and change the condition under that same lock.
  • Always wait in a while loop that re-checks the condition.
  • Prefer notifyAll() unless you've proven notify() is safe.
  • Notify after changing the state, never instead of it. A notification is not stored: if no thread is waiting at that moment, it's simply lost. The guarded state (the flag, the queue) is what remembers that something happened, which is another reason the waiter must check the condition before waiting.
  • wait() releases only the monitor of the object it's called on. If the thread holds other locks, it keeps them while sleeping, which can easily cause a deadlock.
  • Don't wait on objects you don't control, like a Thread object (the JVM uses notifyAll on threads internally for join) or a shared string.
  • Handle InterruptedException: wait() throws it if the thread is interrupted, just like sleep() (Thread Lifecycle).

Modern alternatives

You'll rarely need to write a buffer like the one above in new code. The JDK has battle-tested versions:

Instead of hand-written... Use
a bounded producer-consumer buffer ArrayBlockingQueue / LinkedBlockingQueue (put and take block for you)
"wait until N things have happened" CountDownLatch
"wait until a result is ready" CompletableFuture / Future.get(timeout)
multiple conditions on one lock ReentrantLock + Condition
Java
BlockingQueue<String> queue = new ArrayBlockingQueue<>(3);
queue.put("order-1");                 // blocks while full
String next = queue.take();           // blocks while empty

They're covered in Concurrent Collections, CountDownLatch, CyclicBarrier, Semaphore and Phaser and CompletableFuture.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What happens when a thread calls obj.wait() without holding obj's monitor?

    wait, notify and notifyAll require the caller to own the object's monitor, so they must be called inside synchronized (obj) or a synchronized method of obj.
  2. 2. Why must wait() be called inside a while loop that re-checks the condition?

    Waking up only means something may have changed. The thread must re-check the condition under the lock before continuing.
  3. 3. Thread A is inside synchronized (lock) { lock.wait(); }. Can thread B enter synchronized (lock) while A is waiting?

    wait() releases the monitor so other threads can change the state and notify. Before wait() returns, A must re-acquire the monitor.
  4. 4. A thread calls notify() on an object, but no thread is waiting on it yet. A second later another thread calls wait() on that object. What happens?

    Notifications are not remembered. That is why the waiter must check a shared condition before waiting, and the signaler must update that condition before notifying.
  5. 5. In a bounded buffer where producers and consumers wait on the same object, why is notifyAll() safer than notify()?

    Producers and consumers wait for different conditions on one monitor. notifyAll wakes everyone, and each re-checks its own condition, so no signal is wasted on the wrong side.

Summary

  • wait(), notify() and notifyAll() let threads sleep until another thread signals a change; they must be called while holding the object's monitor.
  • wait() releases the monitor while sleeping and re-acquires it before returning; a notified thread is BLOCKED until it gets the lock back.
  • Use the guarded-block pattern: change state then notify under the lock, and wait in a while loop that re-checks the condition.
  • Wakeups can be spurious or meant for someone else, and notifications are not stored.
  • Prefer notifyAll(); for producer-consumer, a bounded buffer with two conditions (full, empty) is the classic example.
  • wait(ms) doesn't say whether it timed out; track the deadline yourself.
  • In new code, prefer BlockingQueue, CountDownLatch, CompletableFuture or Condition.

Next: Deadlocks, Livelocks and Starvation, where you'll see what happens when threads wait for each other forever, and how to prevent it.