Monday 10 June 2019

Java Concurrency : CountDownLatch


Java Concurrency: CountDownLatch

Let's learn about next topic: CountDownLatch

I will be sharing the examples I am doing on daily basis to learn the Java Concurrency.
Here is the example of the topic CountDownLatch in Java

Theory:
Let us suppose you need to bring up your application. Now while bringing up the application you should have logging service, dbservice, network service and like that few more services should be up before the main thread starts. You can go for the CountDownLatch by mentioning number of service Program have to wait before it start the main logic.

Example:
We are creating a class service. Where we will be looking if all the service are up. For eg I want 3 services should be up before my main thread is up. If all the 3 services are up we can go ahead with different task else it will wait.

Service.java

import java.util.concurrent.CountDownLatch;

public class Service implements Runnable{
String name;
int time;
CountDownLatch latch;
Service(){

}
Service(String name, int time, CountDownLatch latch)
{
this.latch = latch;
this.name = name;
this.time = time;
}
@Override
public void run() {

System.out.println(name+"  is up");

try {
Thread.sleep(time);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
latch.countDown();

}

}

CountDownExample.java :

import java.util.concurrent.CountDownLatch;

public class CountDownExample {

public static void main(String[] args) {

CountDownLatch latch = new CountDownLatch(2);
Thread cacheService = new Thread(new Service("CacheService", 1000, latch));
Thread cacheService1 = new Thread(new Service("NetworkService", 1000, latch));
Thread cacheService2 = new Thread(new Service("LoggingService", 1000, latch));
cacheService.start();
cacheService1.start();
cacheService2.start();

try {
latch.await();

System.out.println("All the cache service are up. Now starting application");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("You can now go ahead with the main business");
}
}

Output:


NetworkService  is up
CacheService  is up
LoggingService  is up
All the services are up. Now starting application
You can now go ahead with the main business



Happy Learning 😊

2 comments:

  1. Can we have more examples with regards to Java Concurrency Topics?

    ReplyDelete
    Replies
    1. Sure I will be coming up with more topics soon

      Delete