Monitor
medium 50 minA monitor puts shared data, the lock that guards it and the conditions threads wait for into one object.
Video lesson · Chapter 1 of 6
Make a prediction
Monitor
1:04Reel
Theory
Read or listen first. About 2 min.
What it is
A monitor is an object whose methods exclude each other. Its data is private, each method takes the same lock, and a method that cannot go on waits on a condition variable, which lets others in meanwhile.
It is mutex plus condition variables plus data. The lock answers who is inside. The conditions answer what a thread waits for. The data answers whether the wait is over.
Languages support it to different degrees. In Java every object has a monitor and the keyword synchronized enters it. In Python and C++ you combine a lock and conditions by hand.
Why it exists
A lock alone can protect a change, but it cannot wait for one. A thread that finds a buffer empty must let go of the lock, sleep, and be woken. Doing this by hand leaves a gap in which a wake-up gets lost.
A semaphore alone can wait for a number, but not for a condition such as balance covers the amount, or two fields that belong together.
Putting data, lock and waiting into one class means that there is one place to read, one place to test, and no caller who can forget the lock.
A short history
1972
Per Brinch Hansen's Structured Multiprogramming appears in Communications of the ACM, an early step towards monitors.
1974
C. A. R. Hoare publishes Monitors: An Operating System Structuring Concept in Communications of the ACM, with conditions, wait and signal.
1975
Brinch Hansen describes Concurrent Pascal, a language with monitors.
2004
Java 5 adds Lock and Condition, so that one monitor can have several wait sets.
2011
C++11 brings std::mutex and std::condition_variable.
2025
JDK 24 delivers JEP 491: virtual threads no longer pin their carrier when they block in synchronized.
Words to know
- Mutex
- The lock of the monitor. One holder.
- Condition variable
- A set of sleeping threads that belongs to a lock.
- Entry set
- Threads that wait at the door for the lock.
- Wait set
- Threads that sleep on a condition.
- Invariant
- The rule that is true whenever nobody is inside.
- Mesa semantics
- The signaller goes on, the woken thread competes for the lock.
- Hoare semantics
- The woken thread runs at once, the signaller waits.
- Spurious wakeup
- wait returns although nobody signalled.
- Lost wake-up
- A signal that comes before the thread sleeps, and is gone.
- Broadcast
- Wake all sleepers of a condition.
- Nested monitor lockout
- Waiting on an inner condition while holding an outer lock.
- Open call
- Calling foreign code when no lock is held.
The solution, twice
Reach the regular design first. Then go where a FAANG interviewer digs.
How it works
Step through the idea, or press Play.
Enter. One thread at a time holds the lock
Understand it
Start here
One room, one door, two waiting mats
A carnival workshop mixes purple paint in one tub. Painters take litres out, mixers pour litres in. If two people work at the tub at once, the scale is wrong and the floor is purple. So the tub stands in a room with one door. And who cannot go on, because there is too little paint or too little room, goes back out and waits on a mat. That room is a monitor.
The room keeps the state, the door lets one in, the mats hold those who cannot go on. Three parts, one object.
Three components and two calls
The data
Private, with a rule that is true whenever nobody is inside: between 0 and 10 litres.
The lock
Also mutex. One holder. Every method takes it at the start and gives it back at the end.
The conditions
A waiting set for each reason to wait: more paint, more room.
wait()
Leaves the lock and sleeps, as one step. Before it returns, it takes the lock again.
signal() and broadcast()
Wake one sleeper, or all of them. Java says notify and notifyAll, or signal and signalAll. Python says notify and notify_all.
Why
What goes wrong without it
Data here, a lock there, and the knowledge of what belongs together in somebody's head. The first version usually has a lock that callers must remember, and waiting by polling.
The design that hurts
1/4The lock is public
Tub offers its data and its lock. Using the second before the first is a request, not a rule.
uses
Lock inside the object
- Callers see methods only
- Waiting is written once, next to the data
- The rule can be read and tested in one file
- A block or guard gives the lock back, also after an error
Lock beside the data
- Each caller must remember the lock
- Each caller writes its own waiting loop
- The rule is spread over forty places
- One forgotten release, and everything stops
The idea
The object enters the lock for you
A monitor in general
1/4Threads see methods
A thread calls an operation. It sees no lock and no condition.
usesowns (dies together)depends on
Wait and signal, step by step
The life of a thread at a monitor
Four guarantees
| Guarantee | Means | Who gives it |
|---|---|---|
| Mutual exclusion | At most one thread active inside | The lock |
| Condition synchronization | A thread sleeps until a condition may hold, without using the processor | wait and signal |
| Encapsulation | Data, lock and conditions are private to one object | The class |
| Atomic release | No gap between leaving the lock and falling asleep | wait itself |
Meaning
Hoare, Mesa, and why it is while
What happens at the instant of a signal? Two threads now want to be inside: the one that signals and the one that was woken. Only one can be.
Two answers
| Hoare | Mesa | |
|---|---|---|
| After signal | The woken thread runs at once, the signaller waits | The signaller runs on, the woken thread goes to the door |
| Condition when the waiter runs | Certainly still true | It was true, perhaps |
| The check | if is enough | while is needed |
| Cost | Two switches for each signal, harder to build | Cheap, simple |
| Used by | Papers and teaching | Java, Python, C++, POSIX threads, C# |
def run(check): tub, log = 6, [] # Max has poured and rung the bell tub -= 3 # Noor was at the door first log.append(f"Noor takes 3, left {tub}") awake = True # Lee wakes up after wait() if check == "while" and tub < 5: awake = False # looks again: not enough, waits log.append("Lee looks again and waits") if awake: tub -= 5 # if: looked once, before sleeping log.append(f"Lee takes 5, left {tub}") return logprint("if: ", run("if"))print("while:", run("while"))// wrong under Mesa rulesif (!ready) wait();use(); // ready may be false again// rightwhile (!ready) wait();use(); // ready is true, and we hold the lockWhat a monitor method looks like, always
Choosing
Signal one or all?
| signal, notify | broadcast, notifyAll | |
|---|---|---|
| Wakes | One sleeper, you cannot choose which | All sleepers of the condition |
| Correct if | All sleepers wait for the same thing, and one change lets exactly one go on | Always |
| Cost | One thread wakes | Many wake, one goes on, the rest sleep again |
| Danger | The wrong sleeper is woken and the right one sleeps on | A crowd at the door |
| Example | Buffer: one item put, one taker needed | Paint: 4 litres may serve nobody, one, or four |
Painters wait for different amounts: 5, 1 and 1 litres. A mixer pours 2. What do you call?
Breakssignal
- How
- Wake one.
- Limit
- It may wake the one who needs 5. That one sleeps again, and the two who need 1 sleep beside enough paint.
- Choose when
- Only with identical waiters.
Worksbroadcast
- How
- Wake all three, each looks for itself.
- Limit
- One wakes for nothing. With a thousand waiters that becomes visible.
- Choose when
- The right default.
StrongA line of requests in the monitor
- How
- Each waiter has its own condition and amount in a list. The mixer serves the list in order and wakes exactly those who are served.
- Limit
- More code, and a decision about fairness.
- Choose when
- Many waiters, or a promised order. It is how the fair semaphore works.
Fit
When to use it and when not
Use it when
- Several fields must change together and stay consistent
- Threads must wait until a condition over that state holds
- You build a thread-safe structure: buffer, pool, cache, latch
- Producers and consumers share a bounded buffer
- A pool hands out resources and must wait when empty
Leave it when
- One number is all: use an atomic
- Nobody ever waits for a condition: a plain lock is enough
- Reads are frequent and long, writes rare: read-write lock
- The state is on several machines: a lock in one process does not help
- Very high contention: split the state, or use a lock-free structure
- A library already has it: BlockingQueue, CountDownLatch, queue.Queue
A monitor in each language
| Language | Lock | Condition | Remember |
|---|---|---|---|
| Java | synchronized or ReentrantLock | wait, notify or lock.newCondition() | Every object has one wait set only |
| Python | threading.Lock | threading.Condition(lock) | wait_for has the loop inside |
| C++ | std::mutex | std::condition_variable | wait(lock, rule) has the loop inside, and needs unique_lock |
| C# | lock | Monitor.Wait, Monitor.Pulse | The class is called Monitor |
| Go | sync.Mutex | sync.Cond | The documentation points to channels for simple cases |
| TypeScript | not needed between two awaits | a list of promise resolvers | An await in the middle of the work needs a lock again |
Summary
The whole topic in one minute.
A monitor is data, lock and conditions in one object. Methods enter the lock, wait in a while loop, change the state so that the rule holds again, signal, and leave. wait leaves the lock and sleeps in one step.
A signal is a hint: barging, broadcast and spurious wakeups can make it false. Use one condition per reason, and broadcast when in doubt.
In depth: wrong and swallowed signals, beds that remember, nested lockout and open calls, closing with sleepers, and the product of visits and time inside.
- Data, lock and conditions in one object. Callers see methods.
- wait leaves the lock and sleeps in one step, and takes the lock again before it returns.
- Always while, never if. Mesa rules and spurious wakeups have the same cure.
- One condition per reason to wait. Signal after the change, before leaving.
- Not sure? Broadcast.
- Never call unknown code, never do slow work, and never sleep inside.
Sources
- Java Language Specification 17: Threads and Locks
- Java: Condition
- POSIX: pthread_cond_wait
- C++ reference: condition_variable
- Python: threading, condition objects
- .NET: Monitor class
- OpenJDK: ArrayBlockingQueue source
- JEP 491: Synchronize Virtual Threads without Pinning
- Guava: Monitor
- C. A. R. Hoare: Monitors (ACM)