Java Reference
In-Depth Information
Besides defining a phase advance action, the
onAdvance()
method of the
Phaser
class also controls the termination
state of a
Phaser
. A
Phaser
is terminated if its
onAdvance()
method returns
true
. You can use the
isTerminated()
method of the
Phaser
class to check if a phaser is terminated or not. You can also terminate a phaser using its
forceTermination()
method.
Listing 6-38 demonstrates how to add a
Phaser
action. This is a trivial example. However, it demonstrates the concept
of adding and executing a
Phaser
action. It uses an anonymous class to create a custom
Phaser
class. The anonymous
class overrides the
onAdvance()
method to define a
Phaser
action. It simply prints a message in the
onAdvance()
method
as the
Phaser
action. It returns
false
, which means the phaser will not be terminated from the
onAdvance()
method.
Later, it registers the self as a party and triggers a phase advance using the
arriveAndDeregister()
method. On every
phase advance, the
Phaser
action that is defined by the
onAdvance()
method is executed.
Listing 6-38.
Adding a Phaser Action to a Phaser
// PhaserActionTest.java
package com.jdojo.threads;
import java.util.concurrent.Phaser;
public class PhaserActionTest {
public static void main(String[] args) {
// Create a Phaser object using an anonymous class and override its
// onAdvance() method to define a phaser action
Phaser phaser = new Phaser() {
protected boolean onAdvance(int phase, int parties) {
System.out.println("Inside onAdvance(): phase = " +
phase + ", Registered Parties = " + parties);
// Do not terminate the phaser by returning false
return false;
}
};
// Register the self (the "main" thread) as a party
phaser.register();
// Phaser is not terminated here
System.out.println("#1: isTerminated():" + phaser.isTerminated());
// Since we have only one party registered, this arrival will advance
// the phaser and registered parties reduces to zero
phaser.arriveAndDeregister();
// Trigger another phase advance
phaser.register();
phaser.arriveAndDeregister();
// Phaser is still not terminated
System.out.println("#2: isTerminated():" + phaser.isTerminated());