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

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

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

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Keep Your Application Secrets Secret
  • Commonly Occurring Errors in Microsoft Graph Integrations and How To Troubleshoot Them (Part 4)
  • Projections/DTOs in Spring Data R2DBC
  • Coordinating Threads Using CountDownLatch

Trending

  • It’s Not About Control — It’s About Collaboration Between Architecture and Security
  • Issue and Present Verifiable Credentials With Spring Boot and Android
  • How to Practice TDD With Kotlin
  • Java Virtual Threads and Scaling
  1. DZone
  2. Coding
  3. Java
  4. Waiting for Another Thread With CyclicBarrier

Waiting for Another Thread With CyclicBarrier

Let's outline the ideal scenarios and steps involved when invoking CyclicBarrier to wait for threads, or when other classes might be better.

By 
Thomas Krieger user avatar
Thomas Krieger
·
Updated Apr. 16, 18 · Tutorial
Likes (11)
Comment
Save
Tweet
Share
18.1K Views

Join the DZone community and get the full member experience.

Join For Free

The CyclicBarrier lets a set of threads wait until they have all reached a specific state. Initialize the CyclicBarrier with the number of threads that need to wait for each other. Call await to signal that you are ready to proceed and wait for the other threads. We will see how to use it by looking at two real-life examples.

How to Use CyclicBarrier

The first use case of CyclicBarrier is to signal that we are ready to proceed and wait for the other threads. The class DistributedTxCommitTask from the Blazegraph open source graph database uses the CyclicBarrier to coordinate multiple threads. The following shows the creation of the CyclicBarrier:

preparedBarrier = new CyclicBarrier(nservices,
            new Runnable() {
                public void run() {
            // Statements omitted
                }
            });


We need to wait for nservices' threads, so we initialize the CyclicBarrier with this variable, line 1. To execute an action after all threads have called await, we initialize the CyclicBarrier with a Runnable, line 2. The run method of the Runnable class will be called by the last thread calling await. Only after the run method was executed can the threads continue.

When we are ready, we call await, signaling that we are ready and waiting for the other threads:

try {
        // Statements omitted
        preparedBarrier.await();
        // Statements omitted
} finally {               
       if (preparedBarrier != null)
             preparedBarrier.reset();
}


As we see, we execute the task of the thread via a try block, lines 1 to 4. And we call the reset method of the CyclicBarrier in a finally block, line 7. This makes sure that, in the case of an exception, other threads are not waiting infinitely and receive a BrokenBarrierException exception.

Handling of Exceptions

The BrokenBarrierException allows us to signal the other waiting threads that we cannot finish our task and it does not make sense to wait any longer. The BrokenBarrierException gets thrown when:

  • Another thread was interrupted by calling Thread.interrupt while waiting
  • CyclicBarrier reset was called while other threads were still waiting at the barrier.

In the case of Thread.interrupt, the thread that gets interrupted will receive an InterruptedException while waiting and all other threads waiting will receive a BrokenBarrierException. So both exceptions signal that we should give up on our task.

Waiting in Cycles

The second use case of CyclicBarrier is to wait in cycles. The MoreExecutorsTest test from guava, the Google core libraries for Java, shows how to do this. The following shows the first two cycles of this test:

public void testDirectExecutorServiceServiceTermination() throws Exception {
   final ExecutorService executor = newDirectExecutorService();
   final CyclicBarrier barrier = new CyclicBarrier(2);
   Thread otherThread =
       new Thread(
           new Runnable() {
             public void run() {
               try {
                 Future<?> future =
                     executor.submit(
                         new Callable<Void>() {
                           public Void call() throws Exception {
                             // WAIT #1
                             barrier.await(1, TimeUnit.SECONDS);
                             // WAIT #2
                             barrier.await(1, TimeUnit.SECONDS);
                             assertTrue(executor.isShutdown());
                             assertFalse(executor.isTerminated());
                             // Next cycle omitted
                           }
                         });
              // checks omitted
               } catch (Throwable t) {
                 throwableFromOtherThread.set(t);
               }
             }
           });
   otherThread.start();
   // WAIT #1
   barrier.await(1, TimeUnit.SECONDS);
   assertFalse(executor.isShutdown());
   assertFalse(executor.isTerminated());
   executor.shutdown();
   assertTrue(executor.isShutdown());
   assertFalse(executor.isTerminated());
   // WAIT #2
   barrier.await(1, TimeUnit.SECONDS);
   // Next cycle omitted
}


We initialize the CyclicBarrier for two threads, line 3. The first cycle ends when both threads call await, lines 14 and 30. This also starts the second cycle. The second cycle ends when both threads call await again, lines 16 and line 37. This allows you to test a process in multiple steps.

Other Classes to Wait for Threads

Java provides three classes to wait for other threads: CyclicBarrier, CountDownLatch, and Phaser. Use CyclicBarrier when you do the work and need to wait in the same threads. When you need to wait for tasks done in other threads, use CountDownLatch instead. To use CyclicBarrier or CountDownLatch, you need to know the number of threads when you call the constructor. If you need to add threads after construction time, use the class Phaser.

Summary and Next Steps

Use the following steps to wait until a set of threads have reached a specific state with CyclicBarrier:

  1. Initialize the CountDownLatch with the number of threads you are waiting for.
  2. Call await to signal that you are ready and wait for the other threads.
  3. Call reset in the finally block. This makes sure that other threads receive a BrokenBarrierException instead of waiting infinitely when this thread cannot finish its task.
  4. BrokenBarrierException and InterruptedException both signal that we should give up our task.

To use CyclicBarrier, you need to know the number of threads working on the task in advance. We will look at the class Phaser next, which allows us to register threads after construction.

Task (computing) Use case Signal Open source Testing Blocks Reset (computing) Java (programming language) Google (verb)

Published at DZone with permission of Thomas Krieger, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Keep Your Application Secrets Secret
  • Commonly Occurring Errors in Microsoft Graph Integrations and How To Troubleshoot Them (Part 4)
  • Projections/DTOs in Spring Data R2DBC
  • Coordinating Threads Using CountDownLatch

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!