Phaser

A Phaser is a reusable barrier for work that happens in phases, where the number of participating threads can change while it runs. Parties register to join, wait for each other at the end of each phase, and deregister when they leave. This page explains how a Phaser keeps its state, then runs fixed phases, a job whose task count grows as it runs, controlled termination, the traps, and a tiered phaser for many threads.

Share

Contents

How a Phaser works

java.util.concurrent.Phaser (Java 7) generalizes CountDownLatch and CyclicBarrier. Like a barrier, it is used in rounds called phases, numbered 0, 1, 2 and so on. Unlike a barrier, the number of parties is not fixed: a party can register() at any time and leave with arriveAndDeregister(). A phase ends when every registered party has arrived. Then onAdvance runs once, the phase number goes up by one, and waiting parties are released.

All of this state is packed into one 64-bit long and updated with compare-and-set: 16 bits count the parties that have not yet arrived, 16 bits count the registered parties, 31 bits hold the phase number, and the top bit marks termination. Two limits follow from that layout. A single phaser can hold at most 65,535 parties, and the phase number wraps around to 0 after Integer.MAX_VALUE. When the phaser terminates, the top bit makes every phase number it returns negative.

Arriving and waiting are separate. A party can arrive without waiting (arrive()), arrive and wait (arriveAndAwaitAdvance()), or arrive and leave (arriveAndDeregister()). A thread that is not a party at all can wait for a phase to end with awaitAdvance(phase), which is how a phaser replaces a latch whose count is not known in advance.

Phaser compared with the other barrier-style classes
FeatureCountDownLatchCyclicBarrierPhaser
SinceJava 5Java 5Java 7
Reusable for many roundsNoYesYes
Number of parties can changeNoNoYes, register and deregister
Arrive without waitingYes (countDown)NoYes (arrive)
Wait without being a partyYes (await)NoYes (awaitAdvance)
Code that runs between roundsNoBarrier actiononAdvance, which can also end the phaser
What a missing party causesWaiters hangBroken barrier, exceptionsWaiters hang (use timeouts)
Best forOne-off eventsFixed group, fixed roundsChanging groups, or an unknown number of tasks

The phaser programs were run on JDK 21. Work done inside each phase is collected and printed once per phase, because the order in which threads finish a step varies from run to run.

Fixed steps for a group of workers

Three workers each download, parse and save, and no worker may start a step until all have finished the previous one. main registers itself as a party first and deregisters only after starting the workers, a common idiom explained below the output.

Java
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentSkipListSet;
import java.util.concurrent.Phaser;

public class Phases {

    static final String[] STEPS = {"download", "parse", "save"};

    public static void main(String[] args) throws InterruptedException {
        Set<String> done = new ConcurrentSkipListSet<>();       // collected per phase

        // main registers itself first, so no phase can end before all workers are registered
        Phaser phaser = new Phaser(1) {
            @Override
            protected boolean onAdvance(int phase, int registeredParties) {
                if (phase < STEPS.length) {
                    System.out.println("phase " + phase + " (" + STEPS[phase] + ") complete: "
                            + new TreeSet<>(done) + ", parties " + registeredParties);
                    done.clear();
                }
                return registeredParties == 0;                  // end when everyone has left
            }
        };

        List<Thread> workers = new ArrayList<>();
        for (int w = 1; w <= 3; w++) {
            String id = "w" + w;
            phaser.register();                                  // one more party
            Thread t = new Thread(() -> {
                for (String step : STEPS) {
                    done.add(id);                               // "do" the step
                    phaser.arriveAndAwaitAdvance();             // wait for the others
                }
                phaser.arriveAndDeregister();                   // leave
            });
            workers.add(t);
            t.start();
        }
        System.out.println("registered parties before start: " + phaser.getRegisteredParties());
        phaser.arriveAndDeregister();                           // main only guarded the start
        for (Thread t : workers) {
            t.join();
        }
        System.out.println("terminated: " + phaser.isTerminated()
                + ", final phase number " + phaser.getPhase());
    }
}

Output:

Output
registered parties before start: 4
phase 0 (download) complete: [w1, w2, w3], parties 3
phase 1 (parse) complete: [w1, w2, w3], parties 3
phase 2 (save) complete: [w1, w2, w3], parties 3
terminated: true, final phase number -2147483644
  • Each phase completed with all three workers in the set, so no worker ran ahead. onAdvance runs once per phase in the last thread to arrive, before the others are released, which makes it safe to read and clear the shared set there.
  • Before the start there were 4 parties: the three workers and main. Without main's registration, the first worker could reach the end of phase 0 before the second one had registered, see 1 of 1 parties arrived, and advance on its own. main's extra party holds phase 0 open until all workers exist.
  • arriveAndDeregister() counts as an arrival, so when main called it, phase 0 had 3 parties left, which is what onAdvance reported.
  • After "save" the workers deregistered, the count reached 0, and onAdvance returned true, which terminated the phaser. The final phase number is negative because termination sets the top bit.

Waiting for an unknown number of tasks

A latch needs its count up front. A crawler does not know how many pages it will visit, because each page reveals new links. With a phaser, every task registers its children before submitting them and deregisters when it ends. Here each page links to three more, down to depth 4, so the total must be 1 + 3 + 9 + 27 + 81 = 121 pages, but no code ever states that number.

Java
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Phaser;
import java.util.concurrent.atomic.AtomicInteger;

public class DynamicWork {

    // A crawler-like job: each page links to more pages, so the task count is unknown up front
    static final AtomicInteger VISITED = new AtomicInteger();

    static void visit(int depth, Phaser phaser, ExecutorService pool) {
        try {
            VISITED.incrementAndGet();
            if (depth < 4) {
                for (int link = 0; link < 3; link++) {
                    phaser.register();                  // register BEFORE submitting the child
                    pool.submit(() -> visit(depth + 1, phaser, pool));
                }
            }
        } finally {
            phaser.arriveAndDeregister();               // this task is done
        }
    }

    public static void main(String[] args) {
        Phaser phaser = new Phaser(1);                  // the root task's registration
        try (ExecutorService pool = Executors.newFixedThreadPool(4)) {
            pool.submit(() -> visit(0, phaser, pool));
            int phase = phaser.awaitAdvance(0);         // main is not a party; it just watches
            System.out.println("all tasks done, phaser moved to phase " + phase
                    + " (terminated: " + phaser.isTerminated() + ")");
        }
        // 1 + 3 + 9 + 27 + 81 pages at depths 0 to 4
        System.out.println("pages visited: " + VISITED.get() + " (expected 121)");
        System.out.println("registered parties left: " + phaser.getRegisteredParties());
    }
}

Output:

Output
all tasks done, phaser moved to phase -2147483647 (terminated: true)
pages visited: 121 (expected 121)
registered parties left: 0
  • All 121 pages were visited, and main was released only after the last one. main is not a party; it calls awaitAdvance(0), which waits until phase 0 ends without counting as an arrival.
  • The order is the whole trick: a task registers a child before submitting it and deregisters itself in finally. If the child were registered inside the child task, the parent could deregister first, the count would hit zero, and the phaser would end with work still running.
  • When the last task deregistered, the default onAdvance returned true because no parties were left, so the phaser terminated. That is why awaitAdvance returned a negative number, MIN_VALUE + 1, and 0 parties remain.

Ending a phaser with onAdvance

By default a phaser terminates only when its last party deregisters. Overriding onAdvance lets it stop on a condition instead, here after 3 phases, so the workers can simply loop until isTerminated(). The program then pokes the terminated phaser to show what its methods return.

Java
import java.util.concurrent.Phaser;

public class Termination {

    public static void main(String[] args) throws InterruptedException {
        int iterations = 3;
        // onAdvance returns true to terminate: here after a fixed number of phases
        Phaser phaser = new Phaser(2) {
            @Override
            protected boolean onAdvance(int phase, int registeredParties) {
                System.out.println("onAdvance(phase=" + phase + ", parties=" + registeredParties
                        + ") -> " + (phase + 1 >= iterations));
                return phase + 1 >= iterations || registeredParties == 0;
            }
        };

        int[] rounds = new int[2];
        Thread a = new Thread(() -> work(phaser, rounds, 0));
        Thread b = new Thread(() -> work(phaser, rounds, 1));
        a.start();
        b.start();
        a.join();
        b.join();
        System.out.println("worker a ran " + rounds[0] + ", worker b ran " + rounds[1] + " rounds");

        System.out.println("isTerminated: " + phaser.isTerminated());
        System.out.println("getPhase():   " + phaser.getPhase() + " (negative once terminated)");
        System.out.println("getPhase() - Integer.MIN_VALUE = "
                + (phaser.getPhase() - Integer.MIN_VALUE) + ", the phase it would have entered");
        System.out.println("arrive() now returns " + phaser.arrive() + " and does nothing");
        System.out.println("register() now returns " + phaser.register());
    }

    static void work(Phaser phaser, int[] rounds, int me) {
        while (!phaser.isTerminated()) {
            rounds[me]++;
            phaser.arriveAndAwaitAdvance();
        }
    }
}

Output:

Output
onAdvance(phase=0, parties=2) -> false
onAdvance(phase=1, parties=2) -> false
onAdvance(phase=2, parties=2) -> true
worker a ran 3, worker b ran 3 rounds
isTerminated: true
getPhase():   -2147483645 (negative once terminated)
getPhase() - Integer.MIN_VALUE = 3, the phase it would have entered
arrive() now returns -2147483645 and does nothing
register() now returns -2147483645
  • onAdvance ran for phases 0, 1 and 2 and returned true on the third call, so each worker ran exactly 3 rounds. It receives the number of registered parties, which lets it also stop when the group becomes empty, as the default does.
  • Once terminated, getPhase() returns a negative number, -2,147,483,645. Subtracting Integer.MIN_VALUE gives 3, the phase it would have entered. Code that compares phase numbers must check for negative values first.
  • On a terminated phaser, arrive() and register() do nothing and return the same negative phase, and every awaitAdvance returns at once. Nothing throws, so check the return values or isTerminated().
  • onAdvance is also the place for per-phase work such as a convergence check, playing the role of a CyclicBarrier's barrier action.

Phaser traps

A phaser checks less than you might expect. The program shows an arrival from the wrong thread, a party that dies without arriving, how to release stuck threads, and the size limit.

Java
import java.util.concurrent.Phaser;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class PhaserTraps {

    public static void main(String[] args) throws InterruptedException {
        // Trap 1: nothing checks WHO arrives; an unregistered caller counts as a party
        Phaser pair = new Phaser(2);                    // meant for worker A and worker B
        pair.arrive();                                  // a helper that never registered
        pair.arrive();                                  // worker A arrives
        System.out.println("1. phase advanced to " + pair.getPhase()
                + " although worker B never arrived");
        Phaser empty = new Phaser();                    // no parties at all
        try {
            empty.arrive();
        } catch (IllegalStateException e) {
            System.out.println("1. arrive with 0 parties: IllegalStateException");
        }

        // Trap 2: a party that fails without deregistering blocks everyone else
        Phaser phaser = new Phaser(2);
        Thread failing = new Thread(() -> {
            throw new IllegalStateException("crashed before arriving");
        });
        failing.setUncaughtExceptionHandler((t, e) ->
                System.out.println("2. worker died: " + e.getMessage()));
        failing.start();
        failing.join();
        int phase = phaser.arrive();                    // main arrives; one party missing
        try {
            phaser.awaitAdvanceInterruptibly(phase, 300, TimeUnit.MILLISECONDS);
        } catch (TimeoutException e) {
            System.out.println("2. still in phase " + phaser.getPhase() + " after 300 ms, "
                    + phaser.getUnarrivedParties() + " party never arrived");
        }

        // Fix: deregister in finally, or force termination to release all waiters
        Thread waiter = new Thread(() -> {
            int p = phaser.awaitAdvance(phaser.getPhase());
            System.out.println("3. waiter released, awaitAdvance returned " + p);
        });
        waiter.start();
        Thread.sleep(100);
        phaser.forceTermination();
        waiter.join();
        System.out.println("3. after forceTermination: terminated " + phaser.isTerminated());

        // Trap 4: one Phaser holds at most 65,535 parties
        try {
            new Phaser().bulkRegister(65536);
        } catch (IllegalStateException e) {
            System.out.println("4. bulkRegister(65536): IllegalStateException");
        }
    }
}

Output:

Output
1. phase advanced to 1 although worker B never arrived
1. arrive with 0 parties: IllegalStateException
2. worker died: crashed before arriving
2. still in phase 0 after 300 ms, 1 party never arrived
3. waiter released, awaitAdvance returned -2147483648
3. after forceTermination: terminated true
4. bulkRegister(65536): IllegalStateException
  1. The phaser counts arrivals, not threads. A helper that never registered called arrive(), and together with worker A that was enough to end phase 0 while worker B had not arrived. The Javadoc calls this a usage error that may only be detected later, if ever. Only an arrival with zero registered parties throws IllegalStateException.
  2. A party that dies before arriving leaves the phase open forever. A timed awaitAdvanceInterruptibly gave up after 300 ms with 1 unarrived party. Put arriveAndDeregister() in a finally block, as the crawler did, so a failing party still leaves.
  3. forceTermination() releases every waiting thread at once; the waiter's awaitAdvance returned Integer.MIN_VALUE, the terminated form of phase 0. Use it to cancel a whole phased job.
  4. bulkRegister(65536) threw IllegalStateException, because the party count has 16 bits. For more parties, use tiering.

Tiered phasers for many parties

Every arrival updates the same long with compare-and-set, so many threads arriving at once on one phaser contend on it. A phaser can have a parent: a child phaser counts as a single party of its parent, and it arrives at the parent only when all of its own parties have arrived. The program runs 40 virtual threads for 2 rounds, split over 4 children of 10 parties each.

Java
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Phaser;
import java.util.concurrent.atomic.AtomicInteger;

public class Tiered {

    public static void main(String[] args) throws InterruptedException {
        AtomicInteger advances = new AtomicInteger();
        Phaser root = new Phaser() {
            @Override
            protected boolean onAdvance(int phase, int registeredParties) {
                advances.incrementAndGet();
                return phase >= 1;                       // two phases, then stop
            }
        };

        // 40 virtual threads, split over 4 child phasers of 10 parties each
        List<Thread> threads = new ArrayList<>();
        AtomicInteger work = new AtomicInteger();
        for (int c = 0; c < 4; c++) {
            Phaser child = new Phaser(root, 10);         // registers itself with root as 1 party
            for (int i = 0; i < 10; i++) {
                threads.add(Thread.ofVirtual().start(() -> {
                    for (int round = 0; round < 2; round++) {
                        work.incrementAndGet();
                        child.arriveAndAwaitAdvance();
                    }
                }));
            }
        }
        System.out.println("root parties (one per child): " + root.getRegisteredParties());
        for (Thread t : threads) {
            t.join();
        }
        System.out.println("work units done: " + work.get() + " (40 threads x 2 rounds)");
        System.out.println("root advanced " + advances.get() + " times, terminated "
                + root.isTerminated());
    }
}

Output:

Output
root parties (one per child): 4
work units done: 80 (40 threads x 2 rounds)
root advanced 2 times, terminated true
  • The root has 4 parties, one per child, not 40. new Phaser(root, 10) registered the child with the root automatically.
  • All 80 units of work were done, and the root advanced twice, once per round: a round ended only when every child's 10 threads had arrived. A thread waiting in child.arriveAndAwaitAdvance() is released only when the root advances, so the whole tree moves in lock step.
  • The root's onAdvance ended the tree after phase 1, and termination propagates to the children. Tiering also removes the 65,535 limit, since each phaser in the tree holds only part of the parties.

Choosing a phaser or something simpler

When to use a Phaser
SituationUse
Fixed group of threads, fixed roundsCyclicBarrier, which also reports broken rounds
Wait once for a known number of eventsCountDownLatch
Parties join or leave between roundsPhaser with register and arriveAndDeregister
Wait for tasks that spawn more tasksPhaser: register children before submitting them, or a ForkJoinPool
Stop after a number of rounds or a conditionOverride onAdvance
Thousands of partiesTiered phasers
Run tasks and collect their resultsExecutorService.invokeAll or CompletableFuture

Two habits prevent most phaser bugs. First, decide which thread owns each registration, and pair every register() with exactly one arriveAndDeregister() in a finally block. Second, wait with awaitAdvanceInterruptibly(phase, timeout, unit) in production code, so a lost party shows up as a TimeoutException in a log instead of a silent hang. For the threads themselves, see thread basics.