Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Phaser: registering, awaiting phase advance, and deregistering

Use `Phaser` to synchronize tasks across repeated phases, admit a worker during an active phase, and terminate the barrier when the last party leaves.

Version: Java SE 21

Syntax

import java.util.concurrent.Phaser;

Phaser phaser = new Phaser(1); // Signature: Phaser(int parties)
int registrationPhase = phaser.register();
phaser.arriveAndAwaitAdvance();
int arrivalPhase = phaser.arriveAndDeregister();

In Java SE 21, java.util.concurrent.Phaser is a reusable barrier with a dynamic party count. Phaser(int) starts at phase 0 with no parent and the given number of registered parties that have not yet arrived. Phaser() starts with none. A negative count or a count above this implementation's limit of 65,535 throws IllegalArgumentException.

register() adds one party that still owes an arrival and returns the phase to which the registration applies. After termination it does nothing and returns a negative value. Trying to register beyond the supported party limit throws IllegalStateException.

arriveAndAwaitAdvance() records an arrival and waits for the phase to advance or the phaser to terminate, keeping the party registered. Interruption alone does not end this wait; for interruption or a timeout, separate arrive() from the appropriate awaitAdvanceInterruptibly(...) overload. arriveAndDeregister() records an arrival and removes the party from future phases without waiting for others. It returns the arrival phase, or a negative value if the phaser was already terminated.

The phaser tracks counts, not thread identities. Arrive once per party per phase: a missing arrival can stall others, and an invalid arrival need not throw immediately. The default onAdvance(int, int) terminates the phaser at the phase boundary when the last party deregisters. Check that state with isTerminated().

In phase 0, main uses the constructor's slot, registers three workers before starting them, and records its own arrival with arrive(). A fourth worker registers in that same phase before releasing the first three through a CompletableFuture. main cannot pass awaitAdvance(...) until all four workers have arrived. All five parties arrive and wait in phase 1, then all five arrive and deregister in phase 2.

Examples

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Phaser;

public class PhaserDemo {
    private static void runWorker(Phaser phaser) {
        phaser.arriveAndAwaitAdvance();  // Phase 0
        phaser.arriveAndAwaitAdvance();  // Phase 1
        phaser.arriveAndDeregister();    // Phase 2
    }

    public static void main(String[] args) throws InterruptedException {
        Phaser phaser = new Phaser(1);
        CompletableFuture<Void> lateWorkerRegistered = new CompletableFuture<>();
        Thread[] workers = new Thread[4];

        for (int i = 0; i < 3; i++) {
            phaser.register();
            workers[i] = new Thread(() -> {
                lateWorkerRegistered.join();
                runWorker(phaser);
            });
            workers[i].start();
        }

        int phaseZero = phaser.arrive();
        workers[3] = new Thread(() -> {
            phaser.register();
            lateWorkerRegistered.complete(null);
            runWorker(phaser);
        });
        workers[3].start();

        phaser.awaitAdvance(phaseZero);
        System.out.println("Phase 0 complete: " + phaser.getRegisteredParties() + " registered");
        phaser.arriveAndAwaitAdvance();
        System.out.println("Phase 1 complete");
        phaser.arriveAndDeregister();

        for (Thread worker : workers) {
            worker.join();
        }
        System.out.println("Phase 2 complete: terminated = " + phaser.isTerminated());
    }
}

Result

Phase 0 complete: 5 registered
Phase 1 complete
Phase 2 complete: terminated = true

Only `main` prints. There are still five registered parties after phase 0 because phase 1 cannot finish without `main` arriving. The last line is printed after `join()` has returned for all four workers.

Related lessons

  • Java · Lesson 35 · Advanced · Version: 2

Sources