CKTIS / Java
Condition: waiting and signalling in Java
Wait for a state change in a loop, carry forward the remaining nanosecond budget, and choose whether to wake one waiter or all of them.
Version: Java SE 21
Syntax
Java SE 21 — java.util.concurrent.locks.Condition
Condition changed = lock.newCondition();
// Condition method declarations:
void await() throws InterruptedException;
long awaitNanos(long nanosTimeout) throws InterruptedException;
void signal();
void signalAll();
// Distinct timed overload of await:
boolean await(long time, TimeUnit unit) throws InterruptedException;Create a Condition with lock.newCondition(). For ReentrantLock, all four methods discussed here require the caller to hold the associated lock. Calling without the lock results in IllegalMonitorStateException, but in JDK 21, await() and awaitNanos(long) check the calling thread’s interrupt status first. If it is already set, they throw InterruptedException instead. Check and update shared state under that same lock, and call unlock() in finally.
Condition.await() waits without a timeout. It atomically releases the associated lock and reacquires it before returning. Wait in a while loop while the state you need is not present: a wakeup can be spurious, or another thread may change the state before you reacquire the lock. Both await() and awaitNanos(long) can throw InterruptedException; when they do, the interrupt status is cleared.
Condition.awaitNanos(long) takes a budget in nanoseconds and returns an estimate of the nanoseconds left after reacquiring the lock. In a loop, check the shared state first. If it still does not meet your condition, stop waiting when remaining <= 0L; otherwise use remaining = changed.awaitNanos(remaining). Do not reset the original budget. The await(long, TimeUnit) overload returns a boolean, not a remaining budget.
With ReentrantLock, an uninterrupted awaitNanos(0L) still fully releases the lock, reacquires it, and restores the original hold count. There is no positive budget for waiting, but reacquiring the lock can take time. The result is non-positive; do not assume it is exactly zero.
After updating the shared state, Condition.signal() selects at most one waiter, whereas Condition.signalAll() wakes all waiters on that same Condition. In the Condition.awaitNanos/signalAll pairing, the broadcast also reaches threads waiting with awaitNanos. Neither signalling method hands over the lock immediately or saves a signal for future waiters. Each awakened thread must reacquire the lock and recheck the state. Use signal() when waking any one waiter is enough; use signalAll() when several may proceed or you cannot tell which waiter can proceed.
Examples
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class Main {
private static final ReentrantLock lock = new ReentrantLock();
private static final Condition arrived = lock.newCondition();
private static final Condition gate = lock.newCondition();
private static int ready;
private static int passed;
private static boolean open;
private static void waitAtGate() {
lock.lock();
try {
ready++;
arrived.signal();
while (!open) {
gate.await();
}
passed++;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
lock.unlock();
}
}
public static void main(String[] args) throws InterruptedException {
Thread first = new Thread(Main::waitAtGate);
Thread second = new Thread(Main::waitAtGate);
lock.lock();
try {
lock.lock();
try {
long remaining = gate.awaitNanos(0L);
System.out.println("budget exhausted: " + (remaining <= 0L));
System.out.println("hold count: " + lock.getHoldCount());
} finally {
lock.unlock();
}
first.start();
second.start();
while (ready < 2) {
arrived.await();
}
open = true;
gate.signalAll();
System.out.println("gate opened");
} finally {
lock.unlock();
}
first.join();
second.join();
System.out.println("workers passed: " + passed);
}
}Result
budget exhausted: true hold count: 2 gate opened workers passed: 2
The first check prints only the sign test and the restored hold count of 2. Each worker then announces its arrival with `arrived.signal()`, and the main thread opens the gate and calls `gate.signalAll()`. Worker order does not affect the output.
Related lessons
- Java · Lesson 30 · Advanced · Version: 2
- Java · Lesson 54 · Intermediate · Version: 2