2014-09-12 2 views
6

CountLatch는 스레드 제어 메커니즘으로 스레드 (또는 많은 스레드)가 을 CountLatch 개체에서 호출하여 차단할 수 있습니다. countDown() 메서드를 호출 할 때 해제됩니다. 시대의.QueudSynchronizer를 사용하여 CountLatch를 구현할 때의 이점은 무엇입니까

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(); 
    } 
} 

그러나, 자바 5가 자신의 구현을 제공합니다 : 나는 wait()notify()와 스레드 제어의 개념을 잘 알고 있기 때문에

,이 같은 CountLatch의 (나)는 명백한 구현이 , 은 AbstractQueuedSynchronizer에서 확장 된 내부 클래스를 사용합니다.

  • countDown() 전화 sync.releaseShared(1)
  • await() 전화

이 더 복잡한 접근 방식의 장점은 무엇입니까 sync.acquireSharedInterruptibly(1) :

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; 
      } 
     } 
    } 

자바 5 CountLatch이 동기화 객체의 래퍼 본질적?

답변

5

제안 된 접근법과 JDK의 가장 큰 차이점은 잠금을 사용하고있는 반면 AbstractQueuedSynchronizer은 잠금이없고 내부적으로 Compare-And-Swap을 사용하므로 중간 정도의 경합에서 더 나은 성능을 제공한다는 것입니다.

관련 문제