Two Problems Monitors Solve: Mutual Exclusion and Condition Waiting
When multiple threads operate on shared state, guaranteeing that “only one thread modifies it at a time” isn’t enough. A consumer might acquire the lock only to find the queue empty; a producer might acquire the lock only to find the queue full. Both need a way to pause when their condition isn’t met, then compete to run again once the state changes.
A monitor bundles shared state, the operations that touch it, mutual exclusion rules, and condition waiting into one abstraction. Java’s combination of synchronized and wait/notify follows this exact model: synchronized protects the state, and wait/notify coordinate when threads can proceed.
A lock alone isn’t enough for producer-consumer
Imagine a bounded queue with fixed capacity. Producers add elements to it; consumers remove them. To stop two threads from mutating the queue at the same time, you can wrap every operation in a lock:
1 | Producer ─┐ |
A lock solves mutual exclusion, but it says nothing about what to do when a condition isn’t satisfied. If a consumer finds the queue empty and loops while holding the lock, no producer can ever get in to add data. If it releases the lock and polls in a tight loop, it burns CPU and still has to handle the race between checking the condition and reacquiring the lock.
There are two separate problems here:
- Mutual exclusion: only one thread at a time may inspect or modify the queue.
- Synchronization: consumers must wait while the queue is empty, and producers can only proceed when the queue isn’t full.
A monitor puts both inside the same boundary. External threads cannot mutate the shared variables directly; they can only go through protected operations. When a condition doesn’t hold, the thread enters a wait set tied to that condition and temporarily gives up access to the monitor.
A monitor is more than a lock: protected state and operations
As a programming model, a monitor has three parts: shared state, the procedures that operate on that state, and one or more condition variables. Mutual exclusion guarantees that at most one thread runs inside the monitor at any moment. Condition variables let a thread that has already entered say, “I can’t make progress in the current state.”
A bounded queue can be described with two conditions:
1 | notEmpty: the queue has at least one element, so a consumer can take |
Waiting on a condition and contending for entry are not the same thing. One thread hasn’t acquired the lock yet and is waiting to enter the critical section; another thread already held the lock, saw that the condition it needed didn’t hold, and voluntarily entered a condition wait. The first is competing for access. The second is waiting for shared state to change in a specific way.
Encapsulation matters here. If outside code can bypass the monitor and mutate the queue directly, state changes can happen without the matching notification, and waiting threads can no longer rely on the monitor’s invariants. Keeping variables and operations inside the same boundary makes it possible to decide who to wake after every update.
The three monitor semantics differ on who runs next after a signal
Discussions of monitors usually distinguish three semantics: Brinch Hansen, Hoare, and Mesa. All three provide mutual exclusion and condition waiting. They differ on when a waiting thread takes over the monitor after another thread issues a signal.
Hoare semantics hand over control immediately. The signaling thread transfers monitor ownership straight to the woken thread and suspends itself. When the woken thread resumes, the condition that just became true is guaranteed to still hold because of that direct handoff. That makes reasoning straightforward, at the cost of tighter scheduling and context-switching support from the runtime.
Brinch Hansen semantics restrict signaling to the very end of a monitor procedure. Right after signaling, the current procedure exits so the woken thread gets a chance to run. This reduces the chance of the signaling thread altering state after a signal, though it constrains how you structure your code.
Mesa semantics treat a signal as a hint that “the state may now be favorable.” The signaling thread keeps running until it leaves the monitor; the waiting thread merely becomes runnable and has to compete for the lock again. By the time it actually re-enters, another thread may have changed the shared state again, so it must recheck its condition.
Java’s intrinsic monitor follows Mesa style: notify() does not immediately release the lock, and the chosen waiting thread does not return from wait() right away. Only after the notifying thread exits the synchronized region and the woken thread reacquires the same lock can it continue.
Why wait in Java must live inside a while loop
Here is a minimal bounded queue in Java. The point isn’t the queue implementation; it’s that condition checks, waiting, and state updates all happen under the same object monitor:
1 | import java.util.ArrayDeque; |
A consumer calling wait() must already hold the current object’s monitor. The call puts the thread into that object’s wait set and releases all reentrant holds it has on the monitor, so producers can enter put(). After the thread is notified, interrupted, times out, or hits a permitted spurious wakeup, it still has to reacquire the monitor. Only once its lock state is restored will wait() return or throw InterruptedException.
The while loop here cannot be replaced with an if. Spurious wakeups aren’t the only reason. Under Mesa semantics, before a notified consumer manages to reacquire the lock, another consumer may already have grabbed the element that was just inserted. Waking up only means the condition might have been true at some point; the thread must verify it again when it actually resumes.
You can picture the lifecycle around wait() like this:
1 | Hold lock and check condition |
notify only sends a signal; it doesn’t hand over the lock
notify() picks an arbitrary thread from the object’s wait set and wakes it, with no ordering guarantee. notifyAll() wakes every thread in the wait set, but none of them can immediately run the protected code either; they still have to wait for the current thread to release the lock and then contend for entry.
In the bounded queue above, both producers and consumers sit in the same object’s wait set, even though they care about opposite conditions. Calling notify() can wake a thread of the same kind whose condition is still false: for example, waking another producer while the queue is still full, while a consumer that could actually make progress stays asleep. That mistakenly woken thread checks its condition and goes right back to waiting, and under certain schedules you can end up with nobody making progress.
notifyAll() forces every waiter to recheck its condition. It’s safer, though with many threads it creates extra contention. When you need separate condition queues, use ReentrantLock with multiple Condition objects so notEmpty and notFull can be signaled independently instead of cramming everyone into Object‘s single wait set.
There’s also an easy-to-miss edge case: wait() only releases the monitor of the object it’s called on. If the thread holds locks on other objects at the same time, none of those are released. Calling wait() casually inside nested locks can still leave other threads stuck on locks you never let go of.
Keep Java semantics separate from HotSpot implementation details
At the language level, Java guarantees that every object is associated with a monitor and a wait set. Synchronized instance methods lock this, static synchronized methods lock the corresponding Class object, and synchronized(lock) locks whatever object the expression evaluates to. Synchronized blocks are typically compiled to monitorenter and monitorexit bytecode instructions, while synchronized methods enter and exit the monitor implicitly via a method flag.
To avoid paying for a full heavyweight monitor when there’s no contention, HotSpot doesn’t allocate one every time synchronized runs. Modern HotSpot usually takes a lightweight locking path first. Only when contention occurs, wait() is called, or the lightweight mechanism isn’t enough does it associate an ObjectMonitor with the object, a process called monitor inflation.
In OpenJDK’s current ObjectMonitor implementation, you can see fields for the owner, wait set, entry list, and a recursion count for reentrancy. wait() puts waiting threads into the wait set, and notification moves them back onto the path to re-contend for the monitor. Details like _entry_list, how the owner is represented, and object header layouts are HotSpot implementation specifics, not fixed memory structures mandated by the Java Language Specification. They can change across JDK versions and object header configurations.
So when reasoning about concurrent code, rely on the stable semantics first: what protects the shared state, where the condition is checked, which lock wait() releases, and whether the condition is rechecked after waking up. Object header mark bits and specific queue internals are useful for analyzing performance and diagnostics on a particular HotSpot build, not for treating as a programming contract every JVM has to obey.
Monitors keep concurrency constraints next to the shared state
Monitors work well when you have clear state and stable operation boundaries. For a bounded queue, the invariants are simple: the element count always stays between 0 and capacity, put() only mutates when not full, and take() only mutates when not empty. The lock guards the atomic boundary between checking and mutating, while condition waiting keeps threads from holding onto the lock when they can’t move forward.
In real code, you still have to decide how interruption propagates, whether waits need timeouts, and whether a state change should signal one condition queue or several. Whether you use intrinsic monitors or Lock/Condition, the condition-checking loop needs to follow the same synchronization rules as the shared state itself; otherwise, wait/notify code that looks complete can still miss state changes.