What Is Countdownlatch Inwards Coffee - Concurrency Representative Tutorial

Advertisement

Masukkan script iklan 970x90px

What Is Countdownlatch Inwards Coffee - Concurrency Representative Tutorial

Selasa, 09 Februari 2021

What is CountDownLatch inwards Java
CountDownLatch inwards Java is a variety of synchronizer which allows i Thread  to hold back for i or to a greater extent than Threads earlier starts processing. This is really crucial requirement together with often needed inwards server side nub Java application together with 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 together with 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 together with live on approximately worth noting points virtually this concurrent utility. You tin too implement same functionality using  wait together with notify mechanism inwards Java but it requires lot of code together with getting it write inwards root drive is tricky,  With CountDownLatch it tin  be done inwards only few lines. CountDownLatch too allows flexibility on publish of thread for which main thread should wait, It tin hold back for i thread or n publish of thread, in that place is non much alter on code.  Key bespeak is that you lot demand to figure out where to exercise CountDownLatch inwards Java application which is non hard if you lot empathise What is CountDownLatch inwards Java, What does CountDownLatch do together with How CountDownLatch industrial plant inwards Java.


How CountDownLatch industrial plant inwards Java
to hold back for i or to a greater extent than Threads earlier starts processing What is CountDownLatch inwards Java - Concurrency Example Tutorialthread waits for n publish of threads specified spell creating CountDownLatch inwards Java. Any thread, unremarkably master copy thread of application,  which calls CountDownLatch.await() volition hold back until count reaches null or its interrupted yesteryear approximately other Thread. All other thread are required to produce count downward yesteryear calling CountDownLatch.countDown() i time they are completed or laid upward to the job. equally before long equally count reaches zero, Thread awaiting starts running. One of the disadvantage of CountDownLatch is that its non reusable i time count reaches to zero you lot tin non exercise CountDownLatch whatsoever more, but don't worry Java concurrency API has approximately other concurrent utility called CyclicBarrier for such requirements.


CountDownLatch Exmaple inwards Java

In this department nosotros volition run into a total featured existent the world instance of using CountDownLatch inwards Java. In next CountDownLatch example, Java plan requires three services namely CacheService, AlertService  and ValidationService  to live started together with laid upward earlier application tin cause got whatsoever request together with 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 exercise CountDownLatch inwards Java. CountDownLatch is
 * useful if you lot desire to start master copy processing thread i time 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 whatsoever thread until all service is up
       // together with laid upward to produce in that place job.
       // Countdown latch is idle pick here, master copy thread volition start amongst count 3
       // together with hold back until count reaches zero. each thread i time upward 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 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 shape 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( lift + " 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 into that Application is non started until all services started yesteryear private Threads are completed.

When should nosotros exercise 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 instance of using CountDownLatch inwards Java  is whatsoever server side nub Java application which uses services architecture,  where multiple services is provided yesteryear multiple threads together with 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 i time count is reaches to zero, this is the master copy difference betwixt CountDownLatch together with CyclicBarrier, which is oft asked inwards core Java interviews together with multi-threading  interviews.

2) Main Thread hold back 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 really useful concurrency utility together with if you lot master copy when to exercise CountDownLatch and how to exercise CountDownLatch you lot volition live able to trim down skillful 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 exercise ThreadLocal variable inwards Java