Java CountDownLatch with Example – Concurrency Tutorial

In this Java concurrency tutorial, we will learn About Java CountDownLatch with Example, How CountDownLatch works Java.

A synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes. It was introduced in Java 5 along with other concurrent utilities.

Java CountDownLatch is initialized with a given count. Java CountDownLatch works in latch principal. The await methods block until the current count reaches zero due to invocations of the countDown() method, after which all waiting threads are released and any subsequent invocations of await return immediately.

This is a one-shot phenomenon — the count cannot be reset. If you need a version that resets the count, consider using a CyclicBarrier.

Important Methods:

  • await() – Causes the current thread to wait until the latch has counted down to zero unless the thread is interrupted.
  • await(long timeout, TimeUnit unit) – Causes the current thread to wait until the latch has counted down to zero, unless the thread is interrupted, or the specified waiting time elapses.
  • countDown() – Decrements the count of the latch, releasing all waiting threads if the count reaches zero.
  • getCount() – Returns the current count.
  • Encapsulation gives control over the code.

Java Countdownlatch with Example:

File: CacheService.java

 

File: ValidationService.java

File: CountDownLatchApp.java

 

When should we use CountDownLatch in Java

Use CountDownLatch when one of Thread like main thread, requires waiting for one or more thread to complete before its start doing the processing.

A classical example of using CountDownLatch in Java is any server-side core Java application which uses services architecture, where multiple services are provided by multiple threads and application cannot start processing until all services have started successfully as shown in our CountDownLatch example.

Output : 

 

Leave a Reply

Your email address will not be published. Required fields are marked *

Show Buttons
Hide Buttons