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.
Contents
How a Phaser works
java.util.concurrent.PhaserCountDownLatchCyclicBarrierregister()arriveAndDeregister()onAdvance
All of this state is packed into one 64-bit longInteger.MAX_VALUE
Arriving and waiting are separate. A party can arrive without waiting (arrive()arriveAndAwaitAdvance()arriveAndDeregister()awaitAdvance(phase)
| Feature | CountDownLatch | CyclicBarrier | Phaser |
|---|---|---|---|
| Since | Java 5 | Java 5 | Java 7 |
| Reusable for many rounds | No | Yes | Yes |
| Number of parties can change | No | No | Yes, register and deregister |
| Arrive without waiting | Yes (countDown | No | Yes (arrive |
| Wait without being a party | Yes (await | No | Yes (awaitAdvance |
| Code that runs between rounds | No | Barrier action | onAdvance |
| What a missing party causes | Waiters hang | Broken barrier, exceptions | Waiters hang (use timeouts) |
| Best for | One-off events | Fixed group, fixed rounds | Changing 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
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:
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.
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.onAdvance - Before the start there were 4 parties: the three workers and
. Withoutmain '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.main counts as an arrival, so whenarriveAndDeregister() called it, phase 0 had 3 parties left, which is whatmain reported.onAdvance- After "save" the workers deregistered, the count reached 0, and
returned true, which terminated the phaser. The final phase number is negative because termination sets the top bit.onAdvance
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.
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:
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
was released only after the last one.main is not a party; it callsmain , which waits until phase 0 ends without counting as an arrival.awaitAdvance(0) - The order is the whole trick: a task registers a child before submitting it and deregisters itself in
. 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.finally - When the last task deregistered, the default
returned true because no parties were left, so the phaser terminated. That is whyonAdvance returned a negative number, MIN_VALUE + 1, and 0 parties remain.awaitAdvance
Ending a phaser with onAdvance
By default a phaser terminates only when its last party deregisters. Overriding onAdvanceisTerminated()
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:
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
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.onAdvance- Once terminated,
returns a negative number, -2,147,483,645. SubtractinggetPhase() gives 3, the phase it would have entered. Code that compares phase numbers must check for negative values first.Integer.MIN_VALUE - On a terminated phaser,
andarrive() do nothing and return the same negative phase, and everyregister() returns at once. Nothing throws, so check the return values orawaitAdvance .isTerminated() is also the place for per-phase work such as a convergence check, playing the role of aonAdvance 's barrier action.CyclicBarrier
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.
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:
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
- The phaser counts arrivals, not threads. A helper that never registered called
, 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 throwsarrive() .IllegalStateException - A party that dies before arriving leaves the phase open forever. A timed
gave up after 300 ms with 1 unarrived party. PutawaitAdvanceInterruptibly in aarriveAndDeregister() block, as the crawler did, so a failing party still leaves.finally releases every waiting thread at once; the waiter'sforceTermination() returnedawaitAdvance , the terminated form of phase 0. Use it to cancel a whole phased job.Integer.MIN_VALUE threwbulkRegister(65536) , because the party count has 16 bits. For more parties, use tiering.IllegalStateException
Tiered phasers for many parties
Every arrival updates the same long
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:
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.
registered the child with the root automatically.new Phaser(root, 10) - 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
is released only when the root advances, so the whole tree moves in lock step.child.arriveAndAwaitAdvance() - The root's
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.onAdvance
Choosing a phaser or something simpler
| Situation | Use |
|---|---|
| Fixed group of threads, fixed rounds | |
| Wait once for a known number of events | |
| Parties join or leave between rounds | PhaserregisterarriveAndDeregister |
| Wait for tasks that spawn more tasks | Phaser |
| Stop after a number of rounds or a condition | Override onAdvance |
| Thousands of parties | Tiered phasers |
| Run tasks and collect their results |
Two habits prevent most phaser bugs. First, decide which thread owns each registration, and pair every register()arriveAndDeregister()finallyawaitAdvanceInterruptibly(phase, timeout, unit)TimeoutException