Synchronizers: latches, barriers, semaphores question 49 of 180 senior
What is a Phaser and when does it beat a CyclicBarrier?
- It is the deprecated predecessor of
CyclicBarrier - Correct: A reusable barrier whose number of parties can change between phases, with parties registering and deregistering dynamically
- A barrier that never resets
- A scheduler for periodic tasks
CyclicBarrier fixes the party count at construction. Phaser lets threads register() and
arriveAndDeregister() as the computation proceeds, which fits work that spawns or retires
participants between rounds: a simulation where entities appear and die, or a pipeline whose stages
drain one by one.
It also numbers its phases, so arriveAndAwaitAdvance() returns the phase you just completed and
awaitAdvance(phase) lets a thread wait for a specific round without being a party to it. Overriding
onAdvance(phase, parties) gives you the barrier action plus the ability to terminate the phaser by
returning true.
The honest caveat: most code that reaches for a Phaser does not need one, and the API is easy to get
wrong. Say that. Fixed parties and a fixed number of rounds are a CyclicBarrier, and one-shot is a
latch.
Quiz yourself on Synchronizers: latches, barriers, semaphores Suggest a correction