Java SE API
CountDownLatch.await(long, TimeUnit)
Wait for the count to reach zero or the timeout to elapse.
Formal Syntax & Structure
java syntaxjava
boolean await(long timeout, TimeUnit unit) throws InterruptedExceptionParameters & 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 await(CountDownLatch latch) { try { if (!latch.await(3, TimeUnit.SECONDS)) throw new AssertionError("latch timed out"); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new AssertionError("unexpected cancellation", e); } } static class Box { int value; } public static void main(String[] args) throws Exception { Box box = new Box(); CountDownLatch available = new CountDownLatch(1); Thread writer = new Thread(() -> { box.value = 17; available.countDown(); }); writer.start(); try { await(available); System.out.println(box.value); } finally { finish(writer); } }}