CountDownLatch Start And Finish Gates

Coordinate concurrent workers with two CountDownLatch gates: a one-count start gun to launch together and a worker-count latch to await finish.

JavaResilience

Code

snippet
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class DualGateRunner {

    public static void main(String[] args) throws InterruptedException {
        int workers = 3;
        CountDownLatch startGate = new CountDownLatch(1);
        CountDownLatch doneGate = new CountDownLatch(workers);

        ExecutorService pool = Executors.newFixedThreadPool(workers);
        for (int i = 1; i <= workers; i++) {
            int id = i;
            pool.submit(() -> {
                try {
                    startGate.await(); // all workers pause until the gun fires
                    System.out.println("worker-" + id + " ran");
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                } finally {
                    doneGate.countDown(); // always signal completion
                }
            });
        }

        System.out.println("pending before start: " + doneGate.getCount());
        startGate.countDown(); // release every waiting worker at once
        doneGate.await(3, TimeUnit.SECONDS);
        System.out.println("pending after await: " + doneGate.getCount());

        pool.shutdown();
        pool.awaitTermination(2, TimeUnit.SECONDS);
    }
}

Stepwise trace — CountDownLatch Start And Finish Gates

CountDownLatch Start And Finish Gates is built around the class DualGateRunner.

The loop for (int i = 1; i <= workers; i++) is the only repeated construct.

Watch out for

  • No project configuration or dependency installation is needed prior to running.

Using it

The run prints worker-, pending before start:, pending after await: — each prefix names the step that produced it.

Key statements

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

Interactive Tools for This Topic

FAQ

What does CountDownLatch Start And Finish Gates print when run?
Invoke the file as-is — the `worker-`, `pending before start:`, `pending after await:` prefixes identify which step printed each line.