How does CountDownLatch impact performance or memory usage?

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 } } }

CountDownLatch performance memory usage synchronization threads concurrency