Scrivio Interview library
DebuggingIntermediate6 min read · updated 12 November 2026

A consumer thread runs

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

over a ConcurrentLinkedQueue. The service burns a full CPU core even when idle. Explain and fix.

ConcurrentLinkedQueue.poll never waits: on an empty queue it returns null immediately, so the loop goes straight back to poll again, millions of times per second, and keeps one core at 100 percent even with no work. The fix is to let the thread sleep while there is nothing to do: switch to a BlockingQueue and call take(), or poll with a timeout so the loop can still check its stop flag. If the non-blocking queue must stay, add a back-off such as LockSupport.parkNanos when the queue is empty, accepting a little extra latency. The running flag must also be volatile so the stop signal is seen, and idle CPU should be measured after the change.

Why this question is asked

A consumer loop like this is often the first thing written when someone needs a background worker, and it works: tasks are processed, tests pass. Then someone looks at the dashboards and sees a service with no traffic sitting at a full core, multiplied across every instance, adding real cost and heat to the fleet. Interviewers ask this because it tests whether we understand the difference between non-blocking and blocking APIs, and because the loop hides a second bug about visibility. In this answer, we will recap what poll does on an empty queue, reproduce the spin, fix it with a blocking queue, show the back-off option, fix the stop flag, and verify the result.

1A Quick Recap: Non-Blocking Means It Never Waits

ConcurrentLinkedQueue is a lock-free queue. Its methods never put the calling thread to sleep: offer always succeeds immediately, and poll either returns the head element or returns null right away if the queue is empty. That is a feature when the caller has other things to do and only wants to check for work.

But a thread whose only job is to consume the queue has nothing else to do. If it calls poll in a loop, then every time the queue is empty it learns nothing, does nothing, and asks again. The CPU never gets a chance to run other threads or drop into a low-power state.

2Reproducing the Spin

Here is the consumer from the question with no producer at all.

Java
Queue<Task> queue = new ConcurrentLinkedQueue<>();
boolean running = true; // bug 2: not volatile
void consume() {
while (running) {
Task t = queue.poll(); // empty: returns null in nanoseconds
if (t != null) t.run(); // skipped
} // loops again at once: tens of millions of polls per second
}
// top -H: one thread at ~100% CPU; the service is otherwise idle
Step throughThe spinning loop
  1. running?
    Yespoll the queueNoexit
  2. poll returned a task?
    Yesrun it, loopNoloop immediately

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

With an empty queue, the no branch repeats at full speed forever.

Each iteration takes a few nanoseconds, so the thread executes tens of millions of empty polls per second. The operating system sees a thread that is always runnable and always using its time slice, so it reports a full core in use. With several consumer threads, the service burns several cores while idle. In a container with a CPU limit, those spinning threads also eat the quota that real request threads need, which can raise latency for everything else.

3Fix 1: A BlockingQueue With take or a Timed poll

A BlockingQueue, such as LinkedBlockingQueue, can make the consumer wait. take() parks the thread inside the queue until a producer adds an element, and the producer's offer wakes it. A parked thread uses no CPU at all. Because a thread waiting in take would never look at the running flag, we use poll with a timeout, which waits up to the given time and then returns null, so the loop can check the flag regularly.

Java
private final BlockingQueue<Task> queue = new LinkedBlockingQueue<>(10_000);
private volatile boolean running = true;
void consume() {
while (running) {
try {
Task t = queue.poll(500, TimeUnit.MILLISECONDS); // sleeps until work or 500 ms
if (t != null) t.run();
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // restore the flag and stop
return;
}
}
}
void stop() { running = false; } // the consumer exits within 500 ms
// idle CPU of this thread: ~0%

Latency for new work stays excellent, because offer wakes the waiting consumer immediately; the timeout only limits how long shutdown can take. An alternative to the flag is to call take() and stop the consumer with thread.interrupt(), or by putting a special poison-pill task into the queue that tells the loop to exit. With an executor, simply calling shutdownNow() does the interrupting for us.

4Fix 2: Keep the Queue, Add a Back-off

Sometimes the non-blocking queue is there for a reason, for example producers that must never touch a lock. Then the consumer can back off when it finds nothing: spin a little, then yield, then park for a short time.

Java
void consume() {
int idle = 0;
while (running) {
Task t = queue.poll();
if (t != null) { t.run(); idle = 0; continue; }
if (++idle < 100) Thread.onSpinWait(); // brief spin for bursts
else LockSupport.parkNanos(100_000); // then sleep 0.1 ms per empty poll
}
}
// idle CPU drops to a few percent; a new task waits up to ~0.1 ms longer

The trade-off is explicit. A longer park uses less CPU but adds latency, because a task added while the consumer sleeps waits until the park ends. A few hundred microseconds is a common compromise, and it should be chosen from the latency the work needs, not guessed.

5Making the Stop Flag Visible

The original loop has a second bug that is easy to miss. running is a plain boolean, and the Java memory model allows the JIT compiler to read it once and reuse the value, effectively turning the loop into while (true), because nothing in the loop body forces it to reread the field. A tight loop like this one is exactly where that happens in practice, so stop() may never stop the thread.

Declaring the field volatile fixes it: every read of a volatile field sees the latest write by any thread. An AtomicBoolean or interrupting the thread also work. After both changes, we verify on a staging instance with no traffic: per-thread CPU from top -H or a JFR recording should show the consumer thread near zero while idle, and a shutdown test should confirm the consumer exits within the expected time.

6Follow-up questions

Would Thread.yield() inside the loop be enough?

It reduces the damage when other threads want to run, but on an idle machine yield returns immediately and the loop still spins at nearly full CPU. It is a hint, not a sleep. Blocking or parking is what actually releases the core.

Why not just Thread.sleep(1) when the queue is empty?

It works and is a simple form of back-off, but it adds up to a millisecond or more of latency to every task that arrives during the sleep, and sleep granularity depends on the operating system. A blocking queue gives both zero idle CPU and immediate wake-up, so it is the better default.

When is busy spinning actually the right choice?

In ultra-low-latency systems, such as trading engines, that dedicate a core to a thread and cannot afford even microseconds of wake-up delay. There it is a deliberate decision with pinned cores and Thread.onSpinWait, not an accident in a general-purpose service.

7Conclusion

In this answer, we saw that the consumer burns a core because ConcurrentLinkedQueue.poll returns null immediately on an empty queue, so the loop spins continuously. We fixed it with a BlockingQueue, using take or a timed poll so the thread sleeps until work arrives, and showed a back-off with LockSupport.parkNanos for cases where the non-blocking queue must stay, at the cost of some latency. We also made the running flag volatile so the stop signal is seen, and verified idle CPU and shutdown behaviour after the change.

What to say in the interviewAbout 90 seconds aloud

Open with

The loop is a busy spin. ConcurrentLinkedQueue is non-blocking, so when it's empty, poll returns null immediately, and the loop goes straight back and polls again, tens of millions of times a second.

Then, if they want more

The thread never sleeps, so the OS sees it using a full core even though there's no work. I'd fix it by making the consumer wait.

The cleanest way is to switch to a BlockingQueue like a bounded LinkedBlockingQueue and use take, which parks the thread until a producer adds something, or poll with a timeout of, say, 500 milliseconds so the loop can still check its stop flag regularly. Producers wake the consumer immediately, so latency doesn't suffer, and idle CPU goes to roughly zero.

If for some reason we must keep the non-blocking queue, I'd add a back-off: spin briefly with onSpinWait, then LockSupport.parkNanos for something like a hundred microseconds when the queue stays empty. That cuts CPU a lot but adds up to that much latency to new tasks, so it's a trade-off to choose deliberately.

There's also a second bug: running isn't volatile, so the JIT can hoist the read out of the loop and the thread might never see the stop signal. I'd make it volatile, or use interruption. Finally, I'd measure: check per-thread CPU with top -H or JFR on an idle instance, and test that shutdown actually stops the consumer.

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 consumer thread runs": https://scrivio-interview-library.netlify.app/java/concurrent-collections/b2c04f9c99/