skip to content

How does a Phaser's phase number work, and how does termination change the behavior of its await methods?

level: principalimportance: nice to knowfreq 14%

answer

  1. Phase number: int from 0, ++ each completed round
  2. Methods return the phase you advanced into
  3. Wraps after Integer.MAX_VALUE (cyclic, not infinite)
  4. Terminated => negative phase, await returns immediately
  5. onAdvance true / forceTermination => terminate; default at parties==0

basics

~20 s

Each completed round increments the phase number (an int starting at 0). When the phaser terminates, await methods stop blocking and return a negative number at once, so no thread waits on a phaser that will never advance again.

solid answer

~50 s

A Phaser tracks a phase number: an int starting at 0 that increments by one each time all registered parties arrive and the phaser advances. Methods like arriveAndAwaitAdvance() and awaitAdvance(phase) return the new phase, so code can branch on the round. The phase number wraps around after Integer.MAX_VALUE back to zero - you should compare phases for equality/advance, not assume monotonic growth forever. A phaser becomes terminated when onAdvance(phase, parties) returns true (the default returns true once registered parties hit zero) or when forceTermination() is called. Once it terminates, isTerminated() returns true and all await/arrive methods return immediately with a negative phase number instead of blocking. A party that leaves with arriveAndDeregister() strands no one in the first place, because its deregistration counts as its arrival for the current phase; termination ends the phaser's life, and forceTermination() releases threads blocked at that moment. So designing onAdvance termination correctly is how you avoid both premature release and permanent blocking.

code

java · 14 lines
java
Phaser phaser = new Phaser(3) {
    @Override
    protected boolean onAdvance(int phase, int registeredParties) {
        // terminate after 5 phases, or when everyone has left
        return phase >= 4 || registeredParties == 0;
    }
};

// In a worker:
while (!phaser.isTerminated()) {
    doWork();
    int next = phaser.arriveAndAwaitAdvance(); // returns next phase, or negative if terminated
    if (next < 0) break;                        // terminated: stop cleanly
}

go deeper

for a junior

Knows the phase number counts rounds and that a phaser can be terminated.

for a middle

Uses the returned phase to branch per round and checks isTerminated() to exit loops.

for a senior

Explains onAdvance-driven termination, the default parties==0 rule, and that terminated await calls return a negative phase immediately.

for a principal

Designs onAdvance termination to avoid premature release and deadlock, accounts for phase wraparound and tiering, and knows that arriveAndDeregister(), not termination, keeps a leaving party from stranding the rest.

## What the phase number is A `Phaser` maintains an internal **phase number** — an `int` that starts at **0**. Each time *all currently registered parties* have arrived at the barrier, the phaser **advances**: the phase number increments by one and all waiting parties are released into the next round. So the phase number is essentially "how many rounds have completed." Many methods return it: - `arriveAndAwaitAdvance()` returns the **arriving phase's successor** — i.e. the phase you've advanced into. - `awaitAdvance(int phase)` blocks until the phaser leaves `phase`, then returns the next phase number. - `getPhase()` reads the current phase without participating. Returning the phase lets code make per-round decisions (e.g. "on phase 5, switch strategy"). ## Wraparound Because the phase number is a 32-bit `int`, after `Integer.MAX_VALUE` it **wraps around** back to 0. This is rarely hit in practice, but the design implication is: treat the phase number as a *cyclic* identifier (compare for the specific phase you're waiting on), not as an ever-increasing counter you can index forever. ## Negative phase numbers signal termination When a phaser is **terminated**, its phase number becomes **negative** (the high bit set). This is the runtime signal: any method that returns a phase will return a negative value once the phaser has terminated. Code can check `phaser.isTerminated()` or test for a negative return. ## How termination happens Two routes: 1. **`onAdvance(int phase, int registeredParties)` returns `true`.** This protected hook runs at every phase boundary, on the thread triggering the advance, before releasing others. If it returns `true`, the phaser terminates. The **default** implementation returns `true` exactly when `registeredParties == 0` — i.e. the phaser auto-terminates once the last party deregisters. Override it to terminate after a fixed number of phases, on a convergence condition, etc. 2. **`forceTermination()`** — an explicit, immediate termination, typically used to unblock everyone during shutdown or after an error. ## Why termination changes await behavior — two safety mechanisms This is the subtle, principal-level point, and it is easy to credit termination with work that deregistration does. In a **dynamic-membership** phaser, parties come and go via `register()`/`arriveAndDeregister()`. Consider a thread blocked in `arriveAndAwaitAdvance()` while every *other* party deregisters and leaves: 1. **Deregistration releases it, not termination.** `arriveAndDeregister()` counts as that party's arrival for the current phase and lowers the count for later ones, so when the last peer deregisters, the phase advances normally and the waiter returns the next phase number. The phaser is **not** terminated: the waiter is still registered, so the default `onAdvance` sees one party, not zero. 2. **Termination ends the phaser's life.** Once terminated, **all `await*`/`arrive*` methods return immediately** (with a negative phase) instead of blocking; a loop that checks that return value or `isTerminated()` then exits, while one that ignores both would spin on a phaser that will never advance. `forceTermination()` also releases threads blocked at that moment, which is how you unstick a phase that some party will never reach, for example after a worker crashed without deregistering. So termination is the end-of-life contract, and `arriveAndDeregister()` is what makes leaving early safe. ## Design guidance - **Own your `onAdvance`** when you need deterministic termination (e.g. `return phase >= maxPhases - 1 || registeredParties == 0;`). Returning `true` too early releases parties prematurely; never returning `true` (and never reaching zero parties) risks an unending phaser. - **Check the return / isTerminated()** after each await so loops exit cleanly rather than re-entering a terminated barrier. In the JDK implementation, the party whose arrival triggers the terminating advance still gets the positive next phase back, so test `isTerminated()` too. - **Use `forceTermination()`** in error/shutdown paths to guarantee no thread is left blocked. - Remember phase **wraparound** if you build very long-running phasers keyed on absolute phase counts. ## Relation to scalability None of this changes under **tiering** (parent/child phasers for high party counts): each tier still advances and reports phase numbers consistently; termination propagates so the whole tree releases. The contract — advance increments, termination releases — is uniform.

  • What value do Phaser's await methods return once the phaser is terminated, and why does it matter?
    They return a negative phase number at once instead of blocking. It matters because no thread waits on a phaser that will never advance again: every later call falls straight through, and forceTermination() also releases threads already waiting. Parties that deregister do not rely on it, because their deregistration already counts as an arrival.
  • When does the default onAdvance terminate the phaser?
    The default onAdvance returns true (terminating) exactly when the registered party count reaches zero - i.e. after the last party deregisters - so a phaser cleans itself up automatically once everyone has left.

A turnstile counter at a stadium that resets each event night: it ticks up per round, but when the venue closes (termination) the gates auto-open so no one is trapped waiting inside.

  • Assuming the phase number grows without bound - it wraps at Integer.MAX_VALUE
  • Thinking await methods keep blocking after termination - they return immediately with a negative phase
  • Believing onAdvance only runs once - it runs at every phase boundary
  • Ignoring termination design, risking either premature release or a permanently blocked phaser
  • Crediting termination with releasing a waiter when the other parties deregister - their deregistration counts as arrival and the phase simply advances

Phaser
Java 1.7

context