Skip to content

Instantly share code, notes, and snippets.

@liuzhengyang
Created May 18, 2016 01:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save liuzhengyang/aa7cb450e91057d36bc7ee72c6a2ba11 to your computer and use it in GitHub Desktop.
Save liuzhengyang/aa7cb450e91057d36bc7ee72c6a2ba11 to your computer and use it in GitHub Desktop.
count down latch using aqs
private final class Sync extends AbstractQueuedSynchronizer {
private int count;
public Sync(int count) {
this.count = count;
}
@Override
protected int tryAcquireShared(int arg) {
return (getState() == 0 ? 1 : -1);
}
@Override
protected boolean tryReleaseShared(int arg) {
for (;;) {
int c = getState();
if (c == 0) {
return false;
}
int nextc = c - 1;
if (compareAndSetState(c, nextc)) {
return nextc == 0;
}
}
}
}
private Sync sync = null;
private int count;
public MyCountDown(int count) {
this.sync = new Sync(count);
}
public void await() throws InterruptedException {
sync.acquireSharedInterruptibly(1);
}
public void countDown() {
sync.releaseShared(1);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment