CountdownLatch

CountDownLatch is another concurrency class, in which makes one thread wait for other until it reaches the threshold limit mentioned.
Reach for the threshold limit, is counted by calling countdown() method present in CountDownLatch class.
Every time countdown() method is called, the count is decremented by 1, finally when arrives at zero, the awaiting will stop.

Assume 4 users are started joining the conference, when each thread is started, it will call the countdown() method of the common CountDownLatch object
and wait in the countDownLatch.await(); method until all the threads are started.
Once all the 4 threads are started, then the awaiting will be released., and next subsequent code block will be executed.

Difference between CountDownLatch vs CyclicBarrier

  1. CountDownLatch cannot be reset and re-use, However Cyclicbarrier can be reused, hence used in complex scenarios.
  2. We can not reuse CountDownLatch once count is reaches to zero.

Example:

Result:

Leave a Reply

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