What Is Countdownlatch Inwards Coffee - Concurrency Illustration Tutorial

What is CountDownLatch inwards Java
CountDownLatch inwards Java is a form of synchronizer which allows i Thread  to hold off for i or to a greater extent than Threads earlier starts processing. This is real crucial requirement in addition to often needed inwards server side marrow Java application in addition to 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 in addition to BlockingQueue inwards java.util.concurrent package. In this Java concurrency tutorial nosotros will  what is CountDownLatch in Java, How CountDownLatch plant inwards Java, an instance of CountDownLatch inwards Java in addition to lastly about worth noting points nearly this concurrent utility. You tin likewise implement same functionality using  wait in addition to notify mechanism inwards Java but it requires lot of code in addition to getting it write inwards start endeavour is tricky,  With CountDownLatch it tin  be done inwards merely few lines. CountDownLatch likewise allows flexibility on lay out of thread for which main thread should wait, It tin hold off for i thread or n lay out of thread, in that place is non much alter on code.  Key bespeak is that yous demand to figure out where to exercise CountDownLatch inwards Java application which is non hard if yous empathize What is CountDownLatch inwards Java, What does CountDownLatch do in addition to How CountDownLatch plant inwards Java.


How CountDownLatch plant inwards Java
to hold off for i or to a greater extent than Threads earlier starts processing What is CountDownLatch inwards Java - Concurrency Example Tutorialthread waits for n lay out of threads specified field creating CountDownLatch inwards Java. Any thread, normally primary thread of application,  which calls CountDownLatch.await() volition hold off until count reaches null or its interrupted past times about other Thread. All other thread are required to create count downward past times calling CountDownLatch.countDown() i time they are completed or fix 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 yous tin non exercise CountDownLatch whatsoever more, but don't worry Java concurrency API has about other concurrent utility called CyclicBarrier for such requirements.


CountDownLatch Exmaple inwards Java

In this department nosotros volition encounter a total featured existent earth instance of using CountDownLatch inwards Java. In next CountDownLatch example, Java programme requires three services namely CacheService, AlertService  and ValidationService  to live started in addition to fix earlier application tin grip whatsoever request in addition to 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 programme to demonstrate How to exercise CountDownLatch inwards Java. CountDownLatch is
 * useful if yous desire to start primary 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
       // in addition to fix to create in that place job.
       // Countdown latch is idle alternative here, primary thread volition start amongst count 3
       // in addition to hold off until count reaches zero. each thread i time upward in addition to read volition create
       // a count down. this volition ensure that primary thread is non started processing
       // until all services is up.
     
       //count is three since nosotros bring 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 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( get upward + " 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 instance inwards Java, yous tin encounter that Application is non started until all services started past times private Threads are completed.

When should nosotros exercise CountDownLatch inwards Java :

Use CountDownLatch when i of Thread similar main thread, require to hold off 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 marrow Java application which uses services architecture,  where multiple services is provided past times multiple threads in addition to application tin non start processing  until all services bring started successfully equally shown inwards our CountDownLatch example.


CountDownLatch inwards Java – Things to remember
Few points nearly Java CountDownLatch which is worth remembering:

1) You tin non reuse CountDownLatch i time count is reaches to zero, this is the primary difference betwixt CountDownLatch in addition to CyclicBarrier, which is ofttimes asked inwards core Java interviews in addition to multi-threading  interviews.

2) Main Thread hold off on Latch past times calling CountDownLatch.await() method field other thread calls CountDownLatch.countDown() to inform that they bring 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 in addition to if yous original when to exercise CountDownLatch and how to exercise CountDownLatch yous volition live able to cut back proficient total of complex concurrency command code written using hold off in addition to notify inwards Java.

Further Learning
Multithreading in addition to Parallel Computing inwards Java
Java Concurrency inwards Practice - The Book
When to exercise ThreadLocal variable inwards Java

Belum ada Komentar untuk "What Is Countdownlatch Inwards Coffee - Concurrency Illustration Tutorial"

Posting Komentar

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel