JavaGian java tutorial and java interview question and answer

JavaGian , Free Online Tutorials, JavaGian provides tutorials and interview questions of all technology like java tutorial, android, java frameworks, javascript, ajax, core java, sql, python, php, c language etc. for beginners and professionals.

CountDownLatch in java

CountDownLatch is synchronisation aid that allow one or more threads to wait until set of operations being performed in other threads completes.
So in other words, CountDownLatch waits for other threads to complete set of operations.
CountDownLatch is initialized with count. Any thread generally main threads calls latch.awaits() method, so it will wait for either count becomes zero or it’s interrupted by another thread and all other thread need to call latch.countDown() once they complete some operation.
So count is reduced by 1 whenever latch.countDown() method get called, so  if count is n that means count can be used as threads have to complete some action or some action have to be completed n times.
One of disadvantage of CountDownLatch is you can not reuse it once count is zero. For that ,you need to use CyclicBarrier.

For example:

Below diagram will make you clear. It is an example how CountDownLatch can be used.
Let’s say, you are developing an application, so it’s main thread has to wait for other services (threads) such as UI initialization, database initialization and logging services to get completed.  So Countdownlatch will be initialized with 3 and main thread will call await()  method and each services will call latch.countDown() once they are about to complete.
CountDownLatch in java

Program :

Create a class named UIInitialization.java. This thread will execute latch.countDown() once it completes.
Create a class named LoggingInitialization.java. This thread will execute latch.countDown() once it completes.
Create a class named DatabaseInitialization.java. This thread will execute latch.countDown() once it completes.
Create a class CountDownLatchMain.java. This will be main thread which will wait for UIInitialization, DatabaseInitialization and LoggingInitialization.
When you run above program, you will get following output:

Why not use join instead of CountDownLatch:

As you might know you can use join for this situation too but you have to manually handles it. Most of people use ExecutorService for handling threads now and CountDownLatch works good with it. As CountDownLatch is task oriented , you can submit multiple tasks to thread pool and CountDownLatch will ensure execution of original thread once set of other  dependent threads get completed.

.