CountDownLatch Readiness Gate

Gate startup on several one-shot signals with CountDownLatch and await(timeout), so boot either proceeds when all dependencies report ready or aborts.

JavaResilience

Code

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

public class ServiceStartup {

    public static void main(String[] args) throws InterruptedException {
        List<String> dependencies = List.of("config-server", "database", "cache");
        // 每个依赖就绪后 countDown 一次,计数归零即全部就绪
        CountDownLatch ready = new CountDownLatch(dependencies.size());

        try (ExecutorService pool = Executors.newFixedThreadPool(dependencies.size())) {
            for (String service : dependencies) {
                pool.submit(() -> {
                    System.out.println(service + " warming up");
                    ready.countDown();
                });
            }

            // 主线程设上限等待,超时则放弃启动而不是无限阻塞
            if (ready.await(2, TimeUnit.SECONDS)) {
                System.out.println("all dependencies ready, serving traffic");
            } else {
                System.out.println("startup timed out, aborting");
            }
        }
    }
}

How the snippet works

CountDownLatch Readiness Gate keeps everything in the class ServiceStartup.

The one repetition in this snippet is the loop for (String service : dependencies). Resources are declared in a try-with-resources header, so they close on every exit path without a finally block.

Applying it

Running the file prints labeled results such as all dependencies ready, serving traffic, startup timed out, aborting — each operation’s effect is visible in the output.

Statements that matter

List<String> dependencies = List.of("config-server", "database", "cache");

Interactive Tools for This Topic

FAQ

What does CountDownLatch Readiness Gate print when run?
The script runs standalone; its 2 labeled outputs include `all dependencies ready, serving traffic`, `startup timed out, aborting`.