CountDownLatch
Semaphore
concurrency
Java
synchronization

CountDownLatch vs. Semaphore

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

CountDownLatch and Semaphore are two essential synchronizing constructs provided by the Java concurrency framework, designed to manage and coordinate threads in a multithreaded environment. Understanding the use, differences, and best practices of each can greatly enhance the efficiency of concurrent programming. Below, we delve into a detailed discussion of each synchronization aid and their comparative features.

CountDownLatch

Overview

CountDownLatch is a synchronization aid that allows one or more threads to wait for a set of operations to complete. It operates as a counter. Once the counter reaches zero, the waiting threads are released. This construct is particularly useful for scenarios where you want to ensure all prerequisite tasks are finished before proceeding.

Technical Explanation

A CountDownLatch is initialized with a count value. Each time an event or operation is completed, the count is decremented. Threads can wait using the await() method until the count reaches zero. The primary methods include:

  • CountDownLatch(int count) : Constructor to initialize the latch with a given count.
  • countDown() : Decrements the count by one.
  • await() : Blocks the current thread until the latch has counted down to zero.

Example

  • Divide and Conquer Algorithms: Ensuring sub-tasks finish before aggregating results.
  • Testing: Ensuring test threads wait for certain conditions or actions to complete.
  • Semaphore(int permits) : Initializes the semaphore with a specified number of permits.
  • acquire() : Acquires a permit, blocking if none are available.
  • release() : Releases a permit, returning it to the semaphore.
  • Rate Limiting: Controlling the number of concurrent connections.
  • Resource Pooling: Managing access to a fixed number of pooled resources.
  • Overhead: The overhead of using CountDownLatch is minimal when only a single countdown occurs. For Semaphore , contention can occur if too many threads attempt to acquire permits simultaneously.
  • Error Handling: Always handle potential InterruptedException and ensure proper resource release (especially in semaphores).
  • Resource Management: Be mindful of acquired permits and ensure they are always released to avoid deadlocks in semaphore usage.
  • Phaser: For dynamic and reusable barriers. Similar to CountDownLatch but more flexible.
  • CyclicBarrier: Another barrier form that can be reused after triggering, unlike CountDownLatch.

Course illustration
Course illustration

All Rights Reserved.