Advanced concurrency

advconcurrency1CountDownLatch

Path
pkg16advconcurrency/advconcurrency1CountDownLatch.java
Package
pkg16advconcurrency
Study order
1
Run
Single-file source launch
Command
java pkg16advconcurrency/advconcurrency1CountDownLatch.java

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

pkg16advconcurrency/advconcurrency1CountDownLatch.java
1package pkg16advconcurrency;2 3import java.util.concurrent.CountDownLatch;4import java.util.concurrent.ExecutorService;5import java.util.concurrent.Executors;6import java.util.concurrent.TimeUnit;7 8/*9 * advconcurrency1CountDownLatch.java10 * ----------------------------------11 * CountDownLatch: one or more threads wait until a counter reaches zero.12 *13 * DEFINITION:14 *   A latch is a one-shot synchronizer. Threads call await() to block; other15 *   threads call countDown() to decrement. When count hits 0, all waiters proceed.16 *17 * KEY POINTS:18 *   - Cannot reset — use CyclicBarrier if you need reuse.19 *   - Use case: start N workers, wait for all to finish (or ready signal).20 *   - await(timeout) avoids indefinite blocking.21 */22public class advconcurrency1CountDownLatch {23 24    public static void main(String[] args) throws InterruptedException {25        int workers = 4;26        CountDownLatch startGate = new CountDownLatch(1);   // boss releases workers27        CountDownLatch doneGate  = new CountDownLatch(workers); // workers signal done28 29        try (ExecutorService pool = Executors.newFixedThreadPool(workers)) {30            for (int i = 0; i < workers; i++) {31                int id = i;32                pool.submit(() -> {33                    try {34                        startGate.await();                    // wait for boss35                        System.out.println("  worker " + id + " working...");36                        Thread.sleep(50 + id * 20);37                        doneGate.countDown();                   // signal completion38                    } catch (InterruptedException e) {39                        Thread.currentThread().interrupt();40                    }41                });42            }43            Thread.sleep(100);                                // workers are waiting44            System.out.println("Boss: releasing workers");45            startGate.countDown();46            doneGate.await(5, TimeUnit.SECONDS);              // wait for all workers47            System.out.println("Boss: all workers finished");48        }49    }50}