Understanding Java Locks: volatile, synchronized, monitor, CAS, and AQS
This article explains why locks are needed in Java, describes the fundamentals of volatile and synchronized, details the monitor‑based implementation of synchronized, introduces CAS operations, and outlines advanced lock mechanisms such as biased, lightweight, lock coarsening, elimination, and the AbstractQueuedSynchronizer framework.
Locks are used to prevent dirty reads and data inconsistency caused by concurrent operations.
2.1 volatile
Java allows threads to access shared variables; volatile ensures visibility of updates across threads and can be more convenient than locks in some cases.
2.2 synchronized
Basic principle : every Java object can act as a lock. The lock can be applied to ordinary synchronized methods (instance lock), static synchronized methods (class lock), or synchronized blocks (specified object).
When a thread enters a synchronized block it must acquire the monitor lock; the lock is released when the thread exits or throws an exception.
2.2.1 Implementation of synchronized
Synchronized is built on the Monitor mechanism, which provides mutual exclusion and cooperation.
Mutual exclusion: only one thread can execute the critical section.
Cooperation: threads use wait , notify , and notifyAll to coordinate.
The monitor works as follows:
A thread attempts to acquire the monitor; if successful it becomes the owner.
The owner can call wait to release the monitor and join the wait set.
Another thread calls notify / notifyAll to wake waiting threads, which must reacquire the monitor.
When the synchronized method finishes, the thread releases the monitor.
2.2.2 Bytecode implementation
The compiler generates monitorenter at the beginning of a synchronized block and monitorexit at the end. monitorenter tries to obtain the object's monitor; if the monitor is already owned, the thread blocks until it becomes available. monitorexit releases the monitor, decreasing the monitor entry count.
2.2.3 Lock location
The lock flag is stored in the object header’s Mark Word.
2.2.4 Lock optimizations
Since Java 6, the JVM introduces biased locks and lightweight locks to reduce the cost of acquiring and releasing locks. Locks can be in four states: no lock, biased lock, lightweight lock, and heavyweight lock, which upgrade based on contention but never downgrade.
Biased lock
Used when there is no contention; it avoids atomic operations by assuming the lock is always held by the same thread.
Lightweight lock
Suitable for scenarios where threads alternate execution of synchronized blocks.
Lock coarsening
Combines adjacent lock/unlock pairs into a larger lock region to reduce overhead.
Lock elimination
The JIT compiler removes locks that are proven to have no shared data contention.
Adaptive spinning
Adjusts spin‑wait duration based on recent lock acquisition history to avoid unnecessary CPU usage.
2.3 CAS
Compare‑And‑Swap (CAS) is an atomic operation that updates a memory location only if it matches an expected value, providing a lock‑free way to achieve synchronization. It is implemented using the processor’s CMPXCHG instruction.
Advantages: low overhead when contention is low.
Disadvantages: high CPU cost under contention, ABA problem, and only works for a single variable.
3.1 AbstractQueuedSynchronizer (AQS)
AQS is a framework for building locks and other synchronizers. It uses an int state field and a FIFO double‑linked queue to manage waiting threads.
Exclusive mode (e.g., ReentrantLock ) allows only one thread to hold the lock.
Shared mode (e.g., CountDownLatch ) allows multiple threads to acquire the lock simultaneously.
The acquisition process involves threads creating nodes, enqueuing them, and the head node releasing the lock to its successor.
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.
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.