When should you prefer CountDownLatch and when should you avoid it?

CountDownLatch is a concurrency utility in Java that allows one or more threads to wait until a set of operations in other threads completes. It is a great tool for scenarios where you need to wait for a fixed number of events to occur before proceeding with further execution.

When to Prefer CountDownLatch

  • Multiple Threads Coordination: Use CountDownLatch when you need to wait for a number of threads to complete their tasks before moving on. For example, if you have a number of tasks that need to finish before starting the next phase of a computation.
  • Initial Setup: When you have a startup procedure that must wait for services to initialize.
  • Batch Processing: If you're processing a batch of tasks and want to wait until all processing is done before continuing.

When to Avoid CountDownLatch

  • Dynamic Conditions: Avoid using CountDownLatch if the number of tasks is not fixed or known beforehand. In such situations, a more flexible synchronization mechanism, like CyclicBarrier, may be suitable.
  • Multiple Resets: CountDownLatch cannot be reset once it has counted down to zero, so if you need to reuse the countdown mechanism, you should consider alternatives.
  • Long-Running Tasks: If the tasks being awaited can take a long time to complete or may hang, you might end up blocking your main thread unnecessarily.

Code Example


import java.util.concurrent.CountDownLatch;

public class CountDownLatchExample {
    public static void main(String[] args) {
        final int threadCount = 3;
        CountDownLatch latch = new CountDownLatch(threadCount);
        
        for (int i = 0; i < threadCount; i++) {
            new Thread(() -> {
                try {
                    // Simulate work
                    Thread.sleep(1000);
                    System.out.println("Task completed by " + Thread.currentThread().getName());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    latch.countDown(); // Reduce the count of latch
                }
            }).start();
        }
        
        try {
            latch.await(); // Wait for all tasks to complete
            System.out.println("All tasks completed. Main thread can proceed.");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
    

CountDownLatch Java concurrency thread synchronization await countdown mechanism