Need to coordinate threads so one (or many) waits for others to finish work?
That’s what CountDownLatch does—simple, robust, and perfect for one-shot synchronization. ⚙️🧵
🔸 What it is (Definition)
▪️ CountDownLatch is a concurrency utility that starts with a count and lets threads await until the count reaches zero. Each completed task calls countDown(), and waiting threads resume when the latch hits 0. 🚦
🔸 How it works (Tiny example)
int workers = 3;
CountDownLatch latch = new CountDownLatch(workers);
for (int i = 0; i 〈 workers; i++) {
new Thread(() -〉 {
try { /* do work */ }
finally { latch.countDown(); } // ✅ always decrement
}).start();
}
latch.await(); // waits until 3 countDown() calls happened
// proceed when all workers are done
🔸 Common Use Cases
▪️ Start gate: Delay a set of threads until you say “go” (use a second latch or a barrier). 🏁
▪️ Finish gate: Main thread waits for N worker tasks to complete before continuing. ✅
▪️ Parallel init/bootstrap: Load configs/resources in parallel, then continue when all ready. 🚀
▪️ Testing: Wait for async callbacks/events to finish in unit/integration tests. 🧪
🔸 Gotchas & Tips
▪️ One-shot only: CountDownLatch cannot be reset; use CyclicBarrier or Phaser if you need reuse. 🔁
▪️ Always decrement in finally to avoid deadlocks on exceptions. 🛡️
▪️ Timeouts: Prefer await(timeout, unit) to avoid waiting forever. ⏳
▪️ When tasks produce results: Consider CompletableFuture.allOf(...) or an ExecutorService. 📦
▪️ For “N start simultaneously”: Pair with a second latch (start signal) or use CyclicBarrier. 🧩
🔸 TL;DR
▪️ CountDownLatch lets one or more threads wait until other threads complete N signals.
▪️ Perfect for a one-time rendezvous (finish gate).
▪️ Use finally { latch.countDown(); } and consider timeouts.
🔸 Takeaways
▪️ Use CountDownLatch for one-shot coordination; not reusable.
▪️ Prefer CyclicBarrier/Phaser for repeated phases; CompletableFuture for result aggregation.
▪️ Keep it safe with timeouts and finally blocks.
#Java #Concurrency #Multithreading #CountDownLatch #JavaTips #Threading #Performance #CleanCode #SoftwareEngineering