CountLatch is a thread control mechanism by which a thread (or many threads) can block by calling await() on a CountLatch object that will be released when its countDown() method countDown() been called a number of times.
Since I am familiar with the concept of flow control with wait() and notify() , there is (for me) an obvious CountLatch implementation, for example:
private volatile int count; // initialised in constructor public synchronized void countDown() { count--; if(count <= 0) { notifyAll(); } } public synchronized void await() throws InterruptedException { while(count > 0) { wait(); } }
However, Java 5 provides its own implementation, java.util.concurrent.CountLatch , which uses an inner class extended from AbstractQueuedSynchronizer .
private static final class Sync extends AbstractQueuedSynchronizer { Sync(int count) { setState(count); } int getCount() { return getState(); } protected int tryAcquireShared(int acquires) { return (getState() == 0) ? 1 : -1; } protected boolean tryReleaseShared(int releases) {
The Java 5 CountLatch is essentially a wrapper around this Sync object:
countDown() calls sync.releaseShared(1)await() calls sync.acquireSharedInterruptibly(1)
What is the advantage of this more complex approach?
slim source share