Deep Dive into Java synchronized: Usage, JVM Implementation, and Lock Upgrade Mechanisms
This article explains the Java synchronized keyword, its three usage forms, the underlying JVM object header and monitor structures, the lock acquisition process, and the progression from no lock through biased, lightweight, and heavyweight locks, illustrating how synchronization ensures thread safety.
In Java, the synchronized keyword provides a monitor lock that ensures only one thread can execute the protected code block or method at a time, guaranteeing thread‑safety.
Synchronized Usage
There are three ways to apply synchronized:
On an instance method – the lock is on the current object instance.
On a static method – the lock is on the Class object.
On a synchronized block – the lock is on an explicit object (e.g., this).
public synchronized void method() {
// code
} public static synchronized void method() {
// code
} synchronized(this) {
// code
}Underlying JVM Implementation
The implementation relies on the object header stored in the JVM. Each object header contains a Klass pointer and a Mark Word. The Mark Word holds runtime data such as hash code, GC age, lock state, thread ID, and bias information, and it is the actual lock field used by synchronized.
A monitor (object monitor) is attached to each object; it acts like a special room where only one thread may hold the monitor at a time. Entering the monitor corresponds to monitorenter, exiting corresponds to monitorexit.
Thread State Transitions in a Monitor
When multiple threads contend for the same monitor, the JVM maintains several queues and states: Contention List, Entry List, Wait Set, OnDeck, Owner, and !Owner, reflecting the lifecycle of lock acquisition and release.
Lock Upgrade Path
To reduce the overhead of locking, HotSpot performs lock escalation based on contention:
No‑Lock : no synchronization, threads may race.
Biased Lock : assumes a single thread repeatedly acquires the lock, eliminating most synchronization costs.
Lightweight Lock : if another thread attempts to acquire a biased lock, it upgrades to a lightweight lock using spin‑waiting without blocking.
Heavyweight Lock : the classic monitor where contending threads are blocked until the owner releases the lock.
Understanding these mechanisms helps developers write more efficient concurrent Java code and diagnose performance issues related to synchronization.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
