What is the advantage of using QueuSynchronizer to implement the CountLatch function

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) { // 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; } } } 

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?

+6
source share
1 answer

The main difference between your proposed approach and the JDK is that you use locks, while AbstractQueuedSynchronizer free of locks and uses the Compare-And-Swap internal environment, which provides better performance with moderate competition.

+5
source

Source: https://habr.com/ru/post/975188/


All Articles