Waiting for another thread with CyclicBarrier: 2 Real-life examples

March 29, 2018

Category: The package java.util.concurrent

The CyclicBarrier let a set of threads wait till they have all reached a specific state. Initialize the CyclicBarrier with the number of threads which 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 the threads can 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 a try block, line 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 but receive a BrokenBarrierException exception.

Handling of exceptions

The BrokenBarrierException allows us to signal the other waiting threads that we can not 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 who gets interrupted, will receive an InterruptedException while waiting and all other threads waiting will receive a BrokenBarrierException. So both exception signal that we should give up 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, line 14 and 30. This also starts the second cycle. The second cycle ends when again both threads call await, line 16 and line 37. This allows you two 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 till 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 can not 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..

I would be glad to hear from you about how you use CyclicBarrier in your application.

testing multi-threaded applications on the JVM made easy

LEARN MORE

© 2020 vmlens Legal Notice Privacy Policy