• Latest Code...

    Advanced Multi Threading in Java [ Latch ]

    CountDown latch is one of the kinds of synchronizer which wait for another thread before performing the tasks or This is used to synchronize one or more tasks by enabling them to wait for the tasks completed by other tasks.  It was introduced in Java 5 along with other CyclicBarrier, Semaphore, CuncurrentHashMap and BlockingQueue. Its somehow like the wait and notify but in the more simpler form and will much less code.

    It basically works in the latch principle. Or let us suppose we have a seller who is going to sell 10 (No. of operations) apples. The number of customers may be anything but what the seller is concerned about is the number of apples because when it reaches to 0 he can go home. The seller(Main Thread) will wait for the customers (awaits()). Let's say there are 10 customers(Threads) now who are in the line to buy Apple. When one customer buys that Apple then the number of apple decrease by 1 (countdown()) and another customer will get a chance to buy that apple so on the number of apples goes on decreases and finally become 0. After no apples left in the bucket, the seller can stop selling and go home happily. 

    Note:: In CountDown Latch the countdown cannot be reset. 

    Let's have a look at Java code::

    package com.latch;

    import java.util.Random;
    import java.util.concurrent.CountDownLatch;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;

    /**
     * Created by yubraj on 1/16/17.
     */




    public class latch {

     public static void main(String[] args) {
      ExecutorService executorService = Executors.newSingleThreadExecutor();
      CountDownLatch countDownLatch = new CountDownLatch(5);

      for (int i = 0; i < 5; i++)
       executorService.execute(new Worker(i, countDownLatch));

      try {
       countDownLatch.await();
      } catch (InterruptedException e) {
       e.printStackTrace();
      }

      System.out.println("All the prerequities are done now the application is ready to run yuppy!!!");
      executorService.shutdown();

     }

    }

    class Worker implements Runnable {
     private int id;
     private CountDownLatch countDownLatch;
     private Random random;

     public Worker(int id, CountDownLatch countDownLatch) {
      this.id = id;
      this.countDownLatch = countDownLatch;
     }

     @Override
     public void run() {
      dowork();
      countDownLatch.countDown();
     }

     private void dowork() {
      System.out.println("Thread with id " + this.id + " is Running .....");
      try {
       Thread.sleep(1000);
      } catch (InterruptedException e) {
       e.printStackTrace();
      }
     }

    }


    Circle

    Most recent Elastic Search tutorials for beginner, intermediate and advance level developer, Yubraj Pokharel, in CodingWorkspace