Java Concurrency — CountDownLatch

Pragnyananda Mishra
2 min readJul 10, 2020

Let’s understand CountDownLatch with a practical implementation.

Joey, the foodie guy has ordered ‘pizza’, ‘pancakes’ and ‘burger’ in an online app for chick and duck’s birthday party to surprise chandler. He is so impatient to get the package soon. He keeps on checking the delivery status to get the update time to time.

The food delivery guy has implemented CountDownLatch in his online app. App can able to publish the current status of the delivery. Here it goes how courier guy has implemented the same.

CountDownLatch is used to make sure that a task waits for other dependent threads before it starts to execute.

Here in our example, the task is to prepare the foods first (dependent task) and deliver the food package(main task)to the Joey. So we can take items ordered as

String[] itemsOrdered ={"Pizza","PanCakes","Burger"};

We can declare “count” as number of items ordered that is 3. like

new CountDownLatch(itemsOrdered.length);

We have to create 3 thread as part of dependent task and start the threads by thread.start(). So once thread 1 completes its task, it waits for other threads to complete the task. it uses await() to wait for other threads.

countDownLatch.await()

Meanwhile it reduces “count” by countDown() method. After each thread completes task it reduces the count by 1. It continues this process till we reach count 0.

countDownLatch.countDown();

After we reach count 0, all the dependent task has been completed and we can run the main task on main thread. Now Joey can see that all the items has been prepared as part of separate thread. Status has been changed to “Dispatch” which will be executed by main thread. Please refer the diagram to have a better idea of the process.

CountDownLatch workflow
CountDownLatch Workflow

Please refer the complete code here.

https://github.com/pragnyananda/Java-Programs/tree/master/JavaConcurrency/src/com/example/concurrency/countdownlatch 

Kudos ! Happy learning..

--

--