Understanding Java's AbstractQueuedSynchronizer (AQS) and Concurrency Utilities
This article provides an in-depth explanation of Java's AbstractQueuedSynchronizer (AQS) framework, covering its role in JUC concurrency utilities such as locks, semaphores, CountDownLatch, ReentrantReadWriteLock, and Condition, including template methods, state management, node structures, queue algorithms, and practical code examples.
Java's concurrency utilities (JUC) were created by Doug Lea to improve performance beyond the heavyweight synchronized keyword, and the core of many utilities is the AbstractQueuedSynchronizer (AQS).
AQS implements a template‑method pattern where subclasses provide concrete implementations of methods such as tryAcquire , tryRelease , tryAcquireShared , and tryReleaseShared . The framework maintains a FIFO CLH queue of Node objects that represent waiting threads.
Key fields of Node include prev , next , thread , waitStatus (CANCELLED, SIGNAL, CONDITION, PROPAGATE, etc.), and nextWaiter for condition queues. The state variable is a volatile long that stores lock state; for ReentrantReadWriteLock the high 16 bits hold the read count and the low 16 bits hold the write count.
The main acquisition path is acquire(int arg) for exclusive locks and acquireShared(int arg) for shared locks. If tryAcquire fails, the thread is added to the queue via addWaiter , possibly spinning with enq , and then blocks with LockSupport.park after shouldParkAfterFailedAcquire returns true. Release operations invoke tryRelease and wake the successor with unparkSuccessor .
Condition objects maintain a separate wait queue (firstWaiter/lastWaiter). Methods await and signal / signalAll transfer nodes between the condition queue and the main AQS queue, using transferForSignal and transferAfterCancelledWait . This provides a more flexible and efficient alternative to Object's wait/notify .
Examples in the article illustrate custom lock implementations, usage of CountDownLatch , Semaphore , and ReentrantReadWriteLock , together with the underlying AQS code snippets.
Full-Stack Internet Architecture
Introducing full-stack Internet architecture technologies centered on Java
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.