What is Java's AbstractQueuedSynchronizer, how do ReentrantLock and Semaphore map onto its state, and when would you subclass it?
answer
- a framework, not a lock you call
- one atomic number, meaning left to subclass
- try methods decide; the base class queues
- hold count versus available permits
- FIFO queue, yet arrivals may barge
basics
~20 sAbstractQueuedSynchronizer is the framework under ReentrantLock and Semaphore: one atomic int state whose meaning the subclass defines, plus a FIFO queue of waiting threads. Subclass it only when no existing synchronizer gives the acquire and release rules you need.
solid answer
~50 s`AbstractQueuedSynchronizer` (AQS) is the framework in `java.util.concurrent.locks` that does the queuing and blocking for synchronizers built on one atomic `int` `state`. A subclass gives `state` its meaning by overriding `tryAcquire` and `tryRelease` for **exclusive** mode, or `tryAcquireShared` and `tryReleaseShared` for **shared** mode, and AQS puts failed threads in a FIFO wait queue and parks them with `LockSupport`. `ReentrantLock` uses `state` as an exclusive hold count, with 0 meaning free, and `Semaphore` uses it as a shared count of available permits. The queue does not make acquisition FIFO: a new thread can barge, and a fair subclass typically makes its try method fail when `hasQueuedPredecessors()` returns `true`. I would subclass only when no existing class gives the rules I need and they reduce to an atomic update of one `int`, or one `long` with `AbstractQueuedLongSynchronizer`; otherwise I compose `ReentrantLock` and `Condition`, as `CyclicBarrier` does.
code
java · 28 linesimport java.util.concurrent.locks.AbstractQueuedSynchronizer;
public final class NonReentrantLock {
private static final class Sync extends AbstractQueuedSynchronizer {
@Override protected boolean tryAcquire(int unused) {
if (compareAndSetState(0, 1)) { // state: 0 = free, 1 = held
setExclusiveOwnerThread(Thread.currentThread());
return true;
}
return false; // AQS queues and parks the caller
}
@Override protected boolean tryRelease(int unused) {
if (getExclusiveOwnerThread() != Thread.currentThread()) {
throw new IllegalMonitorStateException();
}
setExclusiveOwnerThread(null);
setState(0); // volatile write publishes the release
return true; // AQS wakes the first queued thread
}
}
private final Sync sync = new Sync();
public void lock() { sync.acquire(1); }
public void unlock() { sync.release(1); }
public boolean tryLock() { return sync.tryAcquire(1); }
}go deeper
Recall that AQS is the abstract base under ReentrantLock and Semaphore, holding an int state and a queue of waiting threads. You normally use those classes, not AQS itself.
Explain the split: the subclass's try methods read and change state, and AQS does the queuing and parking. Map a hold count onto ReentrantLock and permits onto Semaphore, and say why a FIFO queue still allows barging.
Use it to read production behaviour: threads queued in ReentrantLock.lock() show WAITING with the lock's Sync object as their blocker, not BLOCKED on a monitor. Reach for composition first, and justify a subclass by rules no existing class offers.
Treat a custom synchronizer as code the team owns for years, with subtle races and few reviewers able to check them. Set JDK classes as the default, and ask for a written case and stress tests before accepting a subclass.
## What AQS is `java.util.concurrent.locks.AbstractQueuedSynchronizer` (**AQS**) is an abstract class, available since Java 1.5, that provides a framework for blocking locks and related synchronizers built on first-in-first-out (FIFO) wait queues. It is not a lock you create and call. It implements no synchronization interface, and its documentation says subclasses should be non-public internal helpers. `ReentrantLock`, `Semaphore` and `CountDownLatch` follow that: each implements its public methods through a nested class called `Sync`. The design splits the work in two: - **The subclass supplies the policy.** It overrides the protected methods `tryAcquire`, `tryRelease`, `tryAcquireShared`, `tryReleaseShared` and, if it offers conditions, `isHeldExclusively`. Each default throws `UnsupportedOperationException`, so a subclass defines only the mode it supports. - **AQS supplies the mechanics.** Its final methods, such as `acquire`, `release`, `acquireInterruptibly` and `tryAcquireNanos`, handle queuing, blocking, interruption and timeouts. ## The state and the queue An AQS instance holds two things that matter: - **`state`** is a private `volatile int`, reached through the protected final methods `getState()`, `setState()` and `compareAndSetState()`, the last being an atomic compare-and-set (**CAS**). AQS gives the number no meaning. A subclass may keep other fields, but only this value is tracked for synchronization. - **The wait queue** is a linked variant of a **CLH queue** (named for Craig, Landin and Hagersten), held in the private fields `head` and `tail`. A thread joins with one CAS on `tail`. The dummy head node is created at first contention, not at construction. Older write-ups describe queue members such as `waitStatus` and `SIGNAL`. JDK 27's source has neither name: its package-private `Node` class has a `status` field using the bits `WAITING`, `CANCELLED` and `COND`. Treat these names as implementation detail, not API. ## Exclusive and shared mode - **Exclusive mode:** once acquired, acquires by other threads cannot succeed. - **Shared mode:** acquires by several threads may, but need not, succeed. AQS does not otherwise understand the difference. Mechanically, when a shared acquire succeeds, the next waiter is signalled if it is also shared, so it can try as well. Waiters in both modes share one queue. Most subclasses support one mode, and a read-write lock uses both. ## How the JDK's classes map onto state | Class | `state` means | Mode | Acquire | Release | |---|---|---|---|---| | `ReentrantLock` | hold count, 0 is free | exclusive | CAS from 0 to 1, or the owner increments | decrement; at 0, clear the owner and wake a waiter | | `Semaphore` | available permits | shared | CAS down; a negative result queues without changing `state` | CAS up, then wake a waiter | | `CountDownLatch` | remaining count | shared | succeeds when `state` is 0, without changing it | CAS down; wake only on reaching 0 | `ReentrantLock`'s `Sync` keeps the owner in `exclusiveOwnerThread`, a private field of `AbstractOwnableSynchronizer`, the superclass of AQS, and the lock documents a limit of 2147483647 recursive locks, the largest `int`. `Semaphore` records no owner. `ReentrantReadWriteLock` shows the other variant in JDK 25 and 27: its package-private `Sync` extends `AbstractQueuedLongSynchronizer`, which has the same structure with a `long` state, and keeps write holds in the low 32 bits and read holds in the high 32. JDK 21's documentation gave a limit of 65535 for each; those of JDK 25 and 27 give `Integer.MAX_VALUE`. ## What happens under contention 1. `acquire(1)` calls `tryAcquire`. If it succeeds, the queue is never touched. 2. Otherwise the package-private overload of `acquire` loops: it creates a node and adds it to `tail` by CAS. A thread not yet queued, or first in the queue, retries the try method on each pass. 3. It marks the node `WAITING`, goes round the loop again to recheck, and then calls `LockSupport.park(this)`. 4. `release(1)` calls `tryRelease`. If that returns `true`, the private `signalNext(head)` unparks the thread behind the head. 5. The woken thread tries again. Being first gives it the right to contend, not success. Step 5 is why **a FIFO queue does not mean FIFO acquisition**. The try method runs before enqueuing, so a newly arriving thread can **barge** past queued ones, and the documentation says throughput is generally highest that way. Most fair synchronizers make their try method fail when `hasQueuedPredecessors()` returns `true`, and other inspection methods can serve too. Even a fair `ReentrantLock` or `Semaphore` lets its untimed `tryLock()` or `tryAcquire()` barge; whether to choose fairness is a question for those classes themselves. ## When to subclass and when to compose Start with what exists, as the JDK itself often does: `CyclicBarrier` is a `ReentrantLock` with a `Condition`, and `LinkedBlockingQueue` is two locks with conditions. Subclass AQS when all of these hold: - **No existing class has the rules.** `ThreadPoolExecutor`'s private `Worker` class subclasses AQS for a non-reentrant lock, because a task calling a pool method such as `setCorePoolSize` must not be able to reacquire it. - **The rules reduce to one atomic value**, an `int`, or a `long` with the long variant. - **You want the mechanics**: queuing, timeouts, cancellation and, in exclusive mode, `ConditionObject`. Try methods must be thread-safe and should be short and not block. When the model does not fit, the documentation points to atomic classes, your own `Queue` and `LockSupport`. `Phaser` keeps a `long` state with its own stacks of waiters, and `StampedLock` uses its own modified CLH queue, so neither extends AQS.
- How does a fair synchronizer stop barging on top of AbstractQueuedSynchronizer?Most fair synchronizers have tryAcquire or tryAcquireShared report failure when hasQueuedPredecessors() returns true, unless the acquire is reentrant; other inspection methods can serve too. The fair versions of ReentrantLock and Semaphore make this check, yet their untimed tryLock() and tryAcquire() skip it and can still barge. AQS does not decide fairness itself. Its documentation says throughput and scalability are generally highest with default barging, which is not guaranteed to be fair or starvation-free.
- What does the int returned by AQS's tryAcquireShared mean?A negative value means failure, so the thread may queue. Zero means this acquire succeeded but no later shared acquire can. A positive value means it succeeded and later ones might, so a waiting thread must check. Semaphore returns its remaining permits, or -1 on its fair path when a predecessor is queued, and CountDownLatch returns 1 once its count is 0 and -1 before that.
- Why does ReentrantReadWriteLock's internal Sync extend AbstractQueuedLongSynchronizer rather than AbstractQueuedSynchronizer?The lock packs two counts into one atomic value and gives each 32 bits, so its package-private Sync extends AbstractQueuedLongSynchronizer, which is the same class shape with a long state. The low 32 bits hold write holds and the high 32 hold read holds, and the documented limit for each is Integer.MAX_VALUE. JDK 21's documentation still gave 65535.
- AQS is a lock you create and call directly from application code.
- The FIFO wait queue guarantees that threads acquire in arrival order.
- ReentrantLock's state is a boolean flag, with reentry counted somewhere else.
- Semaphore's state goes negative to count the threads waiting for permits.
- Exclusive and shared waiters sit in two separate AQS queues.
- In JDK 27, AQS queue nodes still carry waitStatus with SIGNAL and PROPAGATE values.
- AbstractQueuedSynchronizer
- Java 1.5
- ReentrantLock
- Java 1.5
- Semaphore
- Java 1.5
- AbstractQueuedSynchronizer.hasQueuedPredecessors
- Java 1.7
Assumes JDK 27; AQS's package-private queue members are implementation detail, and older write-ups name ones that JDK 27 does not have.
context
- AbstractQueuedSynchronizer (Java SE 27 & JDK 27)docs.oracle.com
- ReentrantLock (Java SE 27 & JDK 27)docs.oracle.com
- Semaphore.java at jdk-27-gagithub.com