Advanced concurrency

advconcurrency4Phaser

Path
pkg16advconcurrency/advconcurrency4Phaser.java
Package
pkg16advconcurrency
Study order
4
Run
Single-file source launch
Command
java pkg16advconcurrency/advconcurrency4Phaser.java

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg16advconcurrency/advconcurrency4Phaser.java
1package pkg16advconcurrency;2 3import java.util.concurrent.Phaser;4import java.util.concurrent.ExecutorService;5import java.util.concurrent.Executors;6import java.util.concurrent.TimeUnit;7 8/*9 * advconcurrency4Phaser.java10 * --------------------------11 * Phaser: flexible, reusable barrier with dynamic party count.12 *13 * DEFINITION:14 *   Phaser is like CyclicBarrier but parties can register/deregister dynamically15 *   and supports tiered phases (phase number increments each trip).16 *17 * KEY POINTS:18 *   - arriveAndAwaitAdvance() waits for current phase to complete.19 *   - register() / arriveAndDeregister() change party count at runtime.20 *   - Useful for fork/join style pipelines with varying parallelism.21 */22public class advconcurrency4Phaser {23 24    public static void main(String[] args) throws InterruptedException {25        Phaser phaser = new Phaser(1); // main is party 026 27        try (ExecutorService pool = Executors.newFixedThreadPool(3)) {28            for (int i = 0; i < 3; i++) {29                int id = i;30                phaser.register();31                pool.submit(() -> {32                    System.out.println("  worker " + id + " phase 0");33                    phaser.arriveAndAwaitAdvance();34                    System.out.println("  worker " + id + " phase 1");35                    phaser.arriveAndDeregister();36                });37            }38            phaser.arriveAndAwaitAdvance(); // wait phase 039            System.out.println("Main: phase 0 complete");40            phaser.arriveAndAwaitAdvance(); // wait phase 141            System.out.println("Main: phase 1 complete");42            pool.shutdown();43            pool.awaitTermination(3, TimeUnit.SECONDS);44        }45    }46}