AlgoViz

Monitor

medium 50 min

A 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

0:00 / 4:27

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

  1. 1972

    Per Brinch Hansen's Structured Multiprogramming appears in Communications of the ACM, an early step towards monitors.

  2. 1974

    C. A. R. Hoare publishes Monitors: An Operating System Structuring Concept in Communications of the ACM, with conditions, wait and signal.

  3. 1975

    Brinch Hansen describes Concurrent Pascal, a language with monitors.

  4. 2004

    Java 5 adds Lock and Condition, so that one monitor can have several wait sets.

  5. 2011

    C++11 brings std::mutex and std::condition_variable.

  6. 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.

Step 1 of 3

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 paint room
MORE PAINTMORE ROOMPAINT ROOM2 of 10 L5L

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

Tub+ litres: int+ lock: Lockno rule of its own

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

Nothing in this picture keeps the rule between 0 and 10. A monitor makes the four mistakes impossible to write.

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

callsThread+ run()Monitor- data: T- mutex: Lock- conditions: Condition[]+ operation()- whileNot(rule): wait

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 producer never mentions the consumer. Both only talk about the state.

The life of a thread at a monitor

There is no arrow from Asleep to Inside. Every woken thread goes past the door.

Four guarantees

GuaranteeMeansWho gives it
Mutual exclusionAt most one thread active insideThe lock
Condition synchronizationA thread sleeps until a condition may hold, without using the processorwait and signal
EncapsulationData, lock and conditions are private to one objectThe class
Atomic releaseNo gap between leaving the lock and falling asleepwait itself
The last one prevents the lost wake-up: without it, a signal could fall into the gap and the sleeper would never hear it.

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

HoareMesa
After signalThe woken thread runs at once, the signaller waitsThe signaller runs on, the woken thread goes to the door
Condition when the waiter runsCertainly still trueIt was true, perhaps
The checkif is enoughwhile is needed
CostTwo switches for each signal, harder to buildCheap, simple
Used byPapers and teachingJava, Python, C++, POSIX threads, C#
Python
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"))
The story as code, with the turns written out by hand. The order is fixed, so the bug appears every time.
Edit and run it in your browser
Java
// wrong under Mesa rulesif (!ready) wait();use();                    // ready may be false again// rightwhile (!ready) wait();use();                    // ready is true, and we hold the lock
One line decides. The wrong form compiles, passes most tests, and fails under load.

What a monitor method looks like, always

Five boxes and a loop. If a method does not fit, ask whether it belongs in the monitor.

Choosing

Signal one or all?

signal, notifybroadcast, notifyAll
WakesOne sleeper, you cannot choose whichAll sleepers of the condition
Correct ifAll sleepers wait for the same thing, and one change lets exactly one go onAlways
CostOne thread wakesMany wake, one goes on, the rest sleep again
DangerThe wrong sleeper is woken and the right one sleeps onA crowd at the door
ExampleBuffer: one item put, one taker neededPaint: 4 litres may serve nobody, one, or four
If you are not sure, wake all. Being slow is a smaller bug than standing still.

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

LanguageLockConditionRemember
Javasynchronized or ReentrantLockwait, notify or lock.newCondition()Every object has one wait set only
Pythonthreading.Lockthreading.Condition(lock)wait_for has the loop inside
C++std::mutexstd::condition_variablewait(lock, rule) has the loop inside, and needs unique_lock
C#lockMonitor.Wait, Monitor.PulseThe class is called Monitor
Gosync.Mutexsync.CondThe documentation points to channels for simple cases
TypeScriptnot needed between two awaitsa list of promise resolversAn 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