What Is Countdownlatch Inwards Coffee - Concurrency Example Tutorial
What is CountDownLatch inwards Java
CountDownLatch inwards Java is a sort of synchronizer which allows i Thread to hold back for i or to a greater extent than Threads earlier starts processing. This is real crucial requirement together with often needed inwards server side center Java application together with having this functionality built-in equally CountDownLatch greatly simplifies the development. CountDownLatch inwards Java is introduced on Java five along amongst other concurrent utilities similar CyclicBarrier, Semaphore, ConcurrentHashMap together with BlockingQueue inwards java.util.concurrent package. In this Java concurrency tutorial nosotros will what is CountDownLatch in Java, How CountDownLatch plant inwards Java, an event of CountDownLatch inwards Java together with in conclusion to a greater extent than or less worth noting points virtually this concurrent utility. You tin likewise implement same functionality using wait together with notify mechanism inwards Java but it requires lot of code together with getting it write inwards start endeavour is tricky, With CountDownLatch it tin be done inwards only few lines. CountDownLatch likewise allows flexibility on give away of thread for which main thread should wait, It tin hold back for i thread or n give away of thread, in that place is non much alter on code. Key betoken is that you lot demand to figure out where to utilization CountDownLatch inwards Java application which is non hard if you lot sympathize What is CountDownLatch inwards Java, What does CountDownLatch do together with How CountDownLatch plant inwards Java.
How CountDownLatch plant inwards Java
thread waits for n give away of threads specified land creating CountDownLatch inwards Java. Any thread, commonly master copy thread of application, which calls CountDownLatch.await() volition hold back until count reaches null or its interrupted past times to a greater extent than or less other Thread. All other thread are required to produce count downwards past times calling CountDownLatch.countDown() in i trial they are completed or laid upwardly to the job. equally presently equally count reaches zero, Thread awaiting starts running. One of the disadvantage of CountDownLatch is that its non reusable in i trial count reaches to zero you lot tin non utilization CountDownLatch whatever more, but don't worry Java concurrency API has to a greater extent than or less other concurrent utility called CyclicBarrier for such requirements.
CountDownLatch Exmaple inwards Java
In this department nosotros volition come across a total featured existent basis event of using CountDownLatch inwards Java. In next CountDownLatch example, Java plan requires three services namely CacheService, AlertService and ValidationService to survive started together with laid upwardly earlier application tin create got whatever request together with this is achieved past times using CountDownLatch inwards Java.
import java.util.Date;
import java.util.concurrent.CountDownLatch;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Java plan to demonstrate How to utilization CountDownLatch inwards Java. CountDownLatch is
import java.util.concurrent.CountDownLatch;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Java plan to demonstrate How to utilization CountDownLatch inwards Java. CountDownLatch is
* useful if you lot desire to start master copy processing thread in i trial its dependency is completed
* equally illustrated inwards this CountDownLatch Example
*
* @author Javin Paul
*/
public class CountDownLatchDemo {
public static void main(String args[]) {
final CountDownLatch latch = new CountDownLatch(3);
Thread cacheService = new Thread(new Service("CacheService", 1000, latch));
Thread alertService = new Thread(new Service("AlertService", 1000, latch));
Thread validationService = new Thread(new Service("ValidationService", 1000, latch));
cacheService.start(); //separate thread volition initialize CacheService
alertService.start(); //another thread for AlertService initialization
validationService.start();
// application should non start processing whatever thread until all service is up
*
* @author Javin Paul
*/
public class CountDownLatchDemo {
public static void main(String args[]) {
final CountDownLatch latch = new CountDownLatch(3);
Thread cacheService = new Thread(new Service("CacheService", 1000, latch));
Thread alertService = new Thread(new Service("AlertService", 1000, latch));
Thread validationService = new Thread(new Service("ValidationService", 1000, latch));
cacheService.start(); //separate thread volition initialize CacheService
alertService.start(); //another thread for AlertService initialization
validationService.start();
// application should non start processing whatever thread until all service is up
// together with laid upwardly to produce in that place job.
// Countdown latch is idle pick here, master copy thread volition start amongst count 3
// Countdown latch is idle pick here, master copy thread volition start amongst count 3
// together with hold back until count reaches zero. each thread in i trial upwardly together with read volition produce
// a count down. this volition ensure that master copy thread is non started processing
// until all services is up.
//count is three since nosotros convey three Threads (Services)
try{
latch.await(); //main thread is waiting on CountDownLatch to finish
System.out.println("All services are up, Application is starting now");
}catch(InterruptedException ie){
ie.printStackTrace();
}
}
}
/**
* Service degree which volition survive executed past times Thread using CountDownLatch synchronizer.
*/
class Service implements Runnable{
private final String name;
private final int timeToStart;
private final CountDownLatch latch;
public Service(String name, int timeToStart, CountDownLatch latch){
this.name = name;
this.timeToStart = timeToStart;
this.latch = latch;
}
@Override
public void run() {
try {
Thread.sleep(timeToStart);
} catch (InterruptedException ex) {
Logger.getLogger(Service.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println( cite + " is Up");
latch.countDown(); //reduce count of CountDownLatch past times 1
}
}
Output:
ValidationService is Up
AlertService is Up
CacheService is Up
All services are up, Application is starting now
//count is three since nosotros convey three Threads (Services)
try{
latch.await(); //main thread is waiting on CountDownLatch to finish
System.out.println("All services are up, Application is starting now");
}catch(InterruptedException ie){
ie.printStackTrace();
}
}
}
/**
* Service degree which volition survive executed past times Thread using CountDownLatch synchronizer.
*/
class Service implements Runnable{
private final String name;
private final int timeToStart;
private final CountDownLatch latch;
public Service(String name, int timeToStart, CountDownLatch latch){
this.name = name;
this.timeToStart = timeToStart;
this.latch = latch;
}
@Override
public void run() {
try {
Thread.sleep(timeToStart);
} catch (InterruptedException ex) {
Logger.getLogger(Service.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println( cite + " is Up");
latch.countDown(); //reduce count of CountDownLatch past times 1
}
}
Output:
ValidationService is Up
AlertService is Up
CacheService is Up
All services are up, Application is starting now
By looking at output of this CountDownLatch event inwards Java, you lot tin come across that Application is non started until all services started past times private Threads are completed.
When should nosotros utilization CountDownLatch inwards Java :
Use CountDownLatch when i of Thread similar main thread, require to hold back for i or to a greater extent than thread to complete, earlier its start doing processing. Classical event of using CountDownLatch inwards Java is whatever server side center Java application which uses services architecture, where multiple services is provided past times multiple threads together with application tin non start processing until all services convey started successfully equally shown inwards our CountDownLatch example.
CountDownLatch inwards Java – Things to remember
Few points virtually Java CountDownLatch which is worth remembering:
1) You tin non reuse CountDownLatch in i trial count is reaches to zero, this is the master copy difference betwixt CountDownLatch together with CyclicBarrier, which is ofttimes asked inwards core Java interviews together with multi-threading interviews.
2) Main Thread hold back on Latch past times calling CountDownLatch.await() method land other thread calls CountDownLatch.countDown() to inform that they convey completed.
That’s all on What is CountDownLatch in Java, What does CountDownLatch do inwards Java, How CountDownLatch plant inwards Java along amongst a existent life CountDownLatch example inwards Java. This is a real useful concurrency utility together with if you lot master copy when to utilization CountDownLatch and how to utilization CountDownLatch you lot volition survive able to trim expert total of complex concurrency command code written using hold back together with notify inwards Java.
Further Learning
Multithreading together with Parallel Computing inwards Java
Java Concurrency inwards Practice - The Book
When to utilization ThreadLocal variable inwards Java
0 Response to "What Is Countdownlatch Inwards Coffee - Concurrency Example Tutorial"
Post a Comment