• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
  • Skip to footer
  • Core Java
  • Design Patterns
  • JSP
  • Servlets
  • Building Tools
  • jQuery
  • Spring
  • Hibernate
  • Mongo DB
  • More
    • HTML
    • SCJP
    • AJAX
    • UML
    • Struts
    • J2EE
    • Testing
    • Angular JS

J2EE Reference

  • Home
  • About Us
    • Java Learning Centers
  • Contact Us

CountDownLatch in java

April 24, 2017 By j2eereference 3 Comments

CountDownLatch is a java synchronizer that comes under java.util.concurrent package and is available in java from jdk 1.5.

It is used in the scenario where multiple threads are working together and one or more threads need to wait until a set of task is finished by other threads.

Important methods used
await() ; The current thread which called this method will go into waiting state and will wait until the count becomes 0.

CountDown() ;This method when called will decrements the count and when count becomes 0, the current thread will notify the thread which called await() on the same CountDownLatch instance.

getCount() : This method will return the current count.

How it works:

When we create an object of CountDownLatch, we pass an int value  to its constructor which  specify the number of threads it should wait for, all the thread are required to decrement this count by calling countDown() . As soon as count becomes zero, the waiting thread on which await method is called completes its waiting time and resumes further processing.

Example application

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import java.util.concurrent.CountDownLatch;
 
public class CountDownLatchExample{
public static void main(String args[]) throws InterruptedException
{
CountDownLatch latch = new CountDownLatch(3);
System.out.println("Initial count is :"+latch.getCount());
// Let us create three worker threads (subTask-1,subtask-2 and subTask-3)and start them.
for(int i=0;i<=2;i++){
new Thread(new MyRunnableDemo(latch),"subTask-"+i).start();
}
 
// The main task wait for three threads
latch.await();
System.out.println("count after completing all subtasks is :"+latch.getCount());
// Main thread has started
System.out.println("All sub tasks are finished and the main thread is starting now ...");
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName() +" thread has finished");
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import java.util.concurrent.CountDownLatch;
 
class MyRunnableDemo implements Runnable
{
private CountDownLatch latch;
public MyRunnableDemo(CountDownLatch latch)
{
this.latch = latch;
}
@Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+" finished the task");
latch.countDown();
}
}

OutPut :

Initial count is :3
subTask-0 finished the task
subTask-1 finished the task
subTask-2 finished the task
count after completing all subtasks is :0
All sub tasks are finished and the main thread is starting now …
main thread has finished

Real-time use cases

  • In an amusement park, there are certain rides in which it is mandate to have atleast 2 people (2 is count) to share seat in order to take that ride. So, ride keeper waits for 2 persons for each seat so that he can start the ride.
  • Suppose a big heavy rectangular box can be lifted by 4 people from four corners, so you will wait for all 4 to come then only you can lift that heavy box.

 

 

Related Posts

  • Busy Spinning in mutithreading
  • Implementing queue in java
  • TreeSet vs ConcurrentSkipListSet
  • How to create immutable class?
  • Implementing Stack in java
  • What is ReentrantLock?
  • What is Semaphore in java
  • Why AtomicInteger class
  • What is CyclicBarrier?
  • Prototype design pattern

Filed Under: Core Java Tagged With: countDownLatch example, J2EE, java countDownLatch

Reader Interactions

Comments

  1. Karanvir says

    May 3, 2017 at 12:02 pm

    Nice tutorial site for interview prep.

    Reply
  2. Abhiraj says

    May 5, 2017 at 8:35 am

    Nice article….plz upload some topics of garbage collection techniques

    Reply
  3. Anil Chem says

    May 9, 2017 at 12:03 pm

    Nice and accurate explanation.

    Reply

Leave a Reply Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

FOLLOW US ONLINE

  • View J2eereference-166104970118637’s profile on Facebook
  • View j2eereference’s profile on Twitter
  • View j2eereference’s profile on LinkedIn

Subscribe by email

Recent posts

  • What is parallel Stream
  • reduce method of the Stream class
  • Difference between the findFirst() and findAny() method
  • intern() method of String class
  • SOLID – Five principles of object-oriented software design
  • Java Coding Best Practices
  • How to use lambda expression effectively
  • Enhanced pseudo-Random Number Generators in java17
  • How to use Foreign-Memory Access API
  • Pattern Matching for instanceof
  • Text Blocks – Feature added in Java17
  • Record – The new feature added in java 17
  • What is Sealed Class
  • Features added in Java 17
  • Java Buzzwords

Footer

Core Java
Design Patterns
JSP
Servlets
HTML
Building Tools
AJAX
SCJP
jQuery
Testing
Spring
UML
Struts
Java Centers
Java Training
Home
About Us
Contact Us
Copyright © j2eereference.com. All right reserved.