Search code examples
javacyclicbarrier

Does CyclicBarrier reset itself for the last await?


I'm leaning about the CyclicBarrier and I wrote this demo.

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import static java.util.concurrent.ThreadLocalRandom.current;
public class CyclicBarrierDemo {
    public static void main(final String[] args) {
        final int threads = 100;
        final CyclicBarrier barrier
            = new CyclicBarrier(threads, () -> System.out.println("tripped"));
        final int rounds = 5;
        for (int i = 0; i < threads; i++) {
            new Thread(() -> {
                    for (int j = 0; j < rounds; j++) {
                        try {
                            Thread.sleep(current().nextLong(1000L));
                            barrier.await();
                        } catch (InterruptedException | BrokenBarrierException e) {
                            e.printStackTrace(System.err);
                            return;
                        }
                    }
            }).start();
        }
    }
}

The program prints five tripped and quits, as I expected.

tripped
tripped
tripped
tripped
tripped

My question is that the CyclicBarrier instance reset itself when the last await() arrived? So that the output is expected? I couldn't find any words for that.


Solution

  • My question is that the CyclicBarrier instance reset itself when the last await() arrived?

    Yes. In the sense that that instance can then be reused without the application needing to do something.

    So that the output is expected?

    Yes

    I couldn't find any words for that.

    The Javadoc says: "The barrier is called cyclic because it can be re-used after the waiting threads are released."

    Also, the example shown in the javadoc would only work as described if the instance reset itself. Note that there are no explicit calls to reset(). (Furthermore, it is not clear that explictly calling reset() is useful if you want to reuse a barrier .... according to the method's javadoc.)