Why CountDownLatch in java cannot change its state again?

2.3k views Asked by At

In Java once a CountdownLatch reaches its state = 0, it cannot change it, so it remains open forever. I wonder why implementors don't allow to reuse CountDownLatch?

3

There are 3 answers

0
John Vint On BEST ANSWER

If it were reusable how would you handle different iterations of arrival? For instance, lets say you want to wait on the CountDownLatch.

CountDownLatch latch = new CountDownLatch(1);

latch.await();

Then one threads invokes

latch.countDown();

The await is released. Now you have another thread that should only release if the previously thread counted down. So you invoke latch.await(). If the latch were to be mutable, should the thread wait or continue through? How would the latch know this await should not be for another cycle (or phase)?

In the end, it doesn't and rightfully so. A mutable latch is difficult, but it is possible. Java 7 came out with a Phaser. It treats each next iteration as a phase and you can tell the phaser to await on a particular phase:

phaser.awaitAdvance(phase);

1
Evgeniy Dorofeev On

Because it is CountDownLatch specific feature. If CountDownLatch would reset its counter then it would behave rather like as CyclicBarrier

0
Matej Tymes On

You coud do this instead:

ReusableCountLatch latch = new ReusableCountLatch(); // creates latch with initial count 0
ReusableCountLatch latch2 = new ReusableCountLatch(10); // creates latch with initial count 10

latch.increment(); // increments counter

latch.decrement(); // decrement counter

latch.waitTillZero(); // blocks until counts falls to zero

boolean succeeded = latch.waitTillZero(200, MILLISECONDS); // waits for up to 200 milliseconds until count falls to zero

int count = latch.getCount(); // gets actual count

to use it you just add a dependency:

compile 'com.github.matejtymes:javafixes:1.3.0'