Phaser in brief
40 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)A batch job works in stages, and every worker must finish stage one before anyone starts stage two. Some workers may join or leave in the middle. Which tool handles a changing team?
Phases and registered parties
A Phaser is a reusable barrier that works in numbered phases. The number of registered parties can change, so threads can join or leave between phases.
A Phaser keeps two numbers: the phase, which starts at 0 and goes up by one each time a phase ends, and the registered parties, the threads the current phase waits for.
import java.util.concurrent.Phaser;
public class PhaserBasicsDemo { public static void main(String[] args) { Phaser phaser = new Phaser(1); // main is the only party System.out.println("Phase " + phaser.getPhase() + ", parties " + phaser.getRegisteredParties()); phaser.arriveAndAwaitAdvance(); // all 1 party arrived: phase ends System.out.println("Phase " + phaser.getPhase()); phaser.register(); // a second party joins System.out.println("Parties " + phaser.getRegisteredParties()); }}Phase 0, parties 1 Phase 1 Parties 2
new Phaser(n) starts with n parties; register() adds one and bulkRegister(k) adds k. A party says "I am done with this phase" by arriving. When the number of arrivals equals the number of registered parties, the phase advances: the phase number goes up, the arrival count goes back to 0, and waiting parties are released.
So far this is just a CyclicBarrier with a phase counter. The difference is that the party count is not fixed: it can grow and shrink between phases.
arriveAndAwaitAdvance()
arriveAndAwaitAdvance() means "I have arrived; now wait until everyone has". It is the Phaser version of CyclicBarrier.await(), and it is the call most phase-by-phase code uses. Unlike await(), it throws no checked exceptions.
Example 1 · Three evaluators, three phases
import java.util.concurrent.Phaser;
public class ExamPhasesDemo { static final String[] STEPS = {"check answers", "enter marks", "verify totals"};
static void pause(long ms) { try { Thread.sleep(ms); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }
public static void main(String[] args) throws InterruptedException { Phaser phaser = new Phaser(3) { @Override protected boolean onAdvance(int phase, int registeredParties) { System.out.println("Phase " + phase + " (" + STEPS[phase] + ") done by " + registeredParties + " evaluators"); return phase == STEPS.length - 1; // true = terminate after the last step } };
Thread[] evaluators = new Thread[3]; for (int i = 0; i < 3; i++) { long speed = 10L * (i + 1); evaluators[i] = new Thread(() -> { for (int step = 0; step < STEPS.length; step++) { pause(speed); // this step's work phaser.arriveAndAwaitAdvance(); // wait for the other evaluators } }, "evaluator-" + (i + 1)); evaluators[i].start(); }
for (Thread t : evaluators) { t.join(); } System.out.println("Terminated: " + phaser.isTerminated()); }}Phase 0 (check answers) done by 3 evaluators Phase 1 (enter marks) done by 3 evaluators Phase 2 (verify totals) done by 3 evaluators Terminated: true
What this code does
- Each evaluator works at its own speed and then calls
arriveAndAwaitAdvance(). Nobody starts "enter marks" until all three have finished "check answers". onAdvanceruns once at the end of each phase, in the last evaluator to arrive. It prints a summary and returnstrueafter phase 2, which terminates the Phaser.- Only
onAdvanceandmainprint, so the output is the same on every run. Note thatarriveAndAwaitAdvance()needs notry/catch.
To run code when a phase ends, extend Phaser and override onAdvance(int phase, int registeredParties). It runs once per phase, in the last thread to arrive, before anyone is released, just like a barrier action. It also decides whether the Phaser continues: return true to terminate it, false to go on. By default onAdvance returns true only when no parties are left. After termination isTerminated() is true and waiting threads are released at once.
Predict the output
Which phase is it?
Only one thread uses the Phaser, so the output never changes.
main is the only registered party.
Parties joining and leaving
register() adds a party to the current phase; the phase cannot end until that new party arrives too. arriveAndDeregister() arrives and leaves at the same time: it counts for this phase, and later phases no longer wait for it.
Example 2 · Fest volunteers join and leave between phases
import java.util.ArrayList;import java.util.List;import java.util.Map;import java.util.TreeMap;import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.Phaser;
public class VolunteerShiftsDemo { static Map<String, List<Integer>> log = new ConcurrentHashMap<>();
static Thread volunteer(String name, Phaser phaser, int lastPhase) { Thread t = new Thread(() -> { List<Integer> worked = new ArrayList<>(); while (true) { int phase = phaser.getPhase(); worked.add(phase); if (phase == lastPhase) { phaser.arriveAndDeregister(); break; } phaser.arriveAndAwaitAdvance(); } log.put(name, worked); }, name); t.start(); return t; }
public static void main(String[] args) throws InterruptedException { Phaser phaser = new Phaser(1) { @Override protected boolean onAdvance(int phase, int registeredParties) { System.out.println("Phase " + phase + " over, " + registeredParties + " parties continue"); return registeredParties == 0; } };
phaser.register(); Thread asha = volunteer("Asha", phaser, 2); // phases 0, 1, 2 phaser.register(); Thread bala = volunteer("Bala", phaser, 0); // phase 0 only
phaser.arriveAndAwaitAdvance(); phaser.register(); Thread chitra = volunteer("Chitra", phaser, 2); // joins in phase 1 phaser.arriveAndDeregister();
asha.join(); bala.join(); chitra.join(); for (Map.Entry<String, List<Integer>> e : new TreeMap<>(log).entrySet()) { System.out.println(e.getKey() + " worked in phases " + e.getValue()); } System.out.println("Terminated: " + phaser.isTerminated()); }}Phase 0 over, 2 parties continue Phase 1 over, 2 parties continue Phase 2 over, 0 parties continue Asha worked in phases [0, 1, 2] Bala worked in phases [0] Chitra worked in phases [1, 2] Terminated: true
What this code does
- Each volunteer works in the current phase and then calls
arriveAndAwaitAdvance(); in its last phase it callsarriveAndDeregister()instead and leaves for the day. - Phase 0 waits for main, Asha and Bala. Bala calls
arriveAndDeregister(), so after phase 0 only main and Asha remain: 2 parties. - Main registers Chitra during phase 1 and only then deregisters itself. Because main was still a party, phase 1 could not end before Chitra joined, so Chitra always starts in phase 1.
- In phase 2, Asha and Chitra both deregister.
onAdvancesees 0 parties and returnstrue, so the Phaser terminates. ACyclicBarriercannot change its party count like this.
A common trick is to register the main thread as a party: new Phaser(1). While main is registered, no phase can end without main's arrival, so main can safely start or add workers. When main is done controlling, it calls arriveAndDeregister() and steps out. The value of registeredParties passed to onAdvance is the count for the next phase, after any parties that left this phase are removed.
When Phaser is worth its complexity
A Phaser can do everything a latch and a barrier can, but its code is harder to read and easier to get wrong. Pick the simplest tool that fits the job.
Example 3 · A latch for tasks you discover while running
import java.util.ArrayList;import java.util.Collections;import java.util.List;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Phaser;
public class OrderPackingDemo { static List<String> log = Collections.synchronizedList(new ArrayList<>());
static void submit(ExecutorService pool, Phaser phaser, String job, boolean gift) { phaser.register(); pool.submit(() -> { try { log.add(job); if (gift) { // found more work: a subtask submit(pool, phaser, job.replace("pack", "wrap"), false); } } finally { phaser.arriveAndDeregister(); // this task is finished } }); }
public static void main(String[] args) { Phaser phaser = new Phaser(1); ExecutorService pool = Executors.newFixedThreadPool(3);
submit(pool, phaser, "pack ORD-1", false); submit(pool, phaser, "pack ORD-2", true); submit(pool, phaser, "pack ORD-3", false); submit(pool, phaser, "pack ORD-4", true);
phaser.arriveAndAwaitAdvance(); // wait for every task and subtask pool.shutdown();
List<String> jobs = new ArrayList<>(log); Collections.sort(jobs); jobs.forEach(System.out::println); System.out.println("All " + jobs.size() + " jobs done; phase is now " + phaser.getPhase()); }}pack ORD-1 pack ORD-2 pack ORD-3 pack ORD-4 wrap ORD-2 wrap ORD-4 All 6 jobs done; phase is now 1
What this code does
- Main starts 4 tasks but there are 6 jobs: the gift orders add a wrapping subtask while they run. A
CountDownLatchneeds the count up front, so it cannot handle this. - Each subtask is registered before its parent calls
arriveAndDeregister(), so the phase can never end while work is still being added. Main'sarriveAndAwaitAdvance()returns only when all 6 jobs are done. - The jobs run in any order on the pool; sorting the log makes the output fixed.
- Fixed number of tasks, one-time wait →
CountDownLatch. - Fixed group of threads, many rounds →
CyclicBarrier. - Threads join or leave between phases, or the number of tasks is found at run time →
Phaser. - Phases that should stop on a condition (target reached, no parties left) →
PhaserwithonAdvance.
Phaser is also handy as a latch when you do not know the number of tasks in advance: main registers itself, each task calls register() before it starts and arriveAndDeregister() when it ends, and main calls arriveAndAwaitAdvance() to wait for all of them. A task can even register new subtasks before it arrives.
new Phaser(parent)), which is rarely needed in normal apps.Next step
Check your understanding
10 quick questions