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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import java.util.concurrent.CountDownLatch; public class PrintMessageThread implements Runnable { private String message; private CountDownLatch countDownLatch; public PrintMessageThread(String message, CountDownLatch countDownLatch) { this.message = message; this.countDownLatch = countDownLatch; } @Override public void run() { try { System.out.println("message = " + message); Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } finally { countDownLatch.countDown(); } } } |
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
1 2 3 4 5 6 7 8 9 10 11 12 |
@Test public void countDownLatch() throws InterruptedException { CountDownLatch latch = new CountDownLatch(3); ExecutorService executorService = Executors.newSingleThreadExecutor(); executorService.submit(new PrintMessageThread("Task 1", latch)); executorService.submit(new PrintMessageThread("Task 2", latch)); executorService.submit(new PrintMessageThread("Task 3", latch)); latch.await(); System.out.println("All tasks have been executed"); } |
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:
1 2 3 4 |
message = Task 1 message = Task 2 message = Task 3 All tasks have been executed |
I hope this post has helped you understand how the CountDownLatch works.
Similar posts:
- Java ExecutorService examples
- How to create a Thread in Java
- How to use Callable in Java
- Handle exception thrown by a callable