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.
Join the DZone community and get the full member experience.
Join For FreeThe 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:
- Initialize the CountDownLatch with the number of threads you are waiting for.
- Call await to signal that you are ready and wait for the other threads.
- 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.
- 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.
Published at DZone with permission of Thomas Krieger, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments