Start a Project

CountDown Latch In java

Count Down Latch in Java.

Before going on the topic we recall a topic electronic logic circuit to which we all are familiar.
A Electronic logic circuit performs a action when circuit is in high or low state or we can say 0 or 1.

Countdown latch functionality is something same like logic circuit.

A Countdown Latch is a versatile synchronisation tool and can be used for a number of purposes.Countdown latch can block a thread until other thread have complete assign task.

A useful property of a CountDownLatch is that it doesn’t require that threads calling count Down wait for the count to reach zero before proceeding, it simply prevents any thread from proceeding past an await until all threads could pass.

Example/Sample usage:

1. We can simply use countdown in api calling either from network or database, where we need multiple hit pa rally and a single result at the end.

Work flow

Step 1.
Initialise the countdown latch with count/number you need.
Ex- We have to make a network call 5 times.
COutnDownLatch myLatch= New CountDown(5);

Step 2.
Now call await method so that it will until the count will be zero.
myLatch.await();

step 3.

Call countDown after completion each thread or task Every time countDown call it will reduce the count value by one.
myLatch.countDown();

step 4.
It is the finally step. When all thread or task call countDown then the value of count will be zero. Now the main thread which is waiting for sub threads to complete the work will execute their work.

 

 

 

Note: We can’t reset the count value after initialising CountDownLatch.

Conclusion :

We have discussed how to achieve  single result by  doing multiple threading or dividing task with the help CountDown Latch.

Thankyou for reading!!

 

Exit mobile version