I understand I could simply use CountDownLatch directly, however, as an excercise and to understand Phaser better, I would like to use it instead of COuntDownLatch.
Thus, I would create N number of awaiters, and one thread that needs to flip the latch. All awaiters, if arrive before the flip, would block, however after the latch is counted-down, then all subsequent await() returns instantly.
WIth Phaser I am not sure how to achieve this... Barrier is easy, as we have N + 1 threads, each arriving and awaiting. However, to make sure that no thread will await after the first phase, somehow eludes me.
The only way I could come up with, which is not nice, is as follows:
Phaser p = new Phaser(1);
int phase = p.getPhase();
....
// thread that awaits()
new Thread(new Runnable() {
....
p.awaitAdvance(phase)
}
And the other thread simply advances the phaser to next phase. This is not ideal, so any pointers would be appreciated.
TL;DR: In this context use
Phaser.arriveAndDeregister()for a non-blocking signal to the waiters of the phaser, which corresponds to operationCountDownLatch.countDown().PhaserandCountDownLatch. The first thing to clarify is that aPhasercannot generally encode aCountDownLatch. The tasks synchronizing with aPhasermust all wait for each other (all-to-all synchronization). In aCountDownLatch, there is a group of tasks that awaits some other task to open the latch.PhaserandCyclicBarrier. Both of these mechanisms are used for all-to-all synchronization. The two differences between them are: 1) aPhaserthe set of tasks using the phaser may grow during the life cycle of the phaser, whereas in aCyclicBarrierthe number of participants is fixed; 2) withPhasers, a task may notify other members (participants) and not wait as long as it deregisters from that phaser, whereas all tasks using the cyclic barrier can only wait-and-notify.Encoding a
CountDownLatchwith aPhaser. To encode a CountDownLatch(1) with a phaser you need to keep in mind the following:new Phaser(PARTIES_COUNT)or viaPhaser.register.CountDown.await()=Phaser.arriveAndAwaitAdvance()CountDown.countDown()=Phaser.arriveAndDeregister()Example. Suppose you want the child task to wait for the parent's task signal. Using
CountDownLatchyou would write:Using a
Phaseryou would write:You might want to look at this post for another example.