What Is Countdownlatch Inwards Coffee - Concurrency Illustration Tutorial
What is CountDownLatch inwards Java
CountDownLatch inwards Java is a sort of synchronizer which allows 1 Thread to hold off for 1 or to a greater extent than Threads earlier starts processing. This is real crucial requirement as well as often needed inwards server side total Java application as well as having this functionality built-in equally CountDownLatch greatly simplifies the development. CountDownLatch inwards Java is introduced on Java v along amongst other concurrent utilities similar CyclicBarrier, Semaphore, ConcurrentHashMap as well as BlockingQueue inwards java.util.concurrent package. In this Java concurrency tutorial nosotros will what is CountDownLatch in Java, How CountDownLatch industrial plant inwards Java, an instance of CountDownLatch inwards Java as well as lastly around worth noting points virtually this concurrent utility. You tin too implement same functionality using wait as well as notify mechanism inwards Java but it requires lot of code as well as getting it write inwards start test is tricky, With CountDownLatch it tin be done inwards simply few lines. CountDownLatch too allows flexibility on give away of thread for which main thread should wait, It tin hold off for 1 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 occupation CountDownLatch inwards Java application which is non hard if you lot sympathise What is CountDownLatch inwards Java, What does CountDownLatch do as well as How CountDownLatch industrial plant inwards Java.
How CountDownLatch industrial plant inwards Java
CountDownLatch Exmaple inwards Java
In this department nosotros volition run across a total featured existent globe instance of using CountDownLatch inwards Java. In next CountDownLatch example, Java plan requires three services namely CacheService, AlertService and ValidationService to live started as well as laid upwardly earlier application tin handgrip whatever request as well as this is achieved yesteryear 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 occupation 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 occupation CountDownLatch inwards Java. CountDownLatch is
* useful if you lot desire to start principal processing thread in 1 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
// as well as laid upwardly to produce in that place job.
// Countdown latch is idle selection here, principal thread volition start amongst count 3
// Countdown latch is idle selection here, principal thread volition start amongst count 3
// as well as hold off until count reaches zero. each thread in 1 trial upwardly as well as read volition produce
// a count down. this volition ensure that principal thread is non started processing
// until all services is up.
//count is three since nosotros accept 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 live executed yesteryear 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( mention + " is Up");
latch.countDown(); //reduce count of CountDownLatch yesteryear 1
}
}
Output:
ValidationService is Up
AlertService is Up
CacheService is Up
All services are up, Application is starting now
//count is three since nosotros accept 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 live executed yesteryear 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( mention + " is Up");
latch.countDown(); //reduce count of CountDownLatch yesteryear 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 instance inwards Java, you lot tin run across that Application is non started until all services started yesteryear private Threads are completed.
When should nosotros occupation CountDownLatch inwards Java :
Use CountDownLatch when 1 of Thread similar main thread, require to hold off for 1 or to a greater extent than thread to complete, earlier its start doing processing. Classical instance of using CountDownLatch inwards Java is whatever server side total Java application which uses services architecture, where multiple services is provided yesteryear multiple threads as well as application tin non start processing until all services accept 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 1 trial count is reaches to zero, this is the principal difference betwixt CountDownLatch as well as CyclicBarrier, which is often asked inwards core Java interviews as well as multi-threading interviews.
2) Main Thread hold off on Latch yesteryear calling CountDownLatch.await() method spell other thread calls CountDownLatch.countDown() to inform that they accept completed.
That’s all on What is CountDownLatch in Java, What does CountDownLatch do inwards Java, How CountDownLatch industrial plant inwards Java along amongst a existent life CountDownLatch example inwards Java. This is a real useful concurrency utility as well as if you lot master copy when to occupation CountDownLatch and how to occupation CountDownLatch you lot volition live able to trim skilful amount of complex concurrency command code written using hold off as well as notify inwards Java.
Further Learning
Multithreading as well as Parallel Computing inwards Java
Java Concurrency inwards Practice - The Book
When to occupation ThreadLocal variable inwards Java
Komentar
Posting Komentar