Phaser OnAdvance Caps Multi-Phase Runs

Override Phaser.onAdvance to summarize each completed phase and return true once the final stage finishes, cleanly marking the phaser terminated.

JavaResilience

Code

snippet
import java.util.concurrent.Phaser;

public class CappedPhaserPipeline {

    public static void main(String[] args) throws InterruptedException {
        int maxPhases = 2;
        Phaser phaser = new Phaser(2) {
            @Override
            protected boolean onAdvance(int phase, int registeredParties) {
                System.out.println("onAdvance phase=" + phase + " parties=" + registeredParties);
                return phase + 1 >= maxPhases || registeredParties == 0;
            }
        };

        Thread worker = new Thread(() -> {
            for (int step = 0; step < maxPhases; step++) {
                int nextPhase = phaser.arriveAndAwaitAdvance();
                System.out.println("worker step=" + step + " next=" + nextPhase);
            }
        });
        worker.start();

        for (int step = 0; step < maxPhases; step++) {
            int nextPhase = phaser.arriveAndAwaitAdvance();
            System.out.println("main step=" + step + " next=" + nextPhase);
        }

        worker.join();
        // Negative phase indicates the Phaser terminated via onAdvance()
        System.out.println("terminated=" + phaser.isTerminated());
    }
}

Runtime walkthrough — Phaser OnAdvance Caps Multi-Phase Runs

Phaser OnAdvance Caps Multi-Phase Runs reduces to the class CappedPhaserPipeline and the function onAdvance.

The file repeats itself only inside for (int step = 0; step < maxPhases; step++).

What to watch for

  • Nothing arrives from a registry; the language ships every API used.

Using it

Signature: protected boolean onAdvance(int phase, int registeredParties)

The run emits 4 labeled sections — onAdvance phase=, worker step=, main step=, terminated= — one per step.

main is the driver: it invokes onAdvance before returning.

Key statements

return phase + 1 >= maxPhases || registeredParties == 0;
Thread worker = new Thread(() -> {
    for (int step = 0; step < maxPhases; step++) {
        int nextPhase = phaser.arriveAndAwaitAdvance();
        System.out.println("worker step=" + step + " next=" + nextPhase);
    }
});

Interactive Tools for This Topic

FAQ

What does Phaser OnAdvance Caps Multi-Phase Runs print when run?
No setup needed: run the file and look for labeled lines like `onAdvance phase=`, `worker step=`, `main step=` in the output.