Showing posts with label CountDownLatch in java. Show all posts
Showing posts with label CountDownLatch in java. Show all posts

Friday, October 4, 2013

CyclicBarrier vs CountDownLatch in Java

If you want to get an idea of these two terms before looking into the differences. Please have a look at the following posts. These will explain both the terms with the help of real scenario examples.

CyclicBarrier in Java
CountDownLatch in Java


  • CyclicBarrier as name suggest. CyclicBarrier can be used re-used after the waiting threads are released for synchronization. So the cyclic barrier is used for multiple synchronization points where as CountDownLatch is one synchronization point because we can't re-use it.
  • CyclicBarrier takes an (optional) Runnable task which is run once the common barrier condition is met. where as in CountDownLatch there is no optional runnable task.
  • When using a CyclicBarrier, the assumption is that you specify the number of waiting threads that trigger the barrier. If you specify 3, you must have at least 3 threads to call await(). When using a CountDownLatch, you specify the number of calls to countDown() that will result in all waiting threads being released.
  • In CyclicBarrier  If a thread leaves a barrier point prematurely because of interruption, failure, or timeout, all other threads waiting at that barrier point will also leave abnormally via BrokenBarrierException (or InterruptedException if they too were interrupted at about the same time). where as this is not present in CountDownLatch


Related Post
Semaphore in Java
How Thread exchange data in java
Semaphore vs CountDownLatch
How class are loaded in JVM


If you know anyone who has started learning Java, why not help them out! Just share this post with them. 
Thanks for studying today!...

Monday, September 30, 2013

Semaphore vs CountDownLatch in java


I recommend  before looking for a difference between semaphore and CountDownLatch  if you go through the following post, difference is easy to understand as semaphore and CountDownLatch are explained with detailed examples.


CountDownLatch with examples
Semaphore with examples



Both CountDownLatch and semaphore used for difference scenario and main difference is


  • CountdownLatch is used to start a series of threads and then wait until all of them are complete a given number of times, for instance, before starting main service you want to start initializing services like db connection, starting logging service etc.
  • Semaphore is used to control the number of concurrent threads that are using a resource.That resource can be something like a shared data, or any file. The count on a Semaphore can go up and down as different threads call acquire() and release().






Related Post
Daemon Thread in java with demo example
Concept of Upcasting and downcasting in java with example
Why java doesn't support operator overloading
when to use concurrent Has Map



Thanks for reading the post !
Please share or comment on this as this encourage me to write more :) 



Wednesday, September 12, 2012

CountDownLatch in java

The Java concurrency API provides a class that allows one or more threads to wait until a set of operations are made. It's the CountDownLatch class. This class is initialized with an integer number, which is the number of operations the threads are going to wait for. When a thread wants to wait for the execution of these operations, it uses the await() method.
This method puts the thread to sleep until the operations are completed. When one of these operations finishes, it uses the countDown() method to decrement the internal counter of the CountDownLatch class. When the counter arrives to 0, the class wakes up all the threads that were sleeping in the await() method.




  • This requirement is often needed in server side core java application.
  • You can implement the same functionality using wait() & Notify() mechanism but it require lot of code With CountDownLatch it can be done in few lines.

There is flexibility on number of Threads for which main Thread should wait. It can be one or n number of Threads. CountDownLatch work on the latch principle, means main Thread wait until Gate is open.One thread waits for n number of threads specified while creating CountDownLatch.

Usually main thread of application, which call CountDownLatch.await() will wait until count reached 0 or its interrupted by another thread. All other thread are required to do count down by calling CountDownLatch.countDown() once they complete there job.

East Definition to remember CountDownLatch :
"Suppose a car can be lifted by 5 people so you will wait for all 5 to come. Then only you can lift the car."

Before looking into example, let have a look of countdownlatch class function:
  1. CountDownLatch(int count) : Creates an instance of CountDownLatch with the number of times the countDown() method must be called before the threads waiting with await()can continue execution.
  2. void await( ) : If the current count in CountDownLatch object is zero, it immediately returns; otherwise, the thread blocks until the countdown reaches zero. Can throw an InterruptedException
  3. void countDown( ) : Reduces the number of counts by one in this CountDownLatch object. If the count reaches zero, all the (a)waiting threads are released. If the current count is already zero, nothing happens.
  4. long getCount( ) : Returns the pending counts in this CountDownLatch object.


Example 1 :
For instance, before starting you main application may be you want to start few services such validation, db connection etc in such countdownlatch come into picture.
Here we consider 3 services that we need to start before main services. Please have a look at the code you will easily understood.


Output Sample:
validationis up
readis up
initial up
All Services is up

Example 2

Racing example


This example simulates the start of a running race by counting down from 5. It holds 3 runner thread to be ready to start in the start line of race and once the count down reaches 0, all the 3 runners start running.









Sample Output
tortise ready for countdown to start
hare ready for countdown to start
frog ready for countdown to start
Counter starting
5
4
3
2
1
tortise running....
hare running....
frog running....

How it works...
The CountDownLatch class has three basic elements:

  • The initialization value that determines how many events the CountDownLatch class waits for
  • The await() method, called by the threads that wait for the finalization of all the events
  • The countDown() method, called by the events when they finish their execution

When you create a CountDownLatch object, the object uses the constructor's parameter to initialize an internal counter. Every time a thread calls the countDown() method, the CountDownLatch object decrements the internal counter in one unit. When the internal counter arrives to 0, the CountDownLatch object wakes up all the threads that were waiting in the await() method.
There's no way to re-initialize the internal counter of the CountDownLatch object or to modify its value. Once the counter is initialized, the only method you can use to modify its value is the countDown() method explained earlier. When the counter arrives to 0, all the calls to the await() method return immediately and all subsequent calls to the countDown() method have no effect.

There are some differences with respect to other synchronization methods, which are as follows:

  • The CountDownLatch mechanism is not used to protect a shared resource or a  critical section. It is used to synchronize one or more threads with the execution of  various tasks.
  • It only admits one use. As we explained earlier, once the counter of CountDownLatch arrives at 0, all the calls to its methods have no effect. You have to create a new object if you want to do the same synchronization again.



Related Post

If you know anyone who has started learning Java, why not help them out! Just share this post with them. Thanks for studying today!...