CKTIS / Java
Phaser — synchronizing work stages
Phaser is a reusable synchronization barrier with a variable number of participants. It lets tasks wait for a stage to finish and deregister when their work ends.
Version: Java SE 21; repository runtime, production runtime not attested
Syntax
Phaser phaser = new Phaser();
phaser.register();
phaser.arriveAndAwaitAdvance();
phaser.arriveAndDeregister();Phaser coordinates successive work phases. Phaser.register() adds a participant that has not yet arrived. Registration changes counters but does not bind a participant to a particular thread.
Phaser.arriveAndAwaitAdvance() records arrival and waits for a phase change. Phaser.arriveAndDeregister() records arrival and removes the participant without waiting. By default, removing the last participant terminates the barrier.
In the example, new Phaser(1) accounts for the main thread; the additional registration precedes starting worker. Two phases separate the calculations. The happens-before relationship ensures result visibility after the second barrier.
A missing arrival can block the others. arriveAndAwaitAdvance() does not stop waiting because of interruption; for interruptible waiting, use awaitAdvanceInterruptibly(...) after arrive().
Examples
import java.util.concurrent.Phaser;
public class PhaserExample {
public static void main(String[] args) throws InterruptedException {
Phaser phaser = new Phaser(1);
int[] result = {0};
phaser.register();
Thread worker = new Thread(() -> {
result[0] = 21;
phaser.arriveAndAwaitAdvance();
result[0] *= 2;
phaser.arriveAndDeregister();
});
worker.start();
phaser.arriveAndAwaitAdvance();
phaser.arriveAndAwaitAdvance();
System.out.println("result=" + result[0]);
phaser.arriveAndDeregister();
worker.join();
System.out.println("terminated=" + phaser.isTerminated());
}
}Result
result=42 terminated=true
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.