skip to content

How do a Java monitor's entry set and wait set differ, and what lost wakeup does requiring the monitor for wait() and notify() prevent?

level: middleimportance: should knowfreq 45%

answer

  1. wanting the lock versus gave it up
  2. joined first, unlocked second
  3. notifications are not stored
  4. the check and the wait share one hold

basics

~20 s

The entry set holds threads blocked acquiring the monitor; the wait set holds threads that released it via wait(). Requiring the monitor lets a waiter check its condition and enter wait() under one hold, so no notify() can slip between and vanish.

solid answer

~50 s

The entry set is the threads blocked trying to lock the monitor, for `synchronized` or to relock after `wait()`; `Thread.getState()` shows them `BLOCKED`, and they compete whenever the lock is free. The wait set, which JLS §17.2 gives every object, holds threads that called `wait()`, joined the set and released the lock; they show `WAITING` or `TIMED_WAITING` and do not compete until `notify()`, `notifyAll()`, an interrupt, a timeout or a spurious wakeup removes them. The lost wakeup: a waiter sees its condition false, a notifier changes it and calls `notify()` on an empty wait set, which does nothing, then the waiter sleeps with no notification left to wake it. Requiring the monitor closes that window, because the notifier cannot run between a check and a `wait()` made under one hold. A check made outside the `synchronized` block still loses the wakeup.

code

java · 56 lines
java
public class LostWakeupDemo {
    private static final Object lock = new Object();
    private static boolean ready;

    // Broken: compiles, never throws, and misses a notify sent during the window.
    static void brokenAwait() throws InterruptedException {
        if (!ready) {               // checked without the monitor
            Thread.sleep(200);      // widens the window for this demo
            synchronized (lock) {
                lock.wait(1000);    // an untimed wait() would hang here
            }
        }
    }

    // Correct: the check and the wait share one hold of the monitor.
    static void correctAwait() throws InterruptedException {
        synchronized (lock) {
            while (!ready) {
                lock.wait();
            }
        }
    }

    static void signal() {
        synchronized (lock) {
            ready = true;
            lock.notifyAll();
        }
    }

    static long timed(ThrowingAction action) throws InterruptedException {
        ready = false;
        long start = System.nanoTime();
        Thread waiter = new Thread(() -> {
            try {
                action.run();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });
        waiter.start();
        Thread.sleep(50);
        signal();
        waiter.join();
        return (System.nanoTime() - start) / 1_000_000;
    }

    interface ThrowingAction {
        void run() throws InterruptedException;
    }

    public static void main(String[] args) throws InterruptedException {
        System.out.println("check outside monitor: " + timed(LostWakeupDemo::brokenAwait) + " ms");
        System.out.println("check inside monitor:  " + timed(LostWakeupDemo::correctAwait) + " ms");
    }
}

go deeper

for a junior

Recall two groups: threads blocked trying to enter, and threads that called wait() and gave up the lock. wait() and notify() need the lock, and the condition is checked while holding it.

for a middle

Walk a thread into the wait set and back out: join the set, release all holds, get removed, relock in competition, return. Then replay the lost-wakeup interleaving and show how the monitor rule closes it.

for a senior

Use this when reading thread dumps: many BLOCKED threads point at a lock owner, while WAITING threads that never wake suggest a missed notification, a check outside the monitor, or a notifier stuck behind a lock the waiter kept.

for a principal

Set the team default: raw wait and notify are easy to get subtly wrong, so prefer java.util.concurrent queues and latches, and keep any remaining monitor condition code small, reviewed and confined to one class.

## Two groups around one monitor Every Java object has a **monitor**, a lock that only one thread at a time can hold (JLS §17.1), and a **wait set**, a set of threads (JLS §17.2). Threads relate to that object in two different ways. - The **entry set** is the threads that want the lock and are blocked until they get it. The name is conventional: the JLS only says that other threads attempting the lock "are blocked". HotSpot's private `ObjectMonitor` keeps them in `_entry_list`, whose comment reads "Threads blocked on entry or reentry". - The **wait set** is the threads that called `wait()` and are not competing for the lock at all. `ObjectMonitor` keeps them in a separate `_wait_set`. | | Entry set | Wait set | |---|---|---| | How a thread gets in | `synchronized` finds the lock taken, or a thread relocks after `wait()` | it calls `wait()` while owning the monitor | | Holds this lock? | no, and wants it | no, and has given up all its holds | | `Thread.getState()` | `BLOCKED` | `WAITING`, or `TIMED_WAITING` for a timed wait | | What ends it | the lock coming free and this thread winning it | `notify()`, `notifyAll()`, an interrupt, a timeout or a spurious wakeup | | Competes when the lock is free? | yes | no | ## A thread's path between the two 1. A thread owning the monitor calls `wait()`. 2. It joins the wait set and performs as many unlocks as it has holds. JLS §17.2.1 lists them in that order, and the `Object` Javadoc says "and then": added first, unlocked second. Locks on other objects stay held. 3. It runs nothing until something removes it from the set. `notify()` selects one member, with "no guarantee" about which, and `notifyAll()` removes them all. 4. It competes for the lock. It cannot succeed until the current owner, such as its notifier, has fully unlocked, and the `Object` Javadoc gives it "no reliable privilege or disadvantage" against other contenders. 5. It regains the lock with all its holds restored and returns from `wait()`. On HotSpot, `notify()` normally moves the waiter's node from `_wait_set` to `_entry_list`, leaving it to be woken when the monitor is released. On JDK 27.0.1 and 25.0.3, `getState()` for the notified thread reads `BLOCKED` straight after `notify()`, while the notifier still owns the monitor. That fits `Thread.State.BLOCKED`, which includes reentering a synchronized block "after calling Object.wait". ## The lost wakeup A notification is not stored. JLS §17.2.2 removes a thread only "if m's wait set is not empty", and it describes no record of a notification that found the set empty. So `notify()` followed by `wait(300)` waits out the full timeout. A **lost wakeup** is a waiter going to sleep after the notification it needed has already happened. Neither JLS §17.2 nor the `Object` Javadoc uses that name. Picture `wait()` and `notify()` callable without any lock: 1. The waiter reads `ready` and sees `false`. 2. The notifier sets `ready = true` and calls `notify()`. The wait set is empty, so nothing happens. 3. The waiter calls `wait()` and joins the wait set. 4. Nobody notifies again, so the waiter sleeps with `ready` already true. ## How the monitor rule closes the window The JLS states the rule and not a reason: with no lock held, `wait()` and `notify()` throw `IllegalMonitorStateException`. The reason follows from the mechanics. - The waiter can hold the monitor from its condition check until it is in the wait set, because joining comes before unlocking. - The notifier must own the same monitor, so it cannot run between those two points. - So the notifier runs either before the waiter's `synchronized` block, and the waiter then sees the new state, or after the waiter has joined the set, and `notify()` finds it. This assumes the notifier changes the state under that monitor. ## What the rule does not prevent The JVM checks that you own the monitor at the call. It does not check that your condition test shared that hold. - **A check outside the block.** `if (!ready) { synchronized (lock) { lock.wait(); } }` compiles, never throws for this reason and can still lose the notification. - **No condition at all.** A bare `wait()` with no state behind it has nothing to test, so a `notify()` that came earlier is simply gone. - **The wrong thread woken.** `notify()` can select a waiter that cannot use it, which HotSpot's source calls "one example of a lost wakeup". That is the reason to choose carefully between `notify()` and `notifyAll()`. - **A different guarantee.** JLS §17.2.4 says "notifications cannot be lost due to interrupts", which concerns a thread both notified and interrupted, not this race. The `while` loop around `wait()` is a separate duty: it handles spurious wakeups and contenders that got to the lock first.

  • After Object.notify(), why can the condition already be false again when the notified thread returns from wait()?
    `notify()` only removes the thread from the wait set. It must then relock, competing with any thread blocked on entry, and the `Object` Javadoc gives it no reliable privilege. A contender can win, consume the state and leave. That, together with spurious wakeups, is why the check sits in a `while` loop under the monitor.
  • How does LockSupport.park() avoid this lost wakeup without requiring a monitor?
    `LockSupport` associates a permit with each thread. `unpark(t)` makes it available, and if `t` is not blocked in `park()`, its next call is guaranteed not to block, so an early wakeup is remembered, unlike `notify()`. At most one permit exists and `park()` can return spuriously, so reliable use still tests a `volatile` or atomic variable.
  • What does Object.wait() release if the thread holds the monitor reentrantly or also holds other monitors?
    It releases every hold on that object, however many nested `synchronized` blocks took it, and restores them all before returning. Locks on other objects stay held. So if the notifier needs one of those other locks, it blocks before reaching `notify()`, and both threads can stay stuck.

  • wait() keeps the lock so that no other thread can change the state.
  • A notified thread resumes at once, before the notifier leaves its synchronized block.
  • A notify() with nobody waiting is remembered for the next wait().
  • Threads in the wait set compete for the lock whenever it becomes free.
  • Holding the monitor at wait() is enough, wherever the condition was checked.
  • wait() releases every lock the thread holds, on all objects.

Object.wait, notify and notifyAll
Java 1.0
Thread.State BLOCKED, WAITING, TIMED_WAITING
Java 1.5

Assumes JDK 27; Object.java's wait and notify contract and HotSpot's _entry_list and _wait_set names read the same in JDK 25's source.

context