Video in progress
In what situations are CountDownLatch, CyclicBarrier and Semaphore used?
CountDownLatch: one or more threads wait for N jobs to finish, one time only. CyclicBarrier: N threads wait for each other at a point, and it is reusable. Semaphore: limits how many threads can access a resource at the same time.
📖 Answer
CountDownLatch: "wait until everyone is ready":
CountDownLatch ready = new CountDownLatch(3);
for (String svc : List.of("db", "cache", "broker")) {
executor.submit(() -> { warmUp(svc); ready.countDown(); });
}
ready.await(30, TimeUnit.SECONDS);
Once the counter reaches zero, you can't reset it. It is used a lot in tests: to build the situation "let two threads start at exactly the same time".
CyclicBarrier: phased computation. Each worker finishes its part and calls await(), when the last one arrives the barrier action runs, and everyone moves on to the next phase. If one thread is interrupted, the others get a BrokenBarrierException. It is rare in backend code.
Semaphore: a number of permits:
private final Semaphore slots = new Semaphore(10);
Response callPartner(Request r) throws InterruptedException {
slots.acquire();
try {
return partnerClient.call(r);
} finally {
slots.release();
}
}
If a partner's API can't handle more than 10 parallel requests, this is exactly what you need. With virtual threads it matters even more: threads are unlimited, but the external resource is limited.
Sign up to mark studied questions and save your progress.