2

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.

Jin Kwon
  • 20,295
  • 14
  • 115
  • 184

2 Answers2

4

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.)

Steve Chambers
  • 37,270
  • 24
  • 156
  • 208
Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • Good spot with the Javadoc. IMO it would have been helpful if the Javadoc for the two `await` methods had also explicitly mentioned this (as they are fairly comprehensive in other regards). – Steve Chambers Sep 09 '20 at 20:46
  • @SteveChambers - If you think so, raise an issue via the OpenJDK issue tracker. – Stephen C Sep 09 '20 at 23:03
4

Think of CyclicBarrier as a gate and threads as cars.

The gate (barrier) will not open until it sees 100 cars waiting in front of it. When it opens, it will only allow that batch of 100 cars to pass through and close again. Same thing will happen again (cyclic).

letthefireflieslive
  • 11,493
  • 11
  • 37
  • 61