Java Reference
In-Depth Information
First, the program creates a
Phaser
object by specifying 1 as the initially registered party.
// Start with 1 registered party
Phaser phaser = new Phaser(1);
You register a task with the
Phaser
one at a time. If a task (or a party) is registered and started before other tasks
are registered, the first task will advance the phaser because there will be one registered party and it will arrive at the
phaser by itself. This is the reason that you need to start with one registered party in the beginning. It acts like the
controller party for other tasks.
You create three tasks in a loop. Inside the loop, you register a party (that represents a task) with the
Phaser
,
create a task, and start it. Once you are done with setting up the tasks, you call the
arriveAndDeregister()
method of
the
Phaser
. This takes care of one extra party that you had registered when created the
Phaser
. This method makes a
party arrive at the
Phaser
and deregister without waiting for other registered parties to arrive. After this method call is
over, it is up to the three tasks to arrive at the
Phaser
and advance. Once all three tasks arrive at the
Phaser
, they will
all advance at the same time, thus making them start at the same time. You may get a different output. However, the
last three messages in the output will always be about starting the three tasks.
If you do not want to use an additional party to act as a controller, you need to register all tasks in advance to
make this program work correctly. You can rewrite the code in the
main()
method of the
StartTogetherTaskTest
class as follows:
public static void main(String[] args) {
// Start with 0 registered party
Phaser phaser = new Phaser();
// Let's start three tasks
final int TASK_COUNT = 3;
// Initialize all tasksa in one go
phaser.bulkRegister(TASK_COUNT);
for(int i = 1; i <= TASK_COUNT; i++) {
// Now create the task and start it
String taskName = "Task #" + i;
StartTogetherTask task = new StartTogetherTask(taskName, phaser);
task.start();
}
}
This time, you create a
Phaser
with no registered party. You register all the parties using the
bulkRegister()
method in one go. Note that you do not register a party inside the loop anymore. The new code has the same effect as
the old one. It is just a different way to write the logic.
Like a
CyclicBarrier
, a
Phaser
lets you execute an action upon a phase advance using its
onAdvance()
method.
You will need to create your own
Phaser
class by inheriting it from the
Phaser
class and override the
onAdvance()
method to write your custom
Phaser
action. On each phase advance, the
onAdvance()
method of the phaser is
invoked. The
onAdvance()
method in the
Phaser
class is declared as follows. The first argument is the phase number
and the second is the number of registered parties.
protected boolean onAdvance(int phase, int registeredParties)