Advanced concurrency
advconcurrency2CyclicBarrier
- Path
- pkg16advconcurrency/advconcurrency2CyclicBarrier.java
- Package
- pkg16advconcurrency
- Study order
- 2
- Run
- Single-file source launch
- Command
- java pkg16advconcurrency/advconcurrency2CyclicBarrier.java
There is no in-browser runner. This is the file from the curriculum, unchanged.
1package pkg16advconcurrency;2 3import java.util.concurrent.BrokenBarrierException;4import java.util.concurrent.CyclicBarrier;5import java.util.concurrent.ExecutorService;6import java.util.concurrent.Executors;7 8/*9 * advconcurrency2CyclicBarrier.java10 * ---------------------------------11 * CyclicBarrier: N threads wait at a barrier, then all proceed together (reusable).12 *13 * DEFINITION:14 * Unlike CountDownLatch, CyclicBarrier resets after all parties arrive. Optional15 * barrier action runs once when the barrier trips (e.g. merge partial results).16 *17 * KEY POINTS:18 * - await() blocks until all N parties reach the barrier.19 * - Reusable across multiple phases (simulations, parallel merge steps).20 * - BrokenBarrierException if a waiting thread is interrupted or times out.21 */22public class advconcurrency2CyclicBarrier {23 24 public static void main(String[] args) throws Exception {25 int parties = 3;26 CyclicBarrier barrier = new CyclicBarrier(parties, () ->27 System.out.println(" --- barrier action: all " + parties + " arrived ---"));28 29 try (ExecutorService pool = Executors.newFixedThreadPool(parties)) {30 for (int i = 0; i < parties; i++) {31 int id = i;32 pool.submit(() -> {33 for (int phase = 1; phase <= 2; phase++) {34 System.out.println(" thread " + id + " phase " + phase + " work");35 try {36 barrier.await();37 } catch (BrokenBarrierException | InterruptedException e) {38 Thread.currentThread().interrupt();39 return;40 }41 }42 });43 }44 pool.shutdown();45 while (!pool.isTerminated()) Thread.sleep(50);46 }47 System.out.println("Done — barrier cycled twice across " + parties + " threads");48 }49}