CyclicBarrier Broken Barrier Reset
One timed-out await puts a CyclicBarrier into the broken state: later awaiters get BrokenBarrierException immediately, and reset() clears it for the next round.
Code
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class BrokenBarrierLifecycle {
public static void main(String[] args) throws InterruptedException {
// parties=2:这里只有一个等待方,模拟另一方永远不到
CyclicBarrier barrier = new CyclicBarrier(2);
System.out.println("broken before: " + barrier.isBroken());
try {
barrier.await(50, TimeUnit.MILLISECONDS); // 超时:栅栏被打破
} catch (TimeoutException e) {
System.out.println("timed out, barrier broken: " + barrier.isBroken());
} catch (BrokenBarrierException e) {
System.out.println("entered broken, barrier broken: " + barrier.isBroken());
}
// 打破后后续 await 立刻拿到 BrokenBarrierException,而不是继续等
try {
barrier.await();
} catch (BrokenBarrierException e) {
System.out.println("late await rejected");
}
// reset:清空打破状态,栅栏可以重新投入下一轮使用
barrier.reset();
System.out.println("after reset broken: " + barrier.isBroken());
}
}How the snippet works
The snippet is organized around the class BrokenBarrierLifecycle.
What to watch for
- Imports, when present, point only at standard-library modules.
Applying it
Look for the broken before:, timed out, barrier broken:, entered broken, barrier broken: prefixes as the file executes; they connect every printed line to the step behind it.
Statements that decide the outcome
barrier.await(50, TimeUnit.MILLISECONDS); // 超时:栅栏被打破
} catch (TimeoutException e) {
System.out.println("timed out, barrier broken: " + barrier.isBroken());
CyclicBarrier barrier = new CyclicBarrier(2);
barrier.await();
Interactive Tools for This Topic
FAQ
- What does CyclicBarrier Broken Barrier Reset print when run?
- The script runs standalone; its 5 labeled outputs include `broken before:`, `timed out, barrier broken:`, `entered broken, barrier broken:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.