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

How are you handling the data revolution? We want your take on what's real, what's hype, and what's next in the world of data engineering.

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

SBOMs are essential to circumventing software supply chain attacks, and they provide visibility into various software components.

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

  • Build Your Private Cloud at Home
  • Design Guards: The Missing Layer in Your Code Quality Strategy
  • How to Write for DZone Publications: Trend Reports and Refcards
  • Unveiling Supply Chain Transformation: IIoT and Digital Twins

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

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
  • [email protected]

Let's be friends: