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
- CountDownLatch cannot be reset and re-use, However Cyclicbarrier can be reused, hence used in complex scenarios.
- We can not reuse CountDownLatch once count is reaches to zero.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
import java.util.concurrent.CountDownLatch; public class CountDownLatchExample { public static void main(String[] args) { CountDownLatch countDownLatch = new CountDownLatch(4); MultiChatUser user1 = new MultiChatUser(“Jake”, countDownLatch); MultiChatUser user2 = new MultiChatUser(“Mike”, countDownLatch); MultiChatUser user3 = new MultiChatUser(“Don”, countDownLatch); MultiChatUser user4 = new MultiChatUser(“Kar”, countDownLatch); user1.start(); user2.start(); user3.start(); user4.start(); } } class MultiChatUser extends Thread { private String username; boolean join = false; boolean conferenceCallOpened = false; private CountDownLatch countDownLatch; public MultiChatUser(String username, CountDownLatch countDownLatch) { this.username = username; this.countDownLatch = countDownLatch; } @Override public void run() { joinedConference(); countDownLatch.countDown(); // Until the countDown is set to zero try { countDownLatch.await(); } catch (InterruptedException e) { e.printStackTrace(); } openConferenceCall(); } public void joinedConference() { join = true; System.out.println(username + ” has joined the conference call..”); } public void openConferenceCall() { conferenceCallOpened = true; System.out.println(“Conference call Opened”); // May be can write any function to open the conference call… } } |
Result:
1 2 3 4 5 6 7 8 9 10 |
Result: Jake has joined the conference call.. Kar has joined the conference call.. Don has joined the conference call.. Mike has joined the conference call.. Conference call Opened Conference call Opened Conference call Opened Conference call Opened |