Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: is CountDownLatch threadsafe

In the docs for CountDownLatch I see something like:

public void run() {
      try {
        startSignal.await();
        doWork();
        doneSignal.countDown();
      } catch (InterruptedException ex) {} // return;
}

Here startSignal and doneSignal are CountDownLatch objects.

The docs don't mention anything about the class being thread-safe or not.

like image 356
treecoder Avatar asked May 06 '15 10:05

treecoder


1 Answers

As it is designed to be used by multiple threads it would be fair to assume that it is thread-safe to most meanings of thread-safe.

There is even a happens-before commitment (from your link):

Memory consistency effects: Until the count reaches zero, actions in a thread prior to calling countDown() happen-before actions following a successful return from a corresponding await() in another thread.

With reference to your specific question What if two threads call countDown at the same time? Wouldn't it just do the count down action only once effectively? No, two countDowns will be actioned every time.

like image 79
OldCurmudgeon Avatar answered Oct 19 '22 06:10

OldCurmudgeon