Scrivio Interview library
CodingIntermediate7 min read · updated 12 November 2026

You need to wait until a condition becomes true or 500 ms pass, handling spurious wakeups correctly. Write the loop using Condition.awaitNanos.

We convert 500 ms to nanoseconds once, take the lock, and loop while the condition is false: if the remaining time is zero or less we return false, otherwise we call cond.awaitNanos(nanos) and store its return value, which is an estimate of the time still left. Because the loop checks the condition before the time, a signal that arrives just as the timeout runs out still counts, and because awaitNanos returns the remaining time, a spurious wakeup does not restart the full 500 ms. The method throws InterruptedException, which we propagate or restore.

Why this question is asked

Waiting with a timeout is everywhere in server code: wait for a connection to become free, for a batch to fill, for a background task to signal readiness, but never longer than some budget. Getting it right with a Condition is subtle, because a thread can wake up without being signalled, and a naive loop either waits too long or misses a signal. Interviewers ask for the exact loop because each line has a reason. In this answer, we will recap Condition waiting and spurious wakeups, write the loop, walk through it line by line, see the two common mistakes it avoids, and finish with interruption and the signalling side.

1A Quick Recap of Condition Waiting

A Condition belongs to a lock and lets a thread wait inside that lock until some state changes. await() releases the lock and parks the thread; when the thread is woken, it reacquires the lock before await() returns. The thread that changes the state calls signal() or signalAll() while holding the lock.

Two facts shape every correct use. First, the thread may wake up spuriously, without any signal, and it may also be woken by a signal meant for a state that has changed again by the time it gets the lock. So the state must always be checked in a loop. Second, the timed variant awaitNanos(long nanosTimeout) returns a long: an estimate of the nanoseconds left of the timeout when it returned, zero or negative if the time ran out.

2The Loop

Here is the complete method, with a flag named ready as the condition and the signalling method beside it.

Java
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
class Gate {
private final ReentrantLock lock = new ReentrantLock();
private final Condition cond = lock.newCondition();
private boolean ready; // guarded by lock
boolean awaitReady() throws InterruptedException {
long nanos = TimeUnit.MILLISECONDS.toNanos(500); // 500,000,000 ns
lock.lock();
try {
while (!ready) { // 1. check the condition first
if (nanos <= 0) return false; // 2. then the time: out of time
nanos = cond.awaitNanos(nanos); // 3. wait; keep what is left
}
return true; // ready, within 500 ms
} finally {
lock.unlock();
}
}
void open() {
lock.lock();
try {
ready = true;
cond.signalAll(); // wake every waiter
} finally {
lock.unlock();
}
}
}
// open() called after 120 ms -> awaitReady() returns true after about 120 ms
// open() never called -> awaitReady() returns false after about 500 ms

3Walking Through It Line by Line

The timeout is converted to nanoseconds once, before the loop, because the loop will count it down. Then we take the lock, since both ready and the condition are guarded by it.

Inside the loop, the first thing we do is check ready. If it is already true, perhaps because open() ran before we arrived, we skip the wait entirely and return true. Only when ready is false do we look at the time: if nothing is left, we return false. Otherwise we wait.

cond.awaitNanos(nanos) releases the lock and parks for at most nanos. It returns when signalled, when the time runs out, on a spurious wakeup, or by throwing InterruptedException. In the first three cases it has already reacquired the lock, and it returns how much of the timeout remains. We store that in nanos, so the next round of the loop waits only for what is left. Then the loop goes back to checking ready.

So whatever wakes the thread, it always re-checks the real state under the lock, and the total time waited stays close to the original 500 ms.

Step throughOne round of the timed wait loop
  1. ready is true?
    YesReturn trueNoCheck the time
  2. nanos <= 0?
    YesReturn false: timed outNoWait
  3. nanos = cond.awaitNanos(nanos)releases the lock, reacquires it before returning
  4. Back to the top: check ready again

4 steps in order. Play them, or step through them one at a time.

Condition first, time second, and the remaining time carried forward.

4Mistake 1: Restarting the Full Timeout

A tempting simpler version uses await(500, MILLISECONDS) in the loop. That method returns a boolean, false if the time elapsed, but not the remaining time.

Java
// Wrong: each spurious wakeup starts a new 500 ms wait
while (!ready) {
if (!cond.await(500, TimeUnit.MILLISECONDS)) return false;
}
// woken spuriously at 400 ms, then waits another 500 ms: up to 900 ms in total, or more

Every early wakeup, spurious or a signal for a state that has changed back, starts a fresh 500 ms wait, so the total can exceed the budget by any amount. awaitNanos avoids this by handing us the remaining time to pass into the next wait. An equivalent approach computes a deadline with System.nanoTime() + timeout once and recomputes the remaining time on each round; awaitNanos simply does that bookkeeping for us.

5Mistake 2: Checking the Time Before the Condition

The order of the two checks matters. Suppose the loop checked the time first and returned false whenever awaitNanos reported nothing left. Now imagine open() runs at 499.9 ms: it sets ready and signals, and our awaitNanos returns with a remaining time of zero or slightly negative, because the time ran out at about the same moment as the signal. A time-first loop would return false, even though ready is true and we hold the lock.

Checking ready first means that whenever the state is true by the time we look, we report success. The timeout only wins when the state is still false and no time is left. That is the behaviour callers expect: a late signal is not missed.

Java
// Wrong order: a signal at the deadline is reported as a timeout
while (true) {
if (nanos <= 0) return false; // returns false although ready may be true
if (ready) return true;
nanos = cond.awaitNanos(nanos);
}

6Interruption and the Signalling Side

awaitNanos throws InterruptedException if the thread is interrupted before or during the wait. It reacquires the lock first, so our finally block still unlocks correctly. Our method declares the exception and lets it propagate, which is usually best: the caller asked for the wait to be cancelled, and the exception tells it so. If the method cannot declare it, for example inside a Runnable, catch it, call Thread.currentThread().interrupt() to restore the interrupt status, and return false or rethrow as an unchecked exception. Never swallow it silently, or a shutdown request disappears.

On the signalling side, the rule is to change the state and signal while holding the lock, as open() does. Signalling without the lock throws IllegalMonitorStateException, and changing the state outside the lock could let a waiter check ready, see false, and park just after the signal was sent, so it would wait the full timeout. We use signalAll() here because opening the gate satisfies every waiter, not just one.

7Follow-up questions

Why does awaitNanos return an estimate rather than the exact remaining time?

Because the thread needs time to wake up and reacquire the lock after the wait ends, and that time is not known exactly. The value is good enough to carry the budget forward, but it can be slightly negative when the time is up, which is why the loop checks nanos <= 0, not nanos == 0.

Is there a version that cannot be interrupted?

Condition.awaitUninterruptibly() waits without responding to interrupts, but it has no timeout. For timed waits, all variants respond to interruption. That is usually what we want, because a timed wait in a server should be cancellable at shutdown.

How would you write the same thing without a Condition?

A CountDownLatch with a count of 1 and latch.await(500, TimeUnit.MILLISECONDS) does exactly this for a one-time gate, and it handles spurious wakeups internally. A CompletableFuture with get(500, MILLISECONDS) works if a value is being produced. The Condition loop is needed when the state can change back and forth.

8Conclusion

In this answer, we wrote a timed wait with Condition.awaitNanos: convert 500 ms to nanoseconds once, take the lock, and loop while the condition is false, returning false when no time is left and otherwise storing the remaining time that awaitNanos returns. Carrying the remaining time forward means spurious wakeups do not restart the full timeout, and checking the condition before the time means a signal that arrives at the deadline is not reported as a timeout. InterruptedException is propagated or the interrupt status is restored, and the signalling side changes the state and signals while holding the lock.

What to say in the interviewAbout 90 seconds aloud

Open with

I would write: long nanos = TimeUnit.MILLISECONDS.toNanos(500); lock.lock(); try, while not ready, if nanos is less than or equal to zero return false, otherwise nanos = cond.awaitNanos(nanos); after the loop return true; and unlock in finally.

Then, if they want more

The loop is needed because a thread can wake up spuriously, or be signalled for a state that changed again before it got the lock, so it must always re-check the real state under the lock. awaitNanos is the right method because it returns an estimate of how much of the timeout is left, so after an early wakeup I wait only for the remainder instead of starting the full 500 ms again, which is what happens if I loop on await with a fixed timeout.

The order of the checks matters: I check ready before the time. If the signal arrives right at the deadline, awaitNanos may return zero or a negative value, but ready is already true, so I return true instead of reporting a timeout. awaitNanos throws InterruptedException; I let it propagate, or if I cannot, I restore the interrupt with Thread.currentThread().interrupt().

It reacquires the lock before throwing, so the finally still unlocks correctly. And the signalling side sets ready and calls signalAll while holding the same lock, so no waiter can miss it.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "You need to wait until a condition becomes true or 500 ms pass, handling spurious...": https://scrivio-interview-library.netlify.app/java/locks/2b9a510157/