April 01, 2016

Part 6: Java Thread Interview Questions & Answers (CountDownLatch vs CyclicBarrier)


Let's first understand what exactly CountDownLatch and CyclicBarrier do.

What is a CountDownLatch in Java?


CountDownLatch is introduced on Java 5 along with other concurrent utilities like CyclicBarrier, Semaphore, ConcurrentHashMap, and BlockingQueue in java.util.concurrent package.

Sometimes we might need to start our application only when a particular set of tasks are complete. And these tasks might be running in parallel and getting completed together or maybe at different times. We can achieve this using CountDownLatch.

CountDownLatch is a kind of synchronizer that allows one Thread to wait for one or more Threads before starting processing. This is a very crucial requirement and often needed in server-side core Java applications and having this functionality built-in as CountDownLatch greatly simplifies the development.

If needed, we can also implement the same functionality using the wait and notify mechanism in Java, but it requires a lot of code, and getting it correct on the first attempt is a bit tricky. With CountDownLatch it can be done in just a few lines. It also allows flexibility on the number of threads for which the main thread should wait and it can wait for one thread or n number of threads, there is not much change in code.

Main Thread waits on Latch by calling CountDownLatch.await() method while the other thread calls CountDownLatch.countDown() to inform that they have completed.

Always remember we can not reuse CountDownLatch once the count is reached zero, this is the main difference between CountDownLatch and CyclicBarrier.

When to use CountDownLatch? 
Use CountDownLatch when one of the Threads, like the main thread, requires waiting for one or more threads to complete, before it starts processing.

Example of CountDownLatch



1). Create a thread class Service, which implements Runnable:


2).  Create another class with the Main method:



3).  When we run CountDownLatchDemo, we will get the below output:
service2 is now UP
service3 is now UP
service1 is now UP
service4 is now UP
All services are up..Application is starting now!!

What is CyclicBarrier in Java?


CyclicBarrier is a synchronizer introduced in JDK 5 on java.util.Concurrent package along with other concurrent utilities like Counting Semaphore, BlockingQueue, ConcurrentHashMap, etc. 

Let's assume a group of friends plans to go out for a picnic. They will decide to meet at a common point. Everyone will come there and wait. Once everyone arrives they go for a picnic together. CyclicBarrier works in a similar manner.

In CyclicBarrier a group of threads waits together until all of the threads arrive. At that point, the barrier is broken and action can optionally be taken.

CyclicBarrier is similar to CountDownLatch and allows multiple threads to wait for each other (barrier) before proceeding. But there is a difference: we cannot reuse CountDownLatch once the count reaches zero while we can reuse CyclicBarrier by calling the reset() method which resets Barrier to its initial State. It implies that CountDownLatch is good for one-time events like application start-up time and CyclicBarrier can be used in case of a recurrent event.

When to use CyclicBarrier in Java, e.g.
1). To count the population of India you can have 4 threads which count the population from North, South, East, and West, and once complete they can wait for each other, When the last thread completed their task, the Main thread or any other thread can add results from each zone and print total population.
2). To implement a multiplayer player game that cannot begin until all players have joined.

FYI,
1). If CyclicBarrier is initialized with 3 parties, 3 threads need to call the await method to break the barrier.
2). The thread will block on await() until all parties reach the barrier, another thread interrupts, or await timed out.
3). If another thread interrupts the thread which is waiting on the barrier it will throw BrokernBarrierException as shown below:
java.util.concurrent.BrokenBarrierException
        at java.util.concurrent.CyclicBarrier.dowait(CyclicBarrier.java:172)
        at java.util.concurrent.CyclicBarrier.await(CyclicBarrier.java:327)
4). CyclicBarrier.reset() puts Barrier in its initial state, another thread that is waiting or has not yet reached the barrier will terminate with java.util.concurrent.BrokenBarrierException.

Example of CyclicBarrier

1). Create a class that extends Thread




2). Now let's create CyclicBarrierDemo class.


3). When we run CyclicBarrierDemo, the output will be:
main has finished
Party1 is calling await()
Party2 is calling await()
Party3 is calling await()
Party4 is calling await()
Party4 has started running again
Party3 has started running again
Party2 has started running again
Party1 has started running again


What is the difference between CountDownLatch and CyclicBarrier in Java?


The main difference between CountDownLatch and CyclicBarrier is that we can not re-use CountDownLatch once count reaches zero, but we can reuse the same CyclicBarrier even after the barrier is broken.  In short, when the barrier trips in CyclicBarrier, the count resets to its original value. CountDownLatch is different because the count never resets.

CyclicBarrier allows a number of threads to wait on each other, whereas CountDownLatch allows one or more threads to wait for a number of tasks to complete. We can say CyclicBarrier maintains a count of threads whereas CountDownLatch maintains a count of tasks.

Let's take a hypothetical example of a meditation room, where people come to relax. Here a person is a thread, a meditation room is a resource.

  • If only one person is allowed to come inside the meditation room it will be called MUTEX.
  • Assume N numbers of people are allowed to come inside the meditation room. If anybody leaves the room then another person can be allowed to come inside and relax. This will be called SEMAPHORE.
  • If no one is allowed to enter the meditation room until x number of people arrives, where each person has free will to leave the meditation room. This will be called COUNTDOWNLATCH.
  • Assume no one is allowed to start the meditation unless (they can come inside the meditation room) until X number of people comes inside the meditation room. Let's say we have an instructor, who will not start the meditation class until all the persons enter and grab the seat. Once the meditation class is finished the same barrier will be applied for the next class. This is called CYCLICBARRIER.

No comments:

Post a Comment