AddThis

Thursday 30 January 2020

Semaphore / CountDownLatch / CyclicBarrier Java Concurrency


With Java 5 a lot of concurrency mechanisms were introduced for synchronization. There are three very important concurrency elements that were introduced in Java 5.
  1. Counting Semaphore
  2. CountDownLatch
  3. CyclicBarrier

Today we will try to understand these. Not only their understanding helps us with multithreading they are also a popular topic of Java interview question. Let's see them one by one.

Semaphore
Semaphore maintains a number of permits for a resource and only that many number of threads can access the resource. If the maximum permits allowed is reached then threads will have to wait till some other thread owing a permit releases it.

As an example lets consider a simple semaphore with 1 permit. It's called binary semaphore. It's similar to wait and notify on same object.


public static void main(String args[])
{
              Semaphore binarySemaphore = new Semaphore(1);
              new Thread(() -> {
                             try {
                                           binarySemaphore.acquire();
                                           System.out.println("Semaphore permit acquired by : " + Thread.currentThread().getName());
                                            
                             } catch (Exception e) {
                                           e.printStackTrace();
                             }
                             finally {
                                           System.out.println("Semaphore permit getting released by : " + Thread.currentThread().getName());
                                           binarySemaphore.release();            }
                              
              }).start();
              new Thread(() -> {
                             try {
                                           binarySemaphore.acquire();
                                           System.out.println("Semaphore permit acquired by : " + Thread.currentThread().getName());
                                            
                             } catch (Exception e) {
                                           e.printStackTrace();
                             }
                             finally {
                                           System.out.println("Semaphore permit getting released by : " + Thread.currentThread().getName());
                                           binarySemaphore.release();
                             }
                              
              }).start();
}


and the output would be -
Semaphore permit acquired by : Thread-0
Semaphore permit getting released by : Thread-0
Semaphore permit acquired by : Thread-1
Semaphore permit getting released by : Thread-1

 As you can see from code above you acquire a permit using acquire() method and release a permit using release() method.


NOTES :
You can also acquire permit using acquireUninterruptibly(). This is a blocking call and the thread cannot be interrupted.
Now acquire() is also a blocking call however it can be interrupted unlike acquireUninterruptibly() call
You can also use tryAcquire() call which will try to acquire the permit and if available will return immediately with true. If it is not available it will also return immediately with false. So this is a non blocking call.

CountDownLatch
This is another synchronization mechanism in which a resource is not allowed access till predefined number of threads don't complete their operations. So lets say there are 10 threads making a bread slice. As soon as we are ready with 5 slices we can lets say pack it together for selling. In this case we can use a CountDownLatch. Initialize one with 5 and as soon as 5 threads acknowledge they have finished making slices we can start packing (probably a new thread).

So a thread will wait for n other threads. Let's see an example –


public static void main(String args[])
{
              CountDownLatch countDownLatch = new CountDownLatch(2);
              new Thread(() -> {
                             try {
                                           Thread.sleep(2000);
                                           System.out.println("Calling countdown by : " + Thread.currentThread().getName());
                                           countDownLatch.countDown();
                             } catch (Exception e) {
                                           e.printStackTrace();
                             }
                            
              }).start();
              new Thread(() -> {
                             try {
                                           Thread.sleep(2000);
                                           System.out.println("Calling countdown by : " + Thread.currentThread().getName());
                                           countDownLatch.countDown();
                             } catch (Exception e) {
                                           e.printStackTrace();
                             }
                            
              }).start();
             
              try {
                             System.out.println("Waiting for all other threads finish operation");
                             countDownLatch.await();
                             System.out.println("All other threads finish operation!");
              } catch (InterruptedException e) {
                             e.printStackTrace();
              }
}

Output :
Waiting for all other threads finish operation
Calling countdown by : Thread-1
Calling countdown by : Thread-0
All other threads finish operation!
As you can see main thread calls await() on the countdownlatch and wait for 2 threads to call countDown() on it. Here n is 2 but you can configure it in the constructor.

You need to use this when your use case is to wait for some other initial operations to finish before starting some other operation.

NOTE :
 CountDownLatch is not reusable. So once the count reaches 0 i.e n threads have called countdown() the latch is unusable.

CyclicBarrier
CyclicBarrier is yet another synchronization mechanism. In this, all n threads will wait for each other to reach the barrier. Such waiting threads are called parties. The number of parties are set in the CyclicBarrier during its creation. All parties reach the barrier and call await() which is a blocking call. Once all parties reach the barrier i.e all call await() then all threads get unblocked and proceed for next execution.

Simple use case that you can think of is a multiple game scenario in which a game would not start until all the players have joined. Here all the players are parties whereas game start is a barrier.

Eg –


public static void main(String args[])
{
              CyclicBarrier cyclicBarrier = new CyclicBarrier(3);
              new Thread(() -> {
                             try {
                                           Thread.sleep(2000);
                                           System.out.println("Player joining : " + Thread.currentThread().getName());
                                           cyclicBarrier.await();
                                           System.out.println("Game starting from : " + Thread.currentThread().getName());
                             } catch (Exception e) {
                                           e.printStackTrace();
                             }
                            
              }).start();
              new Thread(() -> {
                             try {
                                           Thread.sleep(2000);
                                           System.out.println("Player joining : " + Thread.currentThread().getName());
                                           cyclicBarrier.await();
                                           System.out.println("Game starting from : " + Thread.currentThread().getName());
                             } catch (Exception e) {
                                           e.printStackTrace();
                             }
                            
              }).start();
              new Thread(() -> {
                             try {
                                           Thread.sleep(2000);
                                           System.out.println("Player joining : " + Thread.currentThread().getName());
                                           cyclicBarrier.await();
                                           System.out.println("Game starting from : " + Thread.currentThread().getName());
                             } catch (Exception e) {
                                           e.printStackTrace();
                             }
                            
              }).start();
             
}

and the output is -
Player joining : Thread-0
Player joining : Thread-1
Player joining : Thread-2
Game starting from : Thread-2
Game starting from : Thread-0
Game starting from : Thread-1
As you can see all threads (3 in above case) will wait for each other to reach the barrier. Once they all reach and call await() they can all proceed to their further tasks.
NOTE :
cyclicBarrier.reset() will put barrier on its initial state, other thread which is waiting or not yet reached barrier will terminate with java.util.concurrent.BrokenBarrierException. So CyclicBarrier can be reused unlike CountDownLatch.

Both CyclicBarrier and CountDownLatch are used to implement a scenario where one Thread waits for one or more Thread to complete there job before starts processing but there is one Difference between CountDownLatch and CyclicBarrier in Java which separates them apart and that is, you can not reuse same CountDownLatch instance once count reaches to zero and latch is open, on the other hand CyclicBarrier can be reused by resetting Barrier, Once barrier is broken.
One major difference is that CyclicBarrier takes an (optional) Runnable task which is run once the common barrier condition is met.
It also allows you to get the number of clients waiting at the barrier and the number required to trigger the barrier. Once triggered the barrier is reset and can be used again.

Summary

Semaphore : Manages a fixed sized pool of resources.
CountDownLatch : One or more threads wait for a set of threads to finish operations.
CyclicBarrier : Set of threads wait for each other until they reach a specific point.



No comments:

Post a Comment

100 AWS Services in Just One Line Each

  100 AWS Services in Just One Line Each Amazon EC2:  Virtual servers in the cloud. Amazon S3:  Scalable object storage service. Amazon RDS:...