A latch counts down as work completes and releases every waiter at zero. It is single-use - create a new one for the next round.
var latch = new CountDownLatch(3);
var done = Collections.synchronizedList(new ArrayList<String>());
for (int i = 1; i <= 3; i++) {
int id = i;
Thread.ofVirtual().start(() -> {
try { Thread.sleep(Duration.ofMillis(10L * id)); } catch (InterruptedException e) { }
done.add("worker" + id);
latch.countDown();
});
}
latch.await();
System.out.println("all workers finished, count = " + done.size());
System.out.println("latch count now = " + latch.getCount());
all workers finished, count = 3
latch count now = 0
Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.
Published 2026-07-30