Java Concurrency Program · CD08
Coordinate Threads with CountDownLatch in Java
A latch is a counter that only goes down. Workers count it down when they finish; anyone calling await() waits until it reaches zero.
Problem Statement
An application must load the cache, connect to the database and read the config on three separate threads before it starts serving requests.
The main thread must not continue until all three workers are ready, whatever order they finish in.
Input/Output Examples
3 workers finish at different timesOutputmain starts after all 3Explanation: await() returns when the count reaches 0.after await() returnsOutputremaining count: 0Explanation: each worker counted down exactly once.await() on the same latch againOutputreturns at onceExplanation: a latch cannot be reset; use CyclicBarrier for that.Visual Explanation
- Createcount3new CountDownLatch(3) main calls await()
- config readycount2countDown()
- cache readycount1countDown()
- database readycount0countDown() gate opens
- Maincontinues
await() continues.The workers never wait on each other. Only the threads that call await() wait, which is the difference between a latch and a barrier.
Approaches
Both approaches block the main thread until the three workers are done. The first uses the classic latch; the second uses futures.
Approach 1: CountDownLatch (Recommended)
Idea: create a latch with a count of 3, have each worker call countDown() when ready, and call await() in main.
- Create
new CountDownLatch(workers.size()). - Start one thread per worker; each calls
countDown()at the end. - Call
ready.await()in the main thread. - Continue once it returns.
Time: O(max t) · Space: O(n). t is a worker's start-up time and n the number of workers.
Approach 2: CompletableFuture.allOf()
Idea: run each worker with runAsync() and wait on CompletableFuture.allOf(tasks).join().
- Map each worker to a
runAsync()future. - Collect the futures into an array.
- Call
allOf(tasks).join().
Time: O(max t) · Space: O(n).
Java Solutions
Each tab is a complete program that runs on Java 17 or later. Thread timing changes from run to run, so the programs print checks (true or false) instead of raw milliseconds; both tabs print the same output.
Approach 1: CountDownLatch (Recommended)
The textbook tool for "wait until N things have happened".
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
public class LatchReady {
// Each worker counts down once when it is ready; await() returns when the count reaches 0
public static void main(String[] args) throws InterruptedException {
List<String> workers = List.of("cache", "database", "config");
CountDownLatch ready = new CountDownLatch(workers.size());
Set<String> readyBeforeMain = ConcurrentHashMap.newKeySet();
for (String name : workers) {
new Thread(() -> {
sleep(100 + name.length() * 20L); // different start-up times
readyBeforeMain.add(name);
ready.countDown();
}).start();
}
ready.await(); // main blocks here
System.out.println("ready before main started: " + new TreeSet<>(readyBeforeMain));
System.out.println("main started after all " + workers.size() + " workers: " + (readyBeforeMain.size() == workers.size()));
System.out.println("remaining count: " + ready.getCount());
}
static void sleep(long ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
ready before main started: [cache, config, database] main started after all 3 workers: true remaining count: 0
Time complexity: O(max t) · Space complexity: O(n).
Approach 2: CompletableFuture.allOf()
Shorter when the workers are tasks rather than long-lived threads, and failures propagate automatically.
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
public class LatchAllOf {
// CompletableFuture.allOf() completes when every worker's future has completed
public static void main(String[] args) {
List<String> workers = List.of("cache", "database", "config");
Set<String> readyBeforeMain = ConcurrentHashMap.newKeySet();
CompletableFuture<?>[] tasks = workers.stream()
.map(name -> CompletableFuture.runAsync(() -> {
sleep(100 + name.length() * 20L);
readyBeforeMain.add(name);
}))
.toArray(CompletableFuture[]::new);
CompletableFuture.allOf(tasks).join(); // main blocks here
long remaining = java.util.Arrays.stream(tasks).filter(t -> !t.isDone()).count();
System.out.println("ready before main started: " + new TreeSet<>(readyBeforeMain));
System.out.println("main started after all " + workers.size() + " workers: " + (readyBeforeMain.size() == workers.size()));
System.out.println("remaining count: " + remaining);
}
static void sleep(long ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
ready before main started: [cache, config, database] main started after all 3 workers: true remaining count: 0
Time complexity: O(max t) · Space complexity: O(n).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| CountDownLatch | O(max t) | O(n) |
| CompletableFuture.allOf() | O(max t) | O(n) |
The main thread waits as long as the slowest worker. The latch itself stores one counter; the futures version keeps one future per worker.
Interview Tips and Recommended Approach
- Call
countDown()in afinallyblock in real code, or a failing worker leaves main waiting forever. - Use
await(timeout, unit)when waiting forever is not acceptable. - Compare with
join(). A latch also works with thread pools, where you do not own the threads. - Contrast with CyclicBarrier: a latch is one-shot and others wait; a barrier is reusable and the workers wait for each other.
Recommended Approach: CountDownLatch
Why: it is purpose-built for this job, works with any kind of thread and makes the "wait for N events" intent obvious.