Why can't CountDownLatch in java change its state again?

In Java, when CountdownLatch reaches its state = 0, it cannot change it, so it stays open forever. I wonder why the developers don't allow CountDownLatch to be reused?

+3


source to share


3 answers


If it was reused, how would you handle the different arrival iterations? For example, let's say you want to wait CountDownLatch

.

CountDownLatch latch = new CountDownLatch(1);

latch.await();

      

Then one thread calls

latch.countDown();



Released await

. You now have another thread that should only be released if the previous thread has been counted. Therefore, you call latch.await()

. If the latch is to be mutable, should the thread wait or continue? How would the latch know that this wait shouldn't be for another cycle (or phase)?

In the end, this is not true. The switchable latch is tricky, but it's possible. Java 7 came out with Phaser . It treats each subsequent iteration as a phase, and you can tell the phaser to wait at a specific phase:

phaser.awaitAdvance(phase);

+5


source


Because this is the CountDownLatch function. If CountDownLatch is to reset its counter then it will behave the same as CyclicBarrier



+1


source


You can 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 just add the dependency:

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

      

0


source







All Articles