Backend Development 19 min read

Deep Dive into Java synchronized and Lock Mechanisms: Principles, JVM Internals, and Optimizations

This article explains thread safety in Java by detailing how the synchronized keyword and various Lock implementations work, covering their underlying JVM mechanisms, lock upgrade paths, optimizations like biased and lightweight locks, and practical differences between synchronized, ReentrantLock, and ReadWriteLock.

Top Architect
Top Architect
Top Architect
Deep Dive into Java synchronized and Lock Mechanisms: Principles, JVM Internals, and Optimizations

Preface

Thread safety is a crucial concern in concurrent programming. Problems arise mainly from two sources: shared data (also called critical resources) and multiple threads operating on that shared data simultaneously.

To solve this, a mutual‑exclusion lock (mutex) ensures that at any moment only one thread can access the shared data while other threads must wait until the lock is released.

1. synchronized lock mechanism

1.1 Purpose of synchronized

The synchronized keyword makes the current thread hold the object's monitor, granting exclusive access to a method or code block and thus guaranteeing thread safety.

Instance method : locks the current instance.

Static method : locks the Class object.

Code block : locks a specified object.

1.2 Underlying semantics

In the JVM, synchronization is based on entering and exiting a monitor object. Each object header contains a monitor that tracks ownership. When a thread acquires the monitor, the owner field points to that thread and a counter is incremented. Calling wait() releases the monitor and decrements the counter, moving the thread to the _WaitSet . When the thread finishes, monitorexit releases the monitor and resets the counter.

1.3 Explicit vs. implicit synchronization

Explicit synchronization (synchronized blocks) uses the bytecode instructions monitorenter and monitorexit . Implicit synchronization (synchronized methods) is indicated by the ACC_SYNCHRONIZED flag in the method's constant‑pool entry; the JVM inserts the monitor instructions automatically.

1.3.1 Implementation of a synchronized block

The block is compiled to monitorenter at the start and monitorexit at the end. If the entry count of the monitor is zero, the thread acquires the lock and sets the count to one. Re‑entering the same monitor increments the count.

1.3.2 Implementation of a synchronized method

When a method is marked ACC_SYNCHRONIZED , the JVM acquires the monitor before executing the method and releases it after the method returns, regardless of normal or exceptional completion.

2. JVM optimizations for synchronized

2.1 Lock upgrade path

The JVM can upgrade a lock through four states: no‑lock, biased lock, lightweight lock, spin lock, and finally heavyweight lock. Biased and lightweight locks use CAS on the object’s Mark Word, avoiding OS mutexes.

2.1.1 Mark‑word flag bits

An object header consists of the object header, Mark Word, class pointer, array length (if applicable), instance data, and padding. The Mark Word stores hash code, generation age, and lock state.

2.1.2 Upgrade process

Biased lock : the first thread that acquires the lock records its thread ID in the Mark Word; subsequent acquisitions by the same thread are fast. If another thread competes, the lock is revoked and upgraded.

Lightweight lock : uses CAS to acquire the lock; suitable for short‑term contention.

Spin lock : the thread spins for a limited number of cycles before falling back to a heavyweight lock.

Adaptive spin : the JVM adjusts spin length based on recent lock acquisition history.

Heavyweight lock : falls back to an OS mutex when contention is high; waiting threads are placed in the _EntryList of the monitor.

2.2 Lock elimination

During JIT compilation, escape analysis can prove that a lock is not shared, allowing the JVM to remove the lock entirely.

2.3 Lock coarsening

If adjacent synchronized blocks use the same lock, the JIT may merge them into a single larger block to reduce lock‑acquire/release overhead.

3. Biased‑lock removal

From JDK 15 onward, biased locks are disabled because they add code complexity, provide diminishing performance benefits, and can degrade performance in thread‑pool‑heavy workloads.

4. Lock interface (java.util.concurrent.locks)

4.1 What is Lock?

The Lock interface (introduced in JDK 5) defines explicit lock operations such as lock() and unlock() . Implementations must be used with try/finally blocks to guarantee release.

4.2 ReentrantLock

ReentrantLock is built on AQS and provides the same re‑entrancy as synchronized but adds features like fairness policies, tryLock, interruptible lock acquisition, and multiple Condition objects.

4.2.1 Differences from synchronized

Explicit vs. implicit locking.

ReentrantLock can be fair; synchronized cannot guarantee fairness.

ReentrantLock supports tryLock() to test lock acquisition without blocking.

ReentrantLock can respond to thread interruption while waiting; synchronized cannot.

ReentrantLock allows multiple wait‑queues via Condition ; synchronized has a single monitor wait set.

4.3 ReadWriteLock

The ReadWriteLock interface separates read and write access. Its typical implementation ReentrantReadWriteLock provides a shared read lock and an exclusive write lock, improving throughput when reads dominate.

Conclusion

Both synchronized and ReentrantLock are re‑entrant locks. In most cases, the simpler synchronized keyword is preferred because it is easier to use and the JVM has heavily optimized it. When advanced features such as fairness, try‑lock, interruptibility, or multiple condition queues are required, ReentrantLock (or ReadWriteLock ) should be chosen.

Feel free to discuss, ask questions, or share your own insights about Java concurrency.

JavaJVMconcurrencymultithreadingLockReentrantLocksynchronizedreadwritelock
Top Architect
Written by

Top Architect

Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.

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.