Java SE API
CyclicBarrier.await(long, TimeUnit)
Wait for the remaining parties at this barrier, with a deadline.
Formal Syntax & Structure
java syntaxjava
int await(long timeout, TimeUnit unit) throws InterruptedException, BrokenBarrierException, TimeoutExceptionParameters & Attributes
| Name | Type | Description |
|---|---|---|
| timeout | long | Maximum wait |
| unit | TimeUnit | Timeout unit |
Working Example
Example Snippetjava
import java.time.Duration;import java.util.concurrent.*;public class Main { // Only finite tasks and timed coordination are used in these examples. static void finish(Thread thread) throws InterruptedException { try { if (!thread.join(Duration.ofSeconds(3))) { thread.interrupt(); if (!thread.join(Duration.ofSeconds(3))) throw new AssertionError("worker did not stop"); throw new AssertionError("worker timed out"); } } catch (InterruptedException e) { thread.interrupt(); throw e; } } static void meet(CyclicBarrier barrier) { try { barrier.await(3, TimeUnit.SECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new AssertionError("unexpected cancellation", e); } catch (BrokenBarrierException | TimeoutException e) { throw new AssertionError(e); } } static class Counter { volatile int value; } public static void main(String[] args) throws Exception { CyclicBarrier readTogether = new CyclicBarrier(2); Counter counter = new Counter(); Runnable increment = () -> { int old = counter.value; meet(readTogether); // Both reads finish before either write. counter.value = old + 1; }; Thread a = new Thread(increment); Thread b = new Thread(increment); a.start(); b.start(); try { finish(a); } finally { finish(b); } System.out.println(counter.value); }}