Scrivio Interview library
DebuggingFoundations6 min read · updated 12 November 2026

A worker loop uses

Java
while (true) {
Task t = queue.poll();
if (t != null) process(t);
}

on a LinkedBlockingQueue and the service uses 100 percent of a CPU core when idle. Fix it and explain shutdown handling.

poll() never waits: on an empty queue it returns null immediately, so while (true) { poll(); } turns into a busy loop that burns a whole core. Replace it with take(), which blocks until an element arrives, or with poll(timeout, unit). For shutdown, treat InterruptedException as the signal to stop and restore the interrupt flag, or use a poison pill or a volatile running flag with a timed poll; often an ExecutorService replaces the hand-written loop altogether.

Why this question is asked

A service that eats a full CPU core while doing nothing is a classic production surprise. It raises cloud bills, slows other processes on the same host and makes CPU-based autoscaling misbehave. Interviewers like this question because the fix is one word, but the follow-up, how the loop stops cleanly, separates people who have run such code in production from people who have only written it. In this answer, we will see why the loop spins, fix it with take(), handle interruption correctly, look at two other shutdown techniques, and see when an executor is the better tool.

1Why the Loop Spins

LinkedBlockingQueue offers two ways to take the head. poll() is the non-blocking one: it returns the head if there is one and null if the queue is empty, and it returns at once either way. take() is the blocking one: if the queue is empty, it parks the thread until another thread adds an element.

Our loop uses poll(). When the service is idle, the queue is empty, so poll() returns null, the if is false, and the loop goes straight back to poll(). That happens millions of times a second. The thread is never parked, so the operating system sees it as always runnable and gives it a full core.

Java
BlockingQueue<Task> queue = new LinkedBlockingQueue<>();
// broken: spins when idle
while (true) {
Task t = queue.poll(); // null immediately when empty
if (t != null) process(t); // skipped, loop again at once
}
// top shows the process at about 100% of one core with no work
Step throughOne pass of the broken loop when the queue is empty
  1. Call poll()does not wait
  2. Got a task?
    Yesprocess itNogo straight back to poll()
  3. Repeat millions of times a secondthe thread never sleeps

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

Nothing in the loop ever makes the thread wait, so idle time becomes CPU time.

2Fix: Block With take()

The fix is to use the method that waits. take() parks the thread inside the queue until an element arrives, and a parked thread uses no CPU at all.

Java
Runnable worker = () -> {
try {
while (true) {
Task t = queue.take(); // parks here while the queue is empty
process(t);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // keep the signal for whoever called us
// fall out of the loop: the worker stops
}
};
// idle CPU: about 0%

Notice that take() throws InterruptedException. That is not noise to swallow: interruption is how Java asks a blocked thread to stop. When someone calls thread.interrupt(), or an executor calls shutdownNow(), the waiting take() wakes up and throws. Our loop catches it outside the while, so the worker ends.

The reason we call Thread.currentThread().interrupt() in the catch block is that throwing InterruptedException clears the thread's interrupt flag. If code higher up checks the flag, for example an executor deciding whether the thread should keep running, it needs to see that an interrupt happened. Catching the exception and continuing the loop would be the worst choice: the thread could then never be stopped, and shutdown would hang.

3Fix With a Timeout: poll(timeout, unit)

Sometimes the worker has other duties, such as flushing a batch every few seconds or checking a flag. Then a timed poll is the right tool: it waits up to the limit and returns null if nothing arrived.

Java
private volatile boolean running = true;
void runWorker() throws InterruptedException {
while (running) {
Task t = queue.poll(500, TimeUnit.MILLISECONDS); // waits at most 500 ms
if (t != null) process(t);
flushIfDue(); // runs at least every 500 ms
}
}
void stop() { running = false; } // the worker notices within about 500 ms

The flag is volatile so that the write in stop(), made by another thread, is guaranteed to be seen by the worker thread. The timeout bounds how long the worker can take to notice: with 500 ms, shutdown takes at most about half a second. The loop now wakes twice a second when idle, which costs almost nothing, unlike the millions of iterations before.

4Clean Shutdown With a Poison Pill

A poison pill is a special element that means stop. The producer puts it at the end of the queue when it is done, and the worker exits when it takes it. The advantage over interruption is that every task submitted before the pill is processed first, so nothing in the queue is lost.

Java
static final Task POISON = new Task("POISON");
// worker
while (true) {
Task t = queue.take();
if (t == POISON) break; // compare by identity: only our exact object
process(t);
}
// shutdown, with 3 workers
for (int i = 0; i < 3; i++) queue.put(POISON); // one pill per worker

Notice that we need one pill per worker, because each worker consumes one pill and stops. We also compare with == because the pill must be our own sentinel object, never a real task that happens to be equal to it. Pills fit well when the queue must be drained; interruption fits when we must stop quickly and can abandon what is left.

5Should We Write This Loop at All?

Often the honest answer is no. An ExecutorService already contains a blocking work queue, worker threads that block on it correctly, and a shutdown protocol. Instead of a loop, we submit each task.

Java
ExecutorService pool = Executors.newFixedThreadPool(3);
pool.submit(() -> process(task)); // instead of queue.put(task)
// shutdown
pool.shutdown(); // no new tasks, finish queued ones
if (!pool.awaitTermination(10, TimeUnit.SECONDS)) {
pool.shutdownNow(); // interrupt the workers
}

shutdown() behaves like a poison pill, letting queued tasks finish, and shutdownNow() behaves like interruption. In Spring we would usually declare a ThreadPoolTaskExecutor bean, whose shutdown is tied to the application context. A hand-written loop is still reasonable when the worker must do batching or ordering that tasks cannot express, and then take() or a timed poll are the tools.

6Follow-up questions

Could we add Thread.sleep(10) after a null from poll() instead?

It reduces CPU use, but it is worse in both directions: it still wakes 100 times a second for nothing, and it adds up to 10 ms of latency to every task that arrives while the thread sleeps. take() wakes the thread exactly when an element arrives, with no wasted wake-ups and no added delay.

What happens if a worker catches InterruptedException inside the loop and continues?

The interrupt is consumed and the loop goes back to take(), so the thread can never be stopped by interruption. shutdownNow() then returns, but the threads keep running, and the JVM may not exit because those threads are not daemon threads. Always either exit or restore the flag and exit.

Does take() use a busy wait internally?

No. LinkedBlockingQueue waits on a Condition tied to its internal lock, which parks the thread through LockSupport. The thread is descheduled by the operating system until a put() signals the condition, so it uses no CPU while waiting.

7Conclusion

In this answer, we saw that poll() returns immediately on an empty queue, so a while (true) loop around it spins and uses a full core. take() fixes it by parking the thread until work arrives, and poll(timeout, unit) fixes it when the worker also has periodic duties. For shutdown, we treat InterruptedException as the stop signal and restore the flag, use a volatile flag with a timed poll, or send one poison pill per worker to drain the queue first. And in many services an ExecutorService replaces the loop with tested code.

What to say in the interviewAbout 90 seconds aloud

Open with

The loop spins because poll is non-blocking: on an empty LinkedBlockingQueue it returns null at once, the if is skipped, and we call poll again, millions of times a second, so the thread never parks and takes a full core.

Then, if they want more

The fix is to use take, which parks the thread until an element is available and uses no CPU while waiting. If the worker also needs to do something periodically, like flush a batch, I would use poll with a timeout, for example 500 milliseconds, instead.

For shutdown, take throws InterruptedException, and I treat that as the stop signal: I catch it outside the loop, call Thread.currentThread().interrupt() to restore the flag, and let the worker exit. I would never catch it and continue, because then the thread can't be stopped.

If I need the queue drained before stopping, I would put a poison pill, one per worker, and have each worker break when it takes it, compared by identity. Another clean option is a volatile running flag with a timed poll, which bounds how long the worker takes to notice.

Finally, I would ask whether we need the hand-written loop at all. An ExecutorService, or a ThreadPoolTaskExecutor in Spring, already has a blocking queue and workers that wait correctly, and shutdown and shutdownNow give us the drain and the interrupt behaviour for free.

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 "A worker loop uses": https://scrivio-interview-library.netlify.app/java/queues-and-deques/81df8f3218/