What is the difference between CountDownLatch and CyclicBarrier, and when would you use each?

CountDownLatch and CyclicBarrier are synchronization utilities from the java.util.concurrent package, but they serve different purposes. CountDownLatch allows one or more threads to wait until a specific number of operations are completed, whereas CyclicBarrier enables a group of threads to wait for each other at a common execution point before continuing. A CountDownLatch can be used only once, while a CyclicBarrier can be reused multiple times.

Key Points: • CountDownLatch is a one-time synchronization mechanism that cannot be reset after the count reaches zero. • CyclicBarrier allows multiple threads to meet at a barrier point and can be reused for subsequent synchronization cycles. • Use CountDownLatch when one thread depends on the completion of other tasks; use CyclicBarrier when multiple threads must progress through phases together.

Example: In an application startup process, the main thread may wait for database, cache, and messaging services to initialize using CountDownLatch. In contrast, a parallel data-processing application may use CyclicBarrier to ensure all worker threads complete one stage before moving to the next stage.

Code Example:

import java.util.concurrent.CountDownLatch;

public class Main {

    public static void main(String[] args)
            throws Exception {

        CountDownLatch latch =
                new CountDownLatch(3);

        for (int i = 1; i <= 3; i++) {

            new Thread(() -> {

                System.out.println(
                        "Task Completed");

                latch.countDown();

            }).start();
        }

        latch.await();

        System.out.println(
                "All Tasks Finished");
    }
}

Interview Tip: A concise interview answer is: CountDownLatch is used when one or more threads need to wait for a fixed number of tasks to complete and can be used only once. CyclicBarrier is used when multiple threads must wait for each other at a common point and can be reused across multiple synchronization cycles.