skip to content

How is Java's synchronized implemented in bytecode and in HotSpot, from ACC_SYNCHRONIZED and monitorenter to inflation, and what did removing biased locking change?

level: seniorimportance: should knowfreq 50%

answer

  1. a flag versus two instructions
  2. catch-any handler guards the exit
  3. mark word tag plus per-thread stack
  4. spin, inflate, then park
  5. disabled in 15, obsolete in 18

basics

~20 s

javac marks a synchronized method with ACC_SYNCHRONIZED and compiles a block to monitorenter and monitorexit. HotSpot locks with a header CAS and a per-thread lock stack, inflating to an ObjectMonitor on contention or wait(). Biased locking no longer exists.

solid answer

~50 s

javac marks a synchronized method with the `ACC_SYNCHRONIZED` flag, so method invocation and return enter and exit the monitor, while a block compiles to `monitorenter` and `monitorexit` plus a catch-any handler that releases the lock on an exception. In HotSpot an uncontended lock is a compare-and-swap that flips the mark word's tag from `01` to `00` and pushes the object on the thread's `LockStack`; no monitor structure is built. It inflates to an `ObjectMonitor` under contention after a short spin (JDK 25 LTS skips that spin by default), on `Object.wait()`, on re-entry when the object is not on top of the stack, or when the stack is full. The monitor spins adaptively, then parks the thread. Biased locking was disabled and deprecated in JDK 15, obsoleted in 18, and JDK 27 rejects its flags, so a thread repeatedly locking one object pays the atomic operations the bias skipped, and costly revocation is gone.

code

java · 13 lines
java
class SyncShapes {
    private int count;

    synchronized void method() {
        count++;
    }

    void block() {
        synchronized (this) {
            count++;
        }
    }
}

go deeper

for a junior

Recall the shape: a synchronized method is a flag in the class file, a synchronized block is a pair of monitorenter and monitorexit instructions, and leaving a block by exception still releases the lock.

for a middle

Explain the mechanics: the tag bits in the mark word, the per-thread lock stack, and what inflation means. Name contention and wait() as triggers, and say that no monitor structure exists until one is needed.

for a senior

Show production judgment: read inflation causes from monitorinflation logging and JFR, read a BLOCKED thread as inside the monitor's contended enter, spinning or parked, and check old advice against the running JDK, since UseBiasedLocking now stops a JDK 27 JVM from starting.

for a principal

Weigh the upgrade trade-off: retiring the bias moved cost onto single-threaded legacy synchronized paths while removing revocation and simplifying the VM. Decide what to benchmark before a JDK move, and where replacing old synchronized collections beats any flag.

**`synchronized` has two layers.** The JVM specification fixes the contract: each object is associated with a monitor, which is locked if and only if it has an owner, and the owner can re-enter it. It says the association "may be managed in various ways", so HotSpot, the JDK's JVM, builds no monitor structure until it needs one. The details below assume JDK 27. ## In the class file: a flag or two instructions This is trimmed `javap -c -v` output from JDK 27's `javac`, for a `count++` guarded both ways: ```text synchronized void method(); flags: (0x0020) ACC_SYNCHRONIZED void block(); 3: monitorenter ... 15: monitorexit 16: goto 24 19: astore_2 ... 21: monitorexit ... 23: athrow 24: return Exception table: from to target type 4 16 19 any 19 22 19 any ``` - **`ACC_SYNCHRONIZED`** is a method access flag. The invocation and return instructions honour it: the JVM enters the monitor (the receiver's, or the `Class` object's for a static method) and exits it whether the call completes normally or abruptly. - **`monitorenter` and `monitorexit`** encode a block, so the compiler must pair them. It keeps the lock object in a local and adds a catch-any handler, and the table's second row sends an exception thrown inside the handler back to it. - **The entry count** is the specification's model of reentrancy: entering sets it to one, re-entering increments it, `monitorexit` decrements it, and zero releases the monitor. ## The uncontended path: tag bits and a lock stack The low two bits of an object's **mark word** (its header word) hold the lock state: | Tag | State | Ownership recorded in | |---|---|---| | `01` | unlocked | nowhere | | `00` | fast-locked | the owner thread's `LockStack` | | `10` | inflated | the `ObjectMonitor`'s private `_owner` field | **Fast locking**, also called lightweight locking, is a compare-and-swap (CAS) from `01` to `00`, then a push of the object onto `LockStack`, a per-thread array of eight entries (`LockStack::CAPACITY`). Unlocking is a CAS back to `01` and a removal from the stack. On CPU ports that enable it (`VM_Version::supports_recursive_fast_locking()`), re-entering an object already on top of a stack with room just pushes it again with no atomic operation, so the recursion depth is the length of that run. `ObjectSynchronizer::enter` is this path's runtime version: interpreted and compiled code run a generated fast path and reach it when that fails, compiled code after trying `ObjectSynchronizer::quick_enter`. ## What makes a lock inflate Inflating means creating or finding an `ObjectMonitor` and setting the tag to `10`. Running with `-Xlog:monitorinflation=trace` prints each cause: - **Contention** (`Monitor Enter`): another thread holds the fast lock. With the monitor table on (see below), the contender first retries the CAS with exponential backoff (`FastLockingSpins`, a diagnostic flag, default 8), because a short critical section is not worth a monitor. - **Re-entry off the top of the stack, or on a full stack** (`Monitor Enter`): lock `a`, lock `b`, lock `a` again, or nest `a` a ninth time. - **`Object.wait()`** (`Monitor Wait`): a wait set needs a monitor. - **A full lock stack** (`VM Internal`): locking a new object inflates any contended entries on the stack, or failing that the oldest. - **JNI `MonitorEnter`** (`JNI Monitor Enter`). Some look-alikes do not inflate. `System.identityHashCode()` writes the hash into a fast-locked object's header, and `notify()` on a fast lock the caller holds returns at once, because an object without a monitor has no waiters. A fast-locked mark word does not say who holds the lock, so a contender inflates with an **anonymous owner**. The holder usually claims the monitor when its unlock sees tag `10`, and sooner if, for example, it calls `wait()` or blocks on another monitor first. `UseObjectMonitorTable` (a diagnostic flag, default true on JDK 27 and false on JDK 25 LTS, forced on with compact object headers) decides where the monitor lives. With it on, the header keeps its hash and class bits and a table keyed by identity hash finds the monitor, so inflating assigns a hash if the object has none. With it off, the mark word points to the monitor. ## Inside the heavyweight monitor 1. CAS the private `_owner` field to this thread's id; an owner re-entering increments the private `_recursions`. 2. Spin adaptively (the private `try_spin`), since the holder may finish soon. 3. Start reporting `Thread.State.BLOCKED`, spin once more, then join the private `_entry_list` and park; a thread that wakes and loses can spin again, so `BLOCKED` does not always mean parked. Since JDK 24 a virtual thread blocking here normally unmounts instead of pinning its carrier. 4. On exit, release `_owner` and wake a waiter if no successor is already chosen. The woken thread must still win `_owner`, and another thread may take it first, so this is not a strict FIFO handoff. Inflation is not permanent: a `MonitorDeflationThread` reclaims idle monitors. ## What removing biased locking changed **Biased locking** let the first locker bias an object to itself, so its later acquisitions needed no atomic instruction; when another thread tried the lock, the JVM ran an expensive revocation. | Release | Change | |---|---| | 15 | Biased locking off by default; `UseBiasedLocking` and related options deprecated (JEP 374) | | 18 | Those options obsolete: a warning, then ignored | | 21 | Lightweight locking added, selected by `-XX:LockingMode=2` (`LM_LIGHTWEIGHT`), an experimental flag until 22 made it a product flag | | 23 | `LM_LIGHTWEIGHT` becomes the default, replacing `LM_LEGACY`, stack locking that overwrote the header | | 24 | `LockingMode`, `LM_LEGACY` and `LM_MONITOR` deprecated | | 27 | Compact object headers (JEP 534) and `UseObjectMonitorTable` on by default; by now the JVM refuses to start on `-XX:LockingMode` or `-XX:+UseBiasedLocking` as unrecognized | - **Cost moved.** A thread repeatedly locking and unlocking an uncontended object pays a CAS each way, unless C2 coarsens the locks (`EliminateLocks`, on by default). JEP 374 names code that synchronizes on every access, such as `Hashtable` and `Vector`, as what benefited, so a regression may show there; newer collections are its remedy. - **Cost removed.** Revocation is gone, along with code JEP 374 calls an impediment to significant design changes in the synchronization subsystem; it also says thread-pool and worker designs generally perform better with the bias disabled. - **Semantics kept.** The bias was an optimization of uncontended locking, so what `synchronized` guarantees did not change. JDK 25 LTS has the same lightweight default but leaves both compact object headers and `UseObjectMonitorTable` off. So by default its mark word points to the monitor, inflating assigns no hash, and a contender inflates with no CAS retry, though the monitor's adaptive spin still runs. `-XX:+UseCompactObjectHeaders` turns the table on too, and the retry's flag is `LightweightFastLockingSpins`, default 13. The JVM still accepts `-XX:LockingMode` there, with a deprecation warning.

  • A contender inflates a lock another thread holds as a fast lock. How does the holder find out?
    Usually at unlock. A fast-locked mark word does not record the holder, so the contender publishes an `ObjectMonitor` with an anonymous owner and sets the tag to `10`. The holder's unlock then sees `10` instead of `00`. `ObjectSynchronizer::exit` finds the object on the holder's own `LockStack`, makes it the owner, copies the recursion depth into `_recursions`, and exits through the monitor, waking a waiter.
  • Does an inflated lock stay inflated for the life of the object?
    No. A `MonitorDeflationThread` reclaims monitors with no owner, contenders or waiters, and the object returns to the unlocked state, so its next uncontended lock is fast again. By default it runs every 60 seconds even when monitor use is low (`GuaranteedAsyncDeflationInterval`), and up to every 250 ms once monitor use passes a threshold (`AsyncDeflationInterval`). Both are diagnostic flags. A thread racing with deflation retries.
  • Why does javac's exception table for a synchronized block also cover the handler itself?
    The second row sends an exception thrown inside the handler back to the handler's start, so its `monitorexit` runs again. The JVM specification says the compiler ensures a `monitorexit` has run for each `monitorenter` at any method completion, normal or abrupt, using handlers that match any exception. A synchronized method needs none of this, because the JVM exits its monitor itself on abrupt completion.
  • How do you find out why a particular object's lock inflated on a running JVM?
    Turn on logging without a restart, `jcmd <pid> VM.log what=monitorinflation=trace output=stdout`, or start with `-Xlog:monitorinflation=trace`: each inflation logs the object's type and a cause such as `Monitor Enter`, `Monitor Wait` or `VM Internal`. JFR's `jdk.JavaMonitorInflate` event, when enabled, records inflation with a stack trace, and `jdk.JavaMonitorDeflate` shows monitors being reclaimed, so you can spot churn. `VM Internal` can mean the eight-entry lock stack overflowed rather than any contention.

A meeting room with a flip sign on the door: taking it uncontended means flipping the sign and noting it in your own pocket diary. When someone queues, or you step out to wait for a call-back, the building assigns a receptionist to keep the lists, and sends the receptionist away once the room sits idle.

  • A synchronized method compiles to monitorenter and monitorexit around its body.
  • Today's HotSpot upgrades a lock from biased to lightweight to heavyweight.
  • HotSpot allocates an ObjectMonitor for every object when the object is created.
  • Lightweight locking copies the object header onto the locking thread's stack.
  • Calling notify() while holding a lock always inflates that lock.
  • Removing biased locking changed what synchronized guarantees about exclusion or visibility.

Biased locking disabled by default
Java 15
Biased locking VM options obsoleted
Java 18
Lightweight locking mode
Java 22pre-release 21
Lightweight locking as the default
Java 23
Object monitor table on by default
Java 27

Assumes JDK 27, where lightweight locking is the only locking mode and compact object headers and the monitor table are on by default; JDK 25 LTS also defaults to lightweight locking, with both off by default, so its contended path and monitor placement differ.

context