Saturday, July 21, 2018

What do you know about CountDownLatch in java?

  1. CountDownLatch is one of the Java Concurrency Utility.
  2. It was introduced in java 5
  3. It falls under java.util.concurrency package
  4. It is kind of synchronizer
  5. It makes 1 thread to wait until other threads have finished their job.
Important methods of CountDownLatch class
  1. await(): void
  2. countDown(): void
  3. getCount(): long
Problem statementI need to get an online food order having various food items i.e. Pizza, Pasta, Coke. Start tracking the processing of the food in another threads. Once all the food items are prepared, I need to notify the customer that food is prepared.

[1]

import java.util.concurrent.CountDownLatch;
public class Processor {
    public static void main(String args[]) {
     CountDownLatch countDownLatch = new CountDownLatch(args.length);
     Thread foodProcessorThread = new Thread(new FoodProcessor(countDownLatch, args));
        foodProcessorThread.start();
        System.out.println("Order is received and is being processed");
        try {
            countDownLatch.await();
            System.out.println("Order is processed successfully and is ready to get dispatched");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
[2]
import java.util.concurrent.CountDownLatch;
public class FoodProcessor implements Runnable {
    private final CountDownLatch latch;
    private final String items[];
    public FoodProcessor(CountDownLatch latch, String items[]) {
        this.latch = latch;
        this.items = items;
    }
    @Override
    public void run() {
        for (int i = 0; i < items.length; i++) {
            try {
                System.out.println("Before processing the item, value of CountDownLatch: " + latch.getCount());
                Thread.sleep(10000);
                System.out.println("items " + items[i] + " is prepared");
                latch.countDown();
                System.out.println("After processing the item, value of CountDownLatch: " + latch.getCount());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
Output:
Order is received and is being processed
Before processing the item, value of CountDownLatch: 3
items Pizza is prepared
After processing the item, value of CountDownLatch: 2
Before processing the item, value of CountDownLatch: 2
items Pasta is prepared
After processing the item, value of CountDownLatch: 1
Before processing the item, value of CountDownLatch: 1
items Coke is prepared
After processing the item, value of CountDownLatch: 0

Order is processed successfully and is ready to get dispatched
ref: click for oracle CountDownLatch doc

    No comments:

    Post a Comment

    Blueprint for self-improvement

    To learn faster: Make the process fun To understand yourself : Write To understand the world better : Read To build deeper connection : Lis...