The source code of JDK1.8 is implemented by AQS shared lock.What are the considerations for using shared locks? Why not use exclusive locks? Attached below is the code implemented by my exclusive lock:
public class MyCountDownLatch {
private static final class Sync extends AbstractQueuedSynchronizer {
Sync(int count) {
setState(count);
}
int getCount() {
return getState();
}
protected boolean tryAcquire(int acquires) {
return (getState() == 0) ? true :false;
}
protected boolean tryRelease(int releases) {
// Decrement count; signal when transition to zero
for (;;) {
int c = getState();
if (c == 0)
return false;
int nextc = c-1;
if (compareAndSetState(c, nextc))
return nextc == 0;
}
}
}
private final MyCountDownLatch.Sync sync;
public MyCountDownLatch(int count) {
this.sync = new MyCountDownLatch.Sync(count);
}
public void await() throws InterruptedException {
sync.acquireInterruptibly(1);
}
public void countDown() {
sync.release(1);
}
public static void main(String[] args) throws InterruptedException {
MyCountDownLatch myCountDownLatch = new MyCountDownLatch(5);
for(int i=0;i<5;i++){
new Thread(()-> {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"start");
myCountDownLatch.countDown();
}).start();
}
myCountDownLatch.await();
System.out.println("finished");
}
}
well, shared lock
means, that you can have more than 1 Thread waiting for completion. If you would implement it using exclusive lock
, then you would be able to wait only by 1 Thread.