CountDownLatch is a synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes. While it can improve performance by allowing threads to proceed only when they are ready, improper use can lead to potential memory and performance issues.
When a CountDownLatch is created, it has a fixed count that signifies the number of operations that must complete before the latch is released. Each time one of those operations completes, the count is decremented. If a thread waits on a CountDownLatch, it will block until the count reaches zero. If used judiciously, it can prevent idle CPU usage and help manage concurrency effectively, but it may also lead to increased memory usage if too many threads are waiting or if used in a long-lived application without proper management.
Here is a simple example demonstrating how to use CountDownLatch in Java:
import java.util.concurrent.CountDownLatch;
public class Example {
public static void main(String[] args) {
int numberOfThreads = 3;
CountDownLatch latch = new CountDownLatch(numberOfThreads);
for (int i = 0; i < numberOfThreads; i++) {
new Thread(new Worker(latch)).start();
}
try {
latch.await(); // Wait until the count reaches zero
System.out.println("All workers have finished!");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class Worker implements Runnable {
private CountDownLatch latch;
public Worker(CountDownLatch latch) {
this.latch = latch;
}
@Override
public void run() {
try {
// Simulate work
Thread.sleep(1000);
System.out.println("Worker done!");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
latch.countDown(); // Decrement the count of the latch
}
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?