Java / Java Concurrency and Multi Threading in Java 17 and Java 21 Interview questions
How does the synchronized keyword achieve mutual exclusion internally?
Every Java object carries an intrinsic lock, or monitor. When a thread enters a synchronized method or block, the JVM emits a monitorenter bytecode instruction that attempts to acquire that object's monitor; a matching monitorexit releases it on normal exit or when an exception propagates out.
HotSpot doesn't always use a full OS-level mutex for this. It escalates through lock states depending on contention, to keep the common case cheap.
| Lock state | When it's used |
| Biased locking | One thread repeatedly re-acquires the same lock with no contention (removed by default in newer JDKs, but part of the escalation history). |
| Lightweight locking | Brief contention, resolved with a fast CAS on the object header, no OS involvement. |
| Heavyweight locking | Sustained contention; the JVM falls back to an OS-level monitor, parking blocked threads. |
Only one thread can hold a given monitor at a time; any other thread calling a synchronized method on the same object blocks until the lock is released, which is what produces mutual exclusion.
More Related questions...