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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

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
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

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • AI’s Role in Everyday Development
  • Leveraging Neo4j for Effective Identity Access Management
  • Process Mining Key Elements
  • The Power of Market Disruption: How to Detect Fraud With Graph Data

Trending

  • Can You Run a MariaDB Cluster on a $150 Kubernetes Lab? I Gave It a Shot
  • Exploring Intercooler.js: Simplify AJAX With HTML Attributes
  • Unit Testing Large Codebases: Principles, Practices, and C++ Examples
  • Designing a Java Connector for Software Integrations

CountDownLatch Use-Cases

By 
Shekhar Gulati user avatar
Shekhar Gulati
·
Aug. 24, 10 · Interview
Likes (1)
Comment
Save
Tweet
Share
24.4K 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.

Related

  • AI’s Role in Everyday Development
  • Leveraging Neo4j for Effective Identity Access Management
  • Process Mining Key Elements
  • The Power of Market Disruption: How to Detect Fraud With Graph Data

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!