AbstractQueuedSynchronizer Custom Shared Latch
Extend AbstractQueuedSynchronizer with tryAcquireShared and tryReleaseShared to rebuild a countdown latch from the shared queue primitives.
Code
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
public class GroupGate {
// a custom shared latch: state counts down, shared queue wakes all waiters at zero
static final class SharedLatch extends AbstractQueuedSynchronizer {
SharedLatch(int count) {
setState(count);
}
int remaining() {
return getState();
}
@Override
protected int tryAcquireShared(int unused) {
return getState() == 0 ? 1 : -1;
}
@Override
protected boolean tryReleaseShared(int unused) {
for (;;) {
int count = getState();
if (count == 0) {
return false;
}
if (compareAndSetState(count, count - 1)) {
return count - 1 == 0; // 归零时唤醒共享队列
}
}
}
}
public static void main(String[] args) throws InterruptedException {
SharedLatch latch = new SharedLatch(2);
Runnable waiter = () -> {
try {
latch.acquireSharedInterruptibly(1);
System.out.println("passed the gate");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
};
Thread first = new Thread(waiter, "first");
Thread second = new Thread(waiter, "second");
first.start();
second.start();
Thread.sleep(50);
System.out.println("remaining: " + latch.remaining());
latch.releaseShared(1);
latch.releaseShared(1);
first.join();
second.join();
}
}How the demo proceeds
The code’s whole job belongs to the classes GroupGate and SharedLatch and the functions tryAcquireShared and tryReleaseShared.
for (;;) is the loop that handles the per-item work.
Watch out for
- All symbols in play are built-ins of the language — nothing arrives over the network.
Using it
Signature: protected int tryAcquireShared(int unused)
Output lines are prefixed (passed the gate, remaining:), so the output keeps a visible trail from step to step.
Key statements
Thread second = new Thread(waiter, "second");
Thread first = new Thread(waiter, "first");
return count - 1 == 0; // 归零时唤醒共享队列
}
Interactive Tools for This Topic
FAQ
- What does AbstractQueuedSynchronizer Custom Shared Latch print when run?
- Run it as a complete program — the output lines carry labels such as `passed the gate`, `remaining:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.