3

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?

Ivan Voroshilin
  • 5,233
  • 3
  • 32
  • 61
  • If it was allowed to be reused, what would stop you from reusing it while it is still counting? – Stav Saad Dec 04 '14 at 15:01
  • @Stav Saad If it's not 0 then don't allow, otherwise allow. I implemented my reusable Latch. Btw standard CyclicBarrier is reusable. I don't see the reason – Ivan Voroshilin Dec 04 '14 at 15:08

3 Answers3

5

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

Chilledrat
  • 2,593
  • 3
  • 28
  • 38
John Vint
  • 39,695
  • 7
  • 78
  • 108
1

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

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
  • 2
    Evgeniy Dorofeev I don't agree, CyclicBarrier waits for all threads to get together in 1 point of code whereas Latch works using events(countDown) and all participants wait in different parts of code. – Ivan Voroshilin Dec 04 '14 at 15:15
0

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'
Matej Tymes
  • 1,694
  • 1
  • 16
  • 30