Java concurrency
CountdownLatch
CyclicBarrier
multithreading
synchronization

Java concurrency Countdown latch vs Cyclic barrier

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Java concurrency is a vital concept in developing applications that can run multiple tasks simultaneously, thereby optimizing the utilization of system resources. Two important constructs in the Java concurrency package designed to manage multiple threads are CountDownLatch and CyclicBarrier. While they may seem similar, each serves unique use cases and possesses distinguishing characteristics. This article examines both, comparing their functionalities, usage, and technical differences.

CountDownLatch

CountDownLatch is a synchronization aid that allows threads to wait until a set of operations complete. Once the counter reaches zero, any waiting threads are released. This class is part of java.util.concurrent package and helps in scenarios that require a thread to wait until a particular condition is met, like when multiple threads need to complete their tasks before proceeding further.

Key Characteristics:

  • Non-resettable: Once the count reaches zero, it cannot be reused.
  • Use Case: Ideal for scenarios where you need one or more threads to wait for a set of operations to complete, e.g., waiting for several services to be initialized before processing a request.

Example:

java
1import java.util.concurrent.CountDownLatch;
2
3public class CountDownLatchExample {
4    private static final int THREAD_COUNT = 3;
5    private static final CountDownLatch latch = new CountDownLatch(THREAD_COUNT);
6
7    public static void main(String[] args) throws InterruptedException {
8        for (int i = 0; i < THREAD_COUNT; i++) {
9            new Thread(new Worker()).start();
10        }
11
12        latch.await(); // Wait until latch count is 0
13        System.out.println("All tasks completed. Continuing execution...");
14    }
15
16    static class Worker implements Runnable {
17        @Override
18        public void run() {
19            try {
20                System.out.println(Thread.currentThread().getName() + " is working on a task...");
21                Thread.sleep(1000); // Simulates task execution
22            } catch (InterruptedException e) {
23                Thread.currentThread().interrupt();
24            } finally {
25                latch.countDown(); // Reduce the count of latch
26                System.out.println(Thread.currentThread().getName() + " completed.");
27            }
28        }
29    }
30}

CyclicBarrier

CyclicBarrier is another synchronization aid that allows a set of threads to wait for each other to reach a common barrier point. It can be reused once it is broken, making it suitable for situations where multiple threads need to sync up at certain points during execution.

Key Characteristics:

  • Resettable: Can be reused by invoking reset() after the barrier is broken, which allows multiple cycles.
  • Use Case: Ideal for repeated execution (e.g., simulations) where threads act in phases and need to meet at barrier points between phases.

Example:

java
1import java.util.concurrent.BrokenBarrierException;
2import java.util.concurrent.CyclicBarrier;
3
4public class CyclicBarrierExample {
5    private static final int THREAD_COUNT = 3;
6    private static final CyclicBarrier barrier = new CyclicBarrier(THREAD_COUNT, 
7        () -> System.out.println("Barrier reached, let's proceed to next phase."));
8
9    public static void main(String[] args) {
10        for (int i = 0; i < THREAD_COUNT; i++) {
11            new Thread(new Worker()).start();
12        }
13    }
14
15    static class Worker implements Runnable {
16        @Override
17        public void run() {
18            try {
19                System.out.println(Thread.currentThread().getName() + " is executing phase...");
20                Thread.sleep(1000); // Simulates task for phase
21                barrier.await(); // Wait for other threads
22                System.out.println(Thread.currentThread().getName() + " is progressing to the next phase.");
23            } catch (InterruptedException | BrokenBarrierException e) {
24                Thread.currentThread().interrupt();
25            }
26        }
27    }
28}

Comparison Table

FeatureCountDownLatchCyclicBarrier
ResettableNoYes
SynchronizationCount down to zero, releasing all waiting threadsSynchronizes at a common barrier point for threads
Usage ScenarioOne-time event like application startup tasksRepeated synchronization like iterative algorithms
ImplementationLatch count cannot be increased after reaching zeroBarrier can be reset after being tripped
Thread ReleaseAllows any thread to wait on latchRequires all threads to reach the barrier to proceed

Conclusion

Choosing between CountDownLatch and CyclicBarrier in Java concurrency boils down to the specific requirements of your application. Utilize CountDownLatch when a one-time countdown is necessary, while CyclicBarrier is more appropriate for applications that require continuous synchronization at various phases.

By understanding and effectively implementing these constructs, developers can build robust concurrent applications, optimizing resource management and improving application performance.


Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.