Phaser
Comprehensive guide with executable examples to using Phaser, an advanced and sophisticated synchronization barrier construct.
If you are interviewing, consider buying our number#1 course for Java Multithreading Interviews.
Overview
The Phaser
class is an extension of the functionality offered by CyclicBarrier
and CountDownLatch
classes and is more flexible in use. One stark difference is that the Phaser
class allows the number of registered parties that synchronize on a phaser to vary over time. The Phaser
can be repeatedly awaited similar to a CyclicBarrier
.
Example
Apart from specifying the number of threads/tasks to synchronize in the constructor, threads/tasks can also register with an instance of Phaser
using the register()
or the bulkRegister(int)
methods. Note, that if a thread register()
-s with an instance of Phaser
there’s no way for the thread to query the instance to determine if it registered with the instance, i.e. there’s no internal book-keeping maintained by the Phaser
instance. However, if such behavior is desired the Phaser
class can be subclassed and the book-keeping functionality added.
The program below exercises some of the APIs exposed by Phaser
to register threads with the barrier. Run the program and study the comments before we discuss them.
Create a free account to view this lesson.
By signing up, you agree to Educative's Terms of Service and Privacy Policy