Lesson · Multithreading Fundamentals
Synchronization: what a monitor actually locks
14 min readSynchronization
synchronized does not lock the code it surrounds. It acquires an object's monitor, and two threads exclude each other only when they acquire the same object. Get that one fact straight and the rest (visibility, reentrancy, granularity) follows.
The increment that needs an agreement
Two threads increment one int and the result comes out wrong. The race-conditions lesson owns that failure: counter++ is LOAD, ADD, STORE, and the write that gets lost sits in the gap between the first two steps. The tool that closes the gap is synchronized, and it is also one of the most misunderstood keywords in the language.
The misunderstanding starts with the mental model. synchronized does not lock a block, a method or a class; it locks an object. Two threads can run the same guarded method at the same moment if they call it on different instances, and two unrelated guarded blocks exclude each other completely if they lock the same instance.
So the question to ask about any synchronized keyword is never "what does this look like", it is "which object does this acquire, and who else acquires it". Hold that question through the next section: every bug in this lesson is an answer to it.
Three forms, one mechanism
Every object in Java carries a monitor, also called its intrinsic lock. synchronized is only the syntax that talks to it: entering a guarded region acquires the monitor of one specified object, leaving releases it, and the JVM allows exactly one owner at a time.
Which object that is depends on the form you wrote. An instance method locks the receiver, this. A static method locks the Class object for that class, so every static synchronized method of the class shares one monitor. A synchronized block locks whatever its expression evaluates to, and that expression must not be null: a null there throws NullPointerException before any locking happens.
The board below turns the table into buttons: acquire the monitor from either thread, watch the loser move to the entry set instead of the guarded code, and increment the counter only from whoever owns the monitor.
| Form | What is locked | Who shares that lock |
|---|---|---|
| synchronized (expr) { ... } | the object the expression returns | only code that uses the same reference |
| synchronized void inc() | the receiver instance (implicit this) | every thread that locks that same instance |
| static synchronized void inc() | the Class object, e.g. MonitorDemo.class | every static synchronized method of the class, in any thread |
The monitor is the object, the block only names it. Two guarded blocks exclude each other exactly when they lock the same object, never because they look alike.
Monitor board · one object, one owner
acquire, release, then count++monitor of
private final Object lock
owner
The thread currently inside the guarded region. At most one.
entry set
Threads that reached the same monitor and are BLOCKED: queued, not sleeping.
guarded counter
0
The monitor is free: acquire it before incrementing.
Running outside the monitor: nothing stops it until it tries to enter.
Running outside the monitor: nothing stops it until it tries to enter.
monitor log
- nothing yet: press acquire on either thread
Try it: let T1 acquire, then press acquire on T2. T2 does not spin, it sits in the entry set until T1 releases.
Inside the monitor: owner, entry set, wait set
A monitor is one owner plus two queues, and a thread's JVM state depends on which queue it is in. The owner is the thread currently inside the guarded region. A thread that reaches the same monitor while it is owned is parked in the entry set and reported as BLOCKED: not sleeping, queued for the lock.
The wait set is the third region, and it stays empty for every lock in this lesson. A thread enters it only by calling wait(), which releases the monitor and waits for a condition rather than for the lock. The next lesson is entirely about it, so keep the two queues apart now: mixing them up explains most wrong intuitions about waiting.
One property of the entry set is worth saying out loud: entry is orderly but not fair. The JVM does not promise that the thread which waited longest enters next, so a synchronized block under heavy contention can starve a thread, and fairness is a ReentrantLock constructor option rather than something the keyword offers (the locks and starvation lessons take it from here).
Monitor anatomy
one owner, two queues
Reached the guarded region first and acquired the monitor.
Reached the same monitor while T1 owns it.
one object: any instance
its monitor is drawn belowowner
Holds the monitor and runs the guarded code. One thread at a time.
entry set
BLOCKED threads queued for the lock. They run when the owner releases it.
wait set
Threads parked in obj.wait(). Empty here: it arrives with the wait/notify lesson.
synchronized (expr) simply names the object whose monitor is drawn here. Two blocks exclude each other when the same object ends up in its left column.
Release and acquire: the half people forget
Mutual exclusion is only half of what synchronized guarantees. The language specification defines a synchronizes-with edge between an unlock of a monitor and every later lock of that same monitor, and the Java Memory Model builds happens-before on top of it: everything a thread wrote before releasing is visible to every thread that acquires the same monitor afterwards.
That edge is why a guarded counter is not only atomic but also readable. Without it a thread could enter the region, read a stale value from a core-local cache, and compute the next value from data that no longer exists. Visibility is not a bonus feature of locking, it is half the contract.
The rule for reads is the same as for writes: read the state under the lock that guards it. A getter that returns a guarded field without synchronizing has quietly opted out of the guarantee and can hand out a value from an unspecified moment.
Releasing a monitor publishes everything you wrote; acquiring it makes those writes visible. Mutual exclusion and visibility come from the same keyword.
The same thread may walk back in
A monitor remembers which thread owns it and how many times that thread acquired it. A second acquisition by the same thread succeeds immediately and increments the count; the monitor is released only when the count returns to zero.
That is reentrancy, and it is why guarded code can call guarded code. A synchronized method may call another synchronized method on the same object, and a recursive method may guard itself, with no deadlock anywhere in sight. The JVM treats the repeat acquisition as a detail of the owner, not as a new contender at the door.
class Ledger { private int total; synchronized void add(int amount) { total += amount; // count = 1 log(); // same thread, same object: count = 2, no deadlock } private synchronized void log() { // runs while the calling thread already owns the monitor } }
What never to lock
Any object works as a lock, which is exactly the problem: some objects are far more shared than the code around them suggests, and two unrelated classes can end up queuing on one monitor.
The default that avoids all of it is a lock object no other code can name: private, so no caller can acquire it, and final, so the reference cannot be swapped for another one later.
public final class Counter { private final Object lock = new Object(); // private: no caller can acquire it private int count; public void increment() { synchronized (lock) { // this object, on this instance count++; } } }
- Interned String literals. Identical literals are the same object JVM-wide, so synchronized ("lock") in two unrelated classes is one lock. The two paths serialize for no reason, and under the wrong interleaving they deadlock.
- Boxed primitives and other cached objects. Integer.valueOf caches -128 to 127, so synchronized (Integer.valueOf(0)) locks an instance the whole JVM shares. Boolean.TRUE and the Character cache have the same shape.
- Objects the caller can reach. Locking on this, or on a field a caller holds, invites outside code into your monitor, where it can hold the lock indefinitely without ever calling your methods.
- getClass() as a stand-in for the class. An instance of a subclass returns a different Class object, so a synchronized (getClass()) block and a static synchronized method of the parent do not even exclude each other.
Lock what you own. A private final lock object cannot be shared by accident; a string literal, a boxed number and a public field can.
One lock per invariant, and keep the section short
The unit that decides locking is the invariant, not the method. If two fields must always agree (a size and the array it describes), one lock guards both updates; two locks would let another thread observe the disagreeing state, which is a race condition with extra steps.
Inside that boundary, keep the critical section as short as it can be while staying correct. File I/O, network calls, slow logging and callbacks into unknown code all hold the lock while they run, and every millisecond there is a millisecond every other thread spends in the entry set.
Coarse and fine locking are the two ends of a trade, and contention decides where you land. An uncontended lock is cheap: the JVM updates the object header and, since JDK 15 disabled biased locking (JEP 374), pays for at least one atomic operation even with a single thread running. A contended lock is a different order of cost, because the loser is parked and later woken by the OS scheduler: a context switch plus a lost time slice, every trip around the loop.
| Granularity | What it buys | What it costs |
|---|---|---|
| one coarse lock | simple to reason about, hard to deadlock, invariants stay whole | unrelated work serializes; throughput becomes the ceiling |
| fine-grained locks | more parallelism for genuinely independent state | deadlock risk, more invariants to hold together, harder reviews |
| lock striping | parallelism inside one structure: partition it, give each part its own lock | no atomicity across partitions; LongAdder and the concurrent collections do this internally |
- No sharing: keep the state on one thread, or hand ownership over (confinement). Nothing to lock, nothing to lose.
- Immutability: if the shared object never changes, readers need no lock and writers build a new object instead.
- Confinement per thread: each worker owns a slice of the work and the results are merged at the end.
- Synchronization last: share and mutate, then guard the smallest correct region with the lock that belongs to that invariant.
Prefer no sharing, then immutable, then confined, and only then synchronized. Locks are the fallback, and the best alternative to a cleverer lock is less shared state.
A lock you did not know you were sharing
Your class synchronizes on "config" and a library synchronizes on "config": two unrelated code paths now share one monitor. The failure is not a crash. Work serializes for no reason, and under the wrong interleaving the two sides deadlock. The same trap sits in boxed values, because Integer.valueOf caches -128 to 127 JVM-wide. A private lock object cannot be reached by accident, so it cannot be shared by accident.
Interview angles
What does synchronized actually lock in each of its three forms?+
An object. An instance method locks this, a static method locks the Class object, and a synchronized block locks whatever the expression evaluates to. Mutual exclusion holds between threads that lock the same object, not between blocks that merely look the same.
Common misconception: synchronized locks the method or the block it is written around.
Does synchronized also guarantee visibility, or only mutual exclusion?+
Both. An unlock synchronizes-with every later lock of the same monitor, so everything written before the release becomes visible to the next owner. The happens-before edge lives on the monitor, not on the field.
That is also why reading a guarded field without the lock is a real bug: the write is atomic and published, but the unlocked read has no edge to attach to, so it can return an earlier value.
Is synchronized reentrant? Show why it has to be.+
Yes. The monitor tracks an owner and a count, so the owning thread can re-enter guarded code it already holds. Without that, a synchronized method calling another synchronized method on the same object would deadlock against itself.
class Base { synchronized void a() { b(); } // count 1, then 2 on the same thread synchronized void b() { } }
Why is locking on a String literal or an Integer a bug?+
Both objects are shared JVM-wide: identical literals are interned to one instance, and Integer.valueOf returns cached instances from -128 to 127. An unrelated class can lock the same object, so the two paths serialize or deadlock without sharing any real state. A private final lock object ends the class of bug.
Coarse or fine-grained locking, how do you decide?+
One lock per invariant, then the shortest critical section that is still correct. Split only when profiling shows real contention on that lock and each resulting piece keeps one invariant whole. Two locks over one invariant trade a correctness bug for throughput, which is the wrong trade every time.
Two methods on the same class touch the same field, one synchronized and one not. What breaks?+
The unlocked method is outside the agreement: it can read or write while another thread is inside the guarded region. Mutual exclusion is a property of the code that participates, so every access to the state must take the same lock.
Follow-up: How would you catch that in review? Look for field names: every read and write of a guarded field should appear inside a synchronized region on the same object.