What Is Countdownlatch Inwards Coffee - Concurrency Representative Tutorial

What is CountDownLatch inwards Java
CountDownLatch inwards Java is a form of synchronizer which allows ane Thread  to hold off for ane or to a greater extent than Threads earlier starts processing. This is real crucial requirement in addition to often needed inwards server side center Java application in addition to having this functionality built-in every bit CountDownLatch greatly simplifies the development. CountDownLatch inwards Java is introduced on Java five 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 in conclusion about worth noting points virtually this concurrent utility. You tin flame too 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 starting fourth dimension examine is tricky,  With CountDownLatch it tin flame  be done inwards simply few lines. CountDownLatch too allows flexibility on expose of thread for which main thread should wait, It tin flame hold off for ane thread or n expose of thread, at that topographic point is non much modify on code.  Key signal is that you lot demand to figure out where to occupation CountDownLatch inwards Java application which is non hard if you lot empathise 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 ane or to a greater extent than Threads earlier starts processing What is CountDownLatch inwards Java - Concurrency Example Tutorialthread waits for n expose of threads specified piece creating CountDownLatch inwards Java. Any thread, unremarkably primary thread of application,  which calls CountDownLatch.await() volition hold off until count reaches null or its interrupted yesteryear about other Thread. All other thread are required to create count downwards yesteryear calling CountDownLatch.countDown() ane time they are completed or ready to the job. every bit presently every bit count reaches zero, Thread awaiting starts running. One of the disadvantage of CountDownLatch is that its non reusable ane time count reaches to zero you lot tin flame non occupation 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 come across a total featured existent globe instance of using CountDownLatch inwards Java. In next CountDownLatch example, Java plan requires iii services namely CacheService, AlertService  and ValidationService  to survive started in addition to ready earlier application tin flame handgrip whatsoever request in addition to 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
 * useful if you lot desire to start primary processing thread ane time its dependency is completed
 * every bit 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 ready to create at that topographic point job.
       // Countdown latch is idle choice here, primary thread volition start amongst count 3
       // in addition to hold off until count reaches zero. each thread ane 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 iii since nosotros convey iii 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 course of pedagogy which volition survive 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( elevate + " 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 flame come 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 ane of Thread similar main thread, require to hold off for ane 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 center Java application which uses services architecture,  where multiple services is provided yesteryear multiple threads in addition to application tin flame non start processing  until all services convey started successfully every bit shown inwards our CountDownLatch example.


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

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

2) Main Thread hold off on Latch yesteryear calling CountDownLatch.await() method piece 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 in addition to if you lot master copy when to occupation CountDownLatch and how to occupation CountDownLatch you lot volition survive able to cut down expert sum 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 occupation ThreadLocal variable inwards Java

Sumber https://javarevisited.blogspot.com/

0 Response to "What Is Countdownlatch Inwards Coffee - Concurrency Representative Tutorial"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel