Video in progress

Strong Middle ⚙️ JVM and memory

What does a synchronized block look like in bytecode, and what states does the JVM move a lock through internally?

The block turns into monitorenter/monitorexit instructions, and a separate monitorexit is added for the exception path too. Internally the JVM first takes a lightweight lock with a CAS, and if there is contention it "inflates" it into a full monitor and puts the waiting threads to sleep at the OS level.

📖 Answer

void add(int x) {
    synchronized (lock) {
        total += x;
    }
}

The javap -c output (shortened):

 4: monitorenter
 5: ... total += x ...
14: aload_2
15: monitorexit
16: goto 24
19: astore_3        // exception handler
20: aload_2
21: monitorexit     // the lock is released even on an exception
22: aload_3
23: athrow
Exception table: 5-16 -> 19 any; 19-22 -> 19 any

In other words, javac guarantees the lock is released even when there is an exception. A synchronized method has no such instructions: the method has the ACC_SYNCHRONIZED flag and the JVM handles it itself.

Internally (HotSpot):

  1. No contention. The thread uses a CAS to move the mark word to the "locked" state. Cheap, no OS involvement.
  2. Contention. If a second thread arrives, it spins for a short while (the lock may be released quickly), and then the lock is "inflated": a native ObjectMonitor is created, and the waiters join a queue and are parked.
  3. wait()/notify() work only with an inflated monitor.

The lightweight lock implementation changed in newer JDKs (the new lightweight locking in JDK 21+, preparation for Lilliput), but that is an internal detail, and the semantics are the same.

The practical result: an uncontended synchronized is very cheap, a contended one is expensive (context switches). JFR's jdk.JavaMonitorEnter event shows lock contention.