CyclicBarrier Arrival Index Across Rounds

Use the arrival index returned by CyclicBarrier.await to elect one thread per round without extra locks, then reuse the barrier across phases.

JavaResilience

Code

snippet
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class BarrierLeaderRound {

    public static void main(String[] args) throws InterruptedException {
        int parties = 3;
        CyclicBarrier barrier = new CyclicBarrier(parties);
        ExecutorService pool = Executors.newFixedThreadPool(parties);

        for (int i = 0; i < parties; i++) {
            int worker = i;
            pool.submit(() -> {
                try {
                    for (int round = 1; round <= 2; round++) {
                        // await() returns parties-1 down to 0; 0 is the final arrival
                        int arrivalIndex = barrier.await(2, TimeUnit.SECONDS);
                        if (arrivalIndex == 0) {
                            System.out.println("round " + round
                                    + " leader=worker-" + worker
                                    + " parties=" + barrier.getParties());
                        }
                    }
                } catch (InterruptedException | BrokenBarrierException | TimeoutException e) {
                    Thread.currentThread().interrupt();
                }
            });
        }

        pool.shutdown();
        pool.awaitTermination(3, TimeUnit.SECONDS);
        System.out.println("waiting at end: " + barrier.getNumberWaiting());
    }
}

Runtime walkthrough — CyclicBarrier Arrival Index Across Rounds

The working surface is the class BarrierLeaderRound — everything else is wiring.

Iteration happens inside for (int i = 0; i < parties; i++) — everything outside it runs once.

Caveats

  • Zero third-party footprint: standard runtime primitives back every behavior shown.

Putting it to use

The demo output is labeled (round, waiting at end:); each label names the call that printed it.

Core lines

ExecutorService pool = Executors.newFixedThreadPool(parties);
Thread.currentThread().interrupt();

Interactive Tools for This Topic

FAQ

What does CyclicBarrier Arrival Index Across Rounds print when run?
Run it as a complete program — the output lines carry labels such as `round`, `waiting at end:`.