Multithreading
CountDownLatch
Coordinate thread startup and synchronization using CountDownLatch.
Interview: Tests usage of CountDownLatch for starting multiple threads concurrently, and waiting for workers to complete.
A CountDownLatch is a synchronization utility used to make one or more threads wait until a set of operations being performed by other threads completes. The latch count cannot be reset once it reaches zero.
Core Idea
A latch blocks calls to await() until countDownLatch.countDown() is invoked N times, reducing the count to zero.
Why It Matters
Allows a main thread to wait for all dependent background services (e.g. caches, configs) to load before starting.
Interview Lens
Tests how to coordinate thread startup gates and comparing latch vs cyclic barrier.
API Mechanics
Key operations on a CountDownLatch:
- Instantiation:
new CountDownLatch(N)sets the latch count to N. countDown(): Decrements the count by 1. Threads calling this do not block.await(): Blocks the calling thread until the latch count reaches zero. Once zero, all waiting threads are released.
Code Walkthrough
This program simulates a system startup gate where the main service waits for 3 database workers to initialize.
import java.util.concurrent.CountDownLatch;public class StartupManager { public static void main(String[] args) throws InterruptedException { CountDownLatch latch = new CountDownLatch(3);
Runnable service = () -> { try { System.out.println(Thread.currentThread().getName() + " is starting..."); Thread.sleep(1000); // Simulate service load System.out.println(Thread.currentThread().getName() + " initialized."); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } finally { latch.countDown(); // Decrement count } };
new Thread(service, "CacheService").start(); new Thread(service, "DBService").start(); new Thread(service, "MessagingService").start();
System.out.println("Main server waiting for services to initialize..."); latch.await(); // Blocks until latch count reaches 0 System.out.println("All services initialized. Server started!"); } }
Interview-Relevant Information
Q: Can you reuse a CountDownLatch?
Answer: No. Once the count reaches zero, the latch is open, and all subsequent calls to await() return immediately. If you need to reset the count and reuse the barrier, use a CyclicBarrier instead.
Quick Checklist
How do you decrement the latch count? Can you reuse CountDownLatch? If yes, you understand CountDownLatch.
Use Cases
Coordinating multi-threaded test runners (main thread waits for workers to complete).
Setting up thread start gates to ensure all threads begin calculations at the exact same moment.
Common Mistakes
Forgetting to call countDown() in catch/finally blocks, leaving the count above 0 and deadlocking the awaiting threads.
Calling await() inside the worker threads rather than the coordinating thread, blocking the workers.