For Phaser I have answered a few questions. Seeing them may help in understanding their applications. They are linked at the bottom. But to understand what the Phaser does and why its useful its important to know what it solves.
Here are attributes of a CountdownLatch and CyclicBarrier
Note:
- Number of parties is another way of saying # of different threads
- Not Reusable means you will have to create a new instance of the
barrier before reusing
- A barrier is advanceable if a thread can arrive and continue doing work
without waiting for others or can wait for all threads to complete
CountdownLatch
- Fixed number of parties
- Not resuable
- Advanceable (look at
latch.countDown();
advanceable
latch.await();
must wait )
CyclicBarrier
- Fixed number of parties
- Reusable
- Not advanceable
So the CountdownLatch is not reusable, you must create a new instance each time, but is avanceable. CylicBarrier can be re used but all threads must wait for each party to arrive at the barrier.
Phaser
- Dynamic number of parties
- Reusable
- Advanceable
When a thread wants to be known to the Phaser they invoke phaser.register()
when the thread arrives at the barrier they invoke phaser.arrive()
and here is where it is advanceable. If the thread wants to await for all registered tasks to complete phaser.arriveAndAwaitAdvance()
There is also the concept of a phase in which threads can wait on a completion of a other operations that may have not completed. Once all threads arrive at the phaser's barrier a new phase is created (an increment of one).
You can take a look at my other answers, maybe it will help:
Java ExecutorService: awaitTermination of all recursively created tasks
Flexible CountDownLatch?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…