CyclicBarrier: concordinating the stages of a multithreaded operation

The CountDownLatch class is useful for various types of "one-off" thread coordination, in particular setting threads off together. However, it has at least two features that can be inconvenient in certain situations:

The CyclicBarrier is generally more useful than CountDownLatch in cases where:

Overview of CyclicBarrier

Firstly, the barrier is constructed with the following:

Then, at each stage (or on each iteration) of the operation:

in other words, this last point means there is a mechanism for an error/timeout in one of the worker threads to "ripple out" to all threads and for the operation to halt, or for the operation to be interrupted externally by interrupting just one of the threads.

Example: parallel sort

On the next page, we look at a parallel sort using CyclicBarrier, as an example of how to use the class.


1. Provided you know which threads are awaiting a latch, you can of course interrupt them.