Scrivio Interview library
ConceptFoundations7 min read · updated 12 November 2026

How does DelayQueue work, and what must an element class implement?

DelayQueue is an unbounded BlockingQueue of Delayed elements, backed by a PriorityQueue ordered by remaining delay, so the element that expires first is always at the head. Element classes implement getDelay(TimeUnit) and compareTo consistently, ideally computing the delay from a deadline based on System.nanoTime. take() blocks until the head's delay has expired, poll() returns null if nothing has expired yet, and size() counts expired and unexpired elements alike.

Why this question is asked

Many programs need to do something later: retry a request in 30 seconds, expire a session after 20 minutes, release a reservation if it is not confirmed in time. DelayQueue is the JDK's building block for this, and ScheduledThreadPoolExecutor uses the same idea internally. Interviewers ask about it because writing a correct element class requires understanding how the queue orders and releases elements, and the clock mistakes are easy to make. In this answer, we will recap what DelayQueue promises, see how it is built, write a correct Delayed element, watch take and poll in action, and look at the details of size, ordering and clocks.

1A Quick Recap of What DelayQueue Promises

A DelayQueue holds elements that each become available at a certain moment. Until that moment, an element is in the queue but cannot be taken. Consumers calling take wait until the earliest element's time has come and then receive it. In other words, it is a queue where every element carries its own release time.

It implements BlockingQueue, so it works with the usual producer and consumer code: producers call put or offer, consumers call take or poll. It is unbounded, so put never blocks; only the consumer side waits, and it waits for time rather than for space.

2How It Is Built

Inside, DelayQueue keeps a PriorityQueue of its elements, ordered by their compareTo method, which must order them by remaining delay. The element that expires soonest is therefore always at the head of the heap. A single ReentrantLock guards the queue, and a condition called available is where consumers wait.

When a consumer calls take, it locks, looks at the head, and asks it for its remaining delay with getDelay(TimeUnit.NANOSECONDS). If the delay is zero or negative, the element has expired and is removed and returned. If it is positive, the consumer waits on the condition for that long. One waiting consumer, called the leader, waits for exactly the head's delay, while any other consumers wait without a timeout until signalled, so that only one thread wakes up per expiry. If a new element is added that expires earlier than the current head, the queue signals the waiting thread so it recalculates.

Step throughWhat take() does
  1. Is the queue empty?
    YesWait until an element is addedNoLook at the head
  2. Ask the head for its delaygetDelay(NANOSECONDS)
  3. Is the delay <= 0?
    YesRemove the head and return itNoWait up to that delay
  4. Woken by timeout or a new, earlier elementloop back and check again

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

Only the head is ever checked, which is why compareTo must agree with getDelay.

3Writing a Correct Delayed Element

An element implements the Delayed interface, which has one method of its own, getDelay(TimeUnit), and inherits compareTo from Comparable<Delayed>. The safest design stores a fixed deadline when the element is created and computes the remaining delay from it each time.

Java
final class RetryTask implements Delayed {
final String name;
private final long deadlineNanos; // fixed at creation
RetryTask(String name, Duration delay) {
this.name = name;
this.deadlineNanos = System.nanoTime() + delay.toNanos();
}
@Override public long getDelay(TimeUnit unit) {
return unit.convert(deadlineNanos - System.nanoTime(), TimeUnit.NANOSECONDS); // <= 0 means expired
}
@Override public int compareTo(Delayed other) {
if (other == this) return 0;
if (other instanceof RetryTask t) {
return Long.compare(deadlineNanos - t.deadlineNanos, 0); // earlier deadline first
}
return Long.compare(getDelay(TimeUnit.NANOSECONDS), other.getDelay(TimeUnit.NANOSECONDS));
}
}

Notice three choices. First, compareTo orders by the same deadline that getDelay uses, so the element with the smallest delay is always at the head. If the two disagreed, the queue might wait on an element far in the future while an earlier one sits behind it, unseen. Second, getDelay converts with unit.convert, because callers may ask in any unit; DelayQueue itself asks in nanoseconds. Third, deadlines are compared by subtracting them, which stays correct even if nanoTime values overflow, as the nanoTime documentation recommends.

The deadline comes from System.nanoTime, not System.currentTimeMillis. nanoTime is a monotonic clock that only moves forward at a steady rate and is meant for measuring elapsed time. currentTimeMillis is the wall clock, which can jump when NTP corrects it or an administrator changes the time; a jump backwards of a minute would delay every element by a minute, and a jump forward would release them early.

4Take, poll and size in Action

Let us add three tasks with different delays, in a mixed order, and watch the queue.

Java
DelayQueue<RetryTask> queue = new DelayQueue<>();
queue.put(new RetryTask("c", Duration.ofMillis(300)));
queue.put(new RetryTask("a", Duration.ofMillis(100)));
queue.put(new RetryTask("b", Duration.ofMillis(200)));
System.out.println(queue.size()); // 3: unexpired elements count too
System.out.println(queue.poll()); // null: nothing has expired yet
System.out.println(queue.peek().name); // a: peek shows the head even before it expires
System.out.println(queue.take().name); // a, after about 100 ms
System.out.println(queue.take().name); // b, after about 200 ms
System.out.println(queue.take().name); // c, after about 300 ms
System.out.println(queue.poll(50, TimeUnit.MILLISECONDS)); // null: empty, waited 50 ms

So expired elements come out in expiry order, not insertion order. poll without arguments never waits: it returns the head only if it has already expired. The timed poll waits up to the given time for an element to expire. size() is 3 at the start even though none is available, which surprises people who use size to decide whether there is work. peek returns the head whether or not it has expired.

5Details Worth Knowing

Because DelayQueue is unbounded, a producer that adds faster than elements expire and are consumed grows memory without limit; long delays make this worse, because elements stay longer. All its contents live in memory, so a restart loses every pending element. It does not accept null elements. drainTo moves only expired elements. And element objects are compared through compareTo, so if a task's deadline must change, we remove it and add a new one rather than mutating it inside the heap.

In application code we often use ScheduledExecutorService instead, which is built on the same idea and runs a task when its delay expires. DelayQueue is the better fit when we want consumer threads to pull timed items and decide what to do with them, for example in a custom cache expiry or rate limiting component.

6Follow-up questions

Why must compareTo be consistent with getDelay?

DelayQueue only ever checks the head of its priority queue, and the head is chosen by compareTo. If compareTo did not order elements by remaining delay, an element with a later deadline could sit at the head, and take would wait for it while an earlier element behind it was already due.

What happens if getDelay is computed from the wall clock?

If the system clock is changed, for example by an NTP correction or a manual change, all delays shift with it. A clock moved back an hour would hold every element for an extra hour. With System.nanoTime, delays measure elapsed time and are unaffected by wall clock changes.

Can several consumers take from the same DelayQueue?

Yes. It is thread-safe, and each expired element is delivered to exactly one consumer. Internally one consumer, the leader, waits for the head's exact delay, and the others wait until signalled, so expiry does not wake every thread at once.

7Conclusion

In this answer, we saw that DelayQueue is an unbounded BlockingQueue whose elements implement Delayed, kept in a PriorityQueue ordered by remaining delay and guarded by one lock. Elements implement getDelay(TimeUnit) and a compareTo consistent with it, best computed from a fixed System.nanoTime deadline so wall clock changes do not matter. take() blocks until the head expires, poll() returns null if nothing has expired, expired elements come out in expiry order, and size() also counts the unexpired ones.

What to say in the interviewAbout 90 seconds aloud

Open with

DelayQueue is an unbounded BlockingQueue where each element becomes available only after its delay has passed. Inside, it keeps a PriorityQueue ordered by the elements' compareTo, guarded by one lock with a condition that consumers wait on.

Then, if they want more

The element class implements Delayed, which means getDelay with a TimeUnit and compareTo against other Delayed elements, and the two must be consistent, because the queue only ever looks at the head of the heap. If compareTo did not order by remaining delay, take could wait for a late element while an earlier one sits behind it.

I would store a fixed deadline at creation, System.nanoTime plus the delay, and have getDelay return the deadline minus the current nanoTime, converted to the requested unit.

Using nanoTime matters, because it is monotonic, while the wall clock from currentTimeMillis can jump when NTP adjusts it, which would release elements early or hold them too long. take blocks until the head's delay is zero or negative, then removes and returns it; poll without arguments returns null immediately if nothing has expired, and the timed poll waits up to a limit.

Elements come out in expiry order, not insertion order. One thing that surprises people is that size counts unexpired elements too, so a size of three does not mean three items are ready. And since it is unbounded and purely in memory, I keep it for work that can be lost on restart.

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 "How does DelayQueue work, and what must an element class implement?": https://scrivio-interview-library.netlify.app/java/queues-and-deques/11b089def0/