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