Fundamentals 24 min read

Understanding the Implementation and Optimization of Java's synchronized Keyword

This article explains how the synchronized keyword is implemented in the JVM using monitorenter and monitorexit instructions, examines the structure of Java object headers and monitor objects, and details the evolution from heavyweight locks to biased and lightweight locks along with other performance optimizations.

Qunar Tech Salon
Qunar Tech Salon
Qunar Tech Salon
Understanding the Implementation and Optimization of Java's synchronized Keyword

When Java developers first learn multithreading, they often rely on the synchronized keyword as a simple way to protect critical sections, but its underlying implementation involves complex JVM mechanisms.

Usage Introduction – The keyword can be applied to instance methods, static methods, or arbitrary code blocks, for example:

public synchronized void instanceMethod() { /* ... */ }
public static synchronized void staticMethod() { /* ... */ }
synchronized (this) { /* ... */ }

Underlying Semantics – Regardless of how it is used, the compiler translates synchronized into the bytecode instructions monitorenter and monitorexit . These instructions acquire and release a monitor associated with the target object.

Class Example and Bytecode – Consider the following test class:

public class SynchronizedTest {
    public void synMethod0() {
        synchronized (this) {
            // do something
        }
    }
    public synchronized void synMethod1() { }
    public static synchronized void synMethod2() { }
}

Running javap -v -p -s -sysinfo -constants SynchronizedTest.class reveals the constant pool, method descriptors, and the ACC_SYNCHRONIZED flag, as well as the bytecode where monitorenter and monitorexit appear.

Java Object Header and Monitor – Every object contains a header (Mark Word) that stores hash code, generation age, and lock state. When a lock is taken, the Mark Word is transformed to point to a ObjectMonitor structure (simplified excerpt):

struct ObjectMonitor {
    void* _header = NULL;
    int   _count = 0;            // number of waiters
    int   _waiters = 0;          // waiting threads
    int   _recursions = 0;       // re‑entry count
    void* _object = NULL;       // associated object
    void* _owner = NULL;        // owning thread
    // ... other fields for wait sets, queues, etc.
}

Only when contention occurs does the JVM allocate a monitor; otherwise the object header alone holds the lock state.

Heavyweight Lock – The monitorenter implementation in InterpreterRuntime::monitorenter eventually calls ObjectMonitor::enter , which uses a CAS operation to set the owner field. If the CAS fails because another thread owns the monitor, the thread is placed in the _cxq queue, may spin, and finally parks (blocks) until the lock is released.

void ObjectMonitor::enter(TRAPS) {
    Thread* Self = THREAD;
    void* cur;
    cur = Atomic::cmpxchgptr(Self, &owner, NULL);
    if (cur == NULL) { /* fast path */ return; }
    if (cur == Self) { _recursions++; return; }
    // enqueue, spin, park, etc.
}

Lock Optimizations (JDK 1.6+)

Biased Lock – The Mark Word stores the thread ID of the last owner; if the same thread repeatedly acquires the lock, no CAS is needed. The lock can be revoked if another thread attempts to acquire it.

Lightweight Lock – The Mark Word is replaced with a pointer to a lock record on the stack; threads compete using CAS and spin before inflating to a heavyweight monitor.

Other Optimizations – Adaptive spinning adjusts spin length based on past success, lock coarsening merges adjacent lock/unlock pairs into a larger region, and lock elimination removes locks for objects that never escape the thread.

A comparison of the three lock types shows their trade‑offs in overhead, CPU usage, and suitability for different contention scenarios.

Thread States – The article also reviews Java thread lifecycle states (NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, TERMINATED) to illustrate how monitors interact with thread scheduling.

JavaJVMconcurrencylockingsynchronizedMonitor
Qunar Tech Salon
Written by

Qunar Tech Salon

Qunar Tech Salon is a learning and exchange platform for Qunar engineers and industry peers. We share cutting-edge technology trends and topics, providing a free platform for mid-to-senior technical professionals to exchange and learn.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.