Video in progress

Strong Middle 🧵 Concurrency

How does a synchronized block work internally, and how does the JVM change lock states?

Every object has a mark word in its header, and synchronized takes the monitor there. Without contention, a thin lock is acquired with CAS; as contention grows, it moves to a heavy OS-level monitor (inflated).

📖 Answer

At the bytecode level, a synchronized block turns into monitorenter/monitorexit, while a synchronized method gets the ACC_SYNCHRONIZED flag. So that monitorexit is called even when an exception is thrown, the compiler adds a hidden finally.

In HotSpot the states look roughly like this:

State When Cost
unlocked nobody holds it none
thin / lightweight one thread takes it, no contention a single CAS
inflated (heavy) another thread had to wait, or wait() was called OS mutex, park/unpark

There used to be biased locking too, but it was disabled by default in JDK 15 and the code was removed completely around JDK 18. So anything old articles say about "biased locks" doesn't apply to Java 21.

Practical takeaways:

  • Uncontended synchronized is cheap, so there's no need to avoid it as "slow".
  • Under heavy contention, threads spin and then get parked. That's where CPU and latency go.
  • The lock is reentrant: if a thread takes the same monitor again, a counter just goes up.

The JIT helps too: if escape analysis sees that an object never leaves the thread, it removes the lock (lock elision), and it merges adjacent blocks (lock coarsening).