Inside Java’s ReentrantLock: How AQS Powers Lock Acquisition and Release
This article explains how Java’s ReentrantLock relies on the AbstractQueuedSynchronizer (AQS) to manage lock state and a FIFO wait queue, detailing the step‑by‑step acquisition process with CAS, node insertion, parking, and the release mechanism that unparks successors.
Java developers are familiar with lock classes such as ReentrantLock, which solve thread‑safety when multiple threads access shared resources. This article explores how the underlying AbstractQueuedSynchronizer (AQS) implements the lock’s behavior.
Lock acquisition
The process starts with the Sync inner class (a subclass of AQS) that maintains the lock state and a FIFO wait queue. When a thread calls lock() , the non‑fair implementation first attempts a CAS operation to set state from 0 to 1. If the CAS succeeds, the thread becomes the owner; otherwise it invokes acquire() to join the wait queue.
When a second thread attempts to lock while the state is already 1, it fails the CAS, creates a Node representing itself, and inserts the node into the doubly‑linked queue via addWaiter() . The thread then calls acquireQueued() , which repeatedly invokes tryAcquire() and, if still unsuccessful, parks the thread using LockSupport.park() .
Lock release
Calling unlock() delegates to AQS’s release() , which invokes tryRelease() in the Sync subclass. The method decrements the state and, when it reaches zero, clears the owner and returns true. Afterwards unparkSuccessor() wakes the next waiting node (the one whose waitStatus is not cancelled) by invoking LockSupport.unpark() , allowing that thread to retry acquisition.
In summary, AQS maintains a state counter and a FIFO wait queue. Successful lock acquisition increments state ; failure enqueues the thread and parks it until the lock is fully released, at which point the next thread is unparked and can acquire the lock.
Sanyou's Java Diary
Passionate about technology, though not great at solving problems; eager to share, never tire of learning!
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.