CountDownLatch in Java

In this post we will talk about the CountDownLatch in Java. Count down latch in java is a away for a thread to wait for one or more operations to complete.

CountDownLatch in Java

When you create a CountDownLatch you will specify a count. The count can be decremented by calling the countDown method. Calling await() on the CountDownLatch will cause the thread to wait until the count reaches zero. Below I have provided an example showing how this works.

Simple Runnable object which will be used by our test.

The Runnable object above does the following:

  • Accepts a message to print
  • Accepts a CountDownLatch object which gets decremented (countDown()) after the Thread has completed its work

The above unit tests does the following:

  • Creates a CountDownLatch with count of 3
  • Invokes 3 tasks that will print a message and decrement the count of the CountDownLatch
  • Wait for the CountDownLatch to reach zero and print the final message.

Running the above code produces the following output:

I hope this post has helped you understand how the CountDownLatch works.

Similar posts:

  1. Java ExecutorService examples
  2. How to create a Thread in Java
  3. How to use Callable in Java
  4. Handle exception thrown by a callable

References:

  1. CountDownLatch API Documentation
  2. CountDownLatch tutorial

Leave a Reply