Deep Dive into the Underlying Implementation of Java's synchronized Keyword
This article explains the purpose, usage patterns, JVM-level object header and monitor mechanisms, lock state transitions, and lock‑upgrade strategies of Java's synchronized keyword, providing code examples and visual diagrams to illustrate how thread synchronization is achieved internally.
The synchronized keyword ensures that only one thread can execute a marked code block or method at a time, providing mutual exclusion for shared resources.
There are three ways to use it:
1. Instance method – locks the current object.
public synchronized void method(){
// code
}2. Static method – locks the Class object.
public static synchronized void method(){
// code
}3. Synchronized block – locks an explicit object.
synchronized(this){
// code
}The implementation relies entirely on the JVM. Each Java object contains a header composed of a Klass pointer and a Mark Word. The Mark Word stores runtime data such as hash code, GC age, lock state, and thread ID, and it is the actual lock holder for synchronized .
Each object also has an associated monitor (object monitor) that acts like a special room; a thread must acquire the monitor (monitorenter) to enter the synchronized block and releases it (monitorexit) when leaving.
When multiple threads contend for the same monitor, the JVM manages several internal states:
Contention List – all threads requesting the lock.
Entry List – candidates eligible to acquire the lock.
Wait Set – threads that called wait() and are blocked.
OnDeck – the single thread currently competing for the lock.
Owner – the thread that currently holds the lock.
!Owner – the thread that releases the lock.
Lock acquisition can evolve through four levels to balance safety and performance:
1. No lock – no synchronization, threads may overwrite each other.
2. Biased lock – optimizes the common case where a lock is repeatedly acquired by the same thread.
3. Lightweight lock – when contention appears, the biased lock upgrades to a lightweight lock that uses spinning instead of blocking.
4. Heavyweight lock – the traditional monitor implementation where contending threads are blocked until the owner releases the lock.
Understanding these mechanisms helps developers write efficient multithreaded Java code and diagnose performance issues related to synchronization.
Mike Chen's Internet Architecture
Over ten years of BAT architecture experience, shared generously!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.