DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report

CountDownLatch Use-Cases

Shekhar Gulati user avatar by
Shekhar Gulati
·
Aug. 24, 10 · Interview
Like (1)
Save
Tweet
Share
23.47K Views

Join the DZone community and get the full member experience.

Join For Free

CountDownLatch is one of the classes that was added to the Java 5 concurrency package. It allows one or more threads to wait until a set of operations being performed in other threads are completed. In this article, I will talk about two use-cases where CountDownLatch can be used:

Use-case 1 :  Achieving Maximum Parallelism

Sometimes we have a use-case where we want to start a number of threads at the same time to achieve maximum parallelism. For example, we want to test a class which creates a single instance of some class.

public class ObjectFactory {

private volatile MyObject object;

public MyObject getInstance() {
if (object == null) {
synchronized (this) {
if (object == null) {
object = new MyObject();
}
}
}
return object;
}
}
Now we need to test that this class will only create a single instance of MyObject even when multiple threads access it parallely. To test this we will create a CountDownLatch and initialize it with 1. Then each thread will wait in its run method until the count down of the latch reaches zero. Because CountDownLatch is initialized with 1, a single thread call to countDown method will trigger all other threads to start at approximately the same time.
@Test
public void shouldCreateOnlySingleIntsanceOfAClassWhenTestedWithParallelThreads() throws Exception{
final ObjectFactory factory = new ObjectFactory();
final CountDownLatch startSignal = new CountDownLatch(1);
class MyThread extends Thread {
MyObject instance;
@Override
public void run() {
try {
startSignal.await();
instance = factory.getInstance();
} catch (InterruptedException e) {
// ignore
}
}
}
int threadCount = 1000;
MyThread[] threads = new MyThread[threadCount];
for (int i = 0;i< threadCount;i++) {
threads[i] = new MyThread();
threads[i].start();
}
startSignal.countDown();
for (MyThread myThread : threads) {
myThread.join();
}
MyObject instance = factory.getInstance();
for (MyThread myThread : threads) {
assertEquals(instance, myThread.instance);
}
}


Use-case 2  : Wait for several threads to complete

The second use-case arises when we want to wait for several threads to complete their work. In this scenario we will initialize the CountDownLatch with the number of threads we want to wait for and then each thread will call the countDown method on finishing its work. We will use the same example used in the first use-case where we used the method to make one thread wait for another thread to complete its work.

@Test
public void shouldCreateOnlySingleIntsanceOfAClassWhenTestedWithParallelThreads()
throws Exception {
int threadCount = 1000;
final ObjectFactory factory = new ObjectFactory();
final CountDownLatch startSignal = new CountDownLatch(1);
final CountDownLatch stopSignal = new CountDownLatch(threadCount);
class MyThread extends Thread {
MyObject instance;

@Override
public void run() {
try {
startSignal.await();
instance = factory.getInstance();
} catch (InterruptedException e) {
// ignore
} finally {
stopSignal.countDown();
}
}
}
MyThread[] threads = new MyThread[threadCount];
for (int i = 0; i < threadCount; i++) {
threads[i] = new MyThread();
threads[i].start();
}
startSignal.countDown();
stopSignal.await();
MyObject instance = factory.getInstance();
for (MyThread myThread : threads) {
assertEquals(instance, myThread.instance);
}
}
Use case

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Distributed Tracing: A Full Guide
  • Rust vs Go: Which Is Better?
  • mTLS Everywere
  • Specification by Example Is Not a Test Framework

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: