CountDownLatch in Multithreading
Table of Contents
- Introduction
- Understanding CountDownLatch in Multithreading
- Detailed Code Explanation
- Key Takeaways and Use Cases
- Conclusion
1. Introduction
In multithreading, managing multiple threads’ execution flow can be challenging, especially when certain threads must wait for others to complete before proceeding. One of the solutions to this problem is the CountDownLatch class in Java. It provides a synchronization aid that allows one or more threads to wait until a set of operations being performed by other threads completes. This article will explore the CountDownLatch mechanism, providing a detailed explanation of its use in multithreading, including an example program and a step-by-step code breakdown.
2. Understanding CountDownLatch in Multithreading
What is CountDownLatch?
CountDownLatch is a class in Java’s java.util.concurrent package that allows a thread to wait for a specific number of operations to complete before continuing. It operates by counting down from a set number of “latches.” When all latches have counted down to zero, the thread(s) waiting on the latch can proceed.
Key Features:
- Initial Count: The latch is initialized with a count. This count is decremented as other threads complete their tasks.
- Thread Synchronization: It ensures that a thread (or multiple threads) waits until the count reaches zero.
- One-Time Use: Once the count reaches zero, the latch cannot be reset.
3. Detailed Code Explanation
We will explore a program that demonstrates the use of CountDownLatch.
Program Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
package org.studyeasy; import java.util.concurrent.CountDownLatch; class SomeThread extends Thread{ private CountDownLatch latch; public SomeThread(CountDownLatch latch) { this.latch = latch; } @Override public void run() { System.out.println("Started thread: " + Thread.currentThread().getName()); System.out.println("Ended thread: " + Thread.currentThread().getName()); System.out.println("**************************"); latch.countDown(); // Decrements the count of the latch } } public class Main { public static void main(String[] args) throws InterruptedException { CountDownLatch latch = new CountDownLatch(4); // Initialize CountDownLatch with a count of 4 SomeThread thread1 = new SomeThread(latch); SomeThread thread2 = new SomeThread(latch); SomeThread thread3 = new SomeThread(latch); SomeThread thread4 = new SomeThread(latch); thread1.start(); thread2.start(); thread3.start(); thread4.start(); latch.await(); // Main thread waits until all other threads have counted down the latch System.out.println("All threads have finished their tasks."); } |
Code Breakdown:
- Class Definition:The SomeThread class extends Thread and accepts a CountDownLatch object in its constructor. The run() method, which is executed when the thread starts, prints when a thread starts and ends, then decrements the latch using latch.countDown().
- CountDownLatch Initialization:In the main() method, a CountDownLatch object is initialized with a count of 4. This count corresponds to the number of threads that need to complete their execution before the main thread can proceed.
- Thread Execution:Four SomeThread objects are created and started. Each thread runs, printing its start and end messages and decrementing the latch by calling countDown().
- Waiting for Threads:The latch.await() statement makes the main thread wait until all four threads have finished and the latch count reaches zero.
- Final Output:Once all threads have finished, the main thread resumes and prints, “All threads have finished their tasks.”
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
Started thread: Thread-0 Ended thread: Thread-0 ************************** Started thread: Thread-1 Ended thread: Thread-1 ************************** Started thread: Thread-2 Ended thread: Thread-2 ************************** Started thread: Thread-3 Ended thread: Thread-3 ************************** All threads have finished their tasks. |
Explanation:
Each thread starts and prints its start and end messages. The latch’s count is decremented each time a thread calls latch.countDown(). The main thread waits until the latch’s count reaches zero before proceeding, ensuring that all threads have completed their execution.
When and Where to Use:
- Multithreading: When you need multiple threads to wait for a task to complete.
- Task Coordination: Ensuring that a set of tasks is completed before proceeding.
4. Key Takeaways and Use Cases
- CountDownLatch is ideal for coordinating multiple threads.
- It ensures that a thread waits for other threads to complete their execution before moving forward.
- It cannot be reset once the count reaches zero, which makes it perfect for one-time events like system startups or task coordination.
Comparison with Other Synchronization Mechanisms:
Feature | CountDownLatch | CyclicBarrier |
---|---|---|
Reset capability | No | Yes |
Multiple threads | Can wait for tasks | Can wait and restart |
Use case | One-time events | Repeated synchronization |
5. Conclusion
In this article, we explored the CountDownLatch class, a valuable synchronization mechanism in Java multithreading. We examined its functionality, demonstrated its use through a practical example, and discussed when and where to apply it. Understanding CountDownLatch can help streamline multithreading tasks and ensure smooth coordination between multiple threads.