Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

What is wrong with this code and how would you fix it?

Java
while (true) {
try {
Task t = queue.take();
handle(t);
} catch (InterruptedException e) {
log.warn("interrupted");
}
}

The catch block logs the InterruptedException and goes round the loop again. Since throwing InterruptedException cleared the interrupt status, the next take() blocks as if nothing happened, so the thread can never be stopped by interruption and shutdownNow() on its executor will not end it. The fix is to restore the flag with Thread.currentThread().interrupt() and leave the loop, or to declare throws InterruptedException and let the caller decide. Swallowing interruption is only acceptable when we own the thread and deliberately end its work.

Why this question is asked

Consumer loops like this one are everywhere: workers reading from a queue, listeners polling a source, background processors. When the loop swallows interruption, the application cannot shut down cleanly, deploys wait for timeouts, and tests hang. Interviewers show this code because the bug is invisible unless we know what InterruptedException does to the interrupt status. In this answer, we will recap interruption, show exactly how the loop defeats it, prove that shutdownNow() fails, and then write two correct versions and discuss when swallowing is acceptable.

1A Quick Recap of Interruption

Each thread has an interrupt status, a boolean flag. Calling interrupt() on a thread sets its flag; it does not stop the thread. Blocking methods such as BlockingQueue.take() check the flag: if it is set, or becomes set while they wait, they clear it and throw InterruptedException. The idea is that the code catching the exception reacts to the request, usually by stopping. This is called cooperative cancellation, because the interrupted code must cooperate for anything to happen.

2What Goes Wrong in This Loop

Let us follow one interruption through the code. The worker is blocked in queue.take() because the queue is empty. Another thread calls interrupt() on it. take() wakes up, clears the interrupt status and throws InterruptedException. The catch block logs interrupted. The while (true) loop continues, and the worker calls take() again. The flag is now false, so take() blocks normally, waiting for the next task.

So the request to stop was received, logged and then thrown away. Nothing records that it ever happened. Interrupt the thread a hundred times and we get a hundred log lines and a thread that is still running. The loop has no other exit condition, so interruption was its only way to end, and that way is now closed.

Java
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.submit(() -> {
while (true) {
try {
Task t = queue.take();
handle(t);
} catch (InterruptedException e) {
log.warn("interrupted"); // flag already cleared; the loop goes on
}
}
});
executor.shutdownNow(); // interrupts the worker
System.out.println(executor.awaitTermination(10, TimeUnit.SECONDS)); // false
// log: WARN interrupted
// The worker is back in take(); the JVM cannot exit because the pool thread is non-daemon
Step throughOne interruption through the broken loop
  1. Worker blocked in take()queue is empty
  2. shutdownNow() calls interrupt()flag = true
  3. take() throws InterruptedExceptionflag cleared to false
  4. catch logs a warningno flag restored, no exit
  5. while (true) calls take() againblocks normally; stop request lost

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

Notice that shutdownNow() did its job, which is only to interrupt the worker. awaitTermination() returns false because the task never finishes. In a Spring application the same happens when the context closes: the executor's shutdown waits, times out and gives up, and in a plain Java program the non-daemon pool thread keeps the JVM alive.

3Fix 1: Restore the Flag and Exit the Loop

When our code cannot declare the checked exception, for example because it is inside a Runnable, the correct reaction is to restore the interrupt status and leave. Restoring it with Thread.currentThread().interrupt() matters because the code that called us, such as the executor's worker loop, also looks at the flag.

Java
Runnable consumer = () -> {
while (!Thread.currentThread().isInterrupted()) {
try {
Task t = queue.take();
handle(t);
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // keep the signal for whoever runs us
log.info("consumer stopping");
return; // and actually stop
}
}
};
executor.submit(consumer);
executor.shutdownNow();
System.out.println(executor.awaitTermination(10, TimeUnit.SECONDS)); // true

The loop condition also checks isInterrupted(), which covers the case where the interruption arrives while handle(t) is running and handle() does not block. Without that check, the thread would only notice at the next take(), which is still fine here because take() throws at once if the flag is already set.

4Fix 2: Declare throws InterruptedException

If the loop lives in a method we control, the simplest correct code does not catch the exception at all. It declares it, and the caller, who knows the context, decides what to do. With a Callable this works directly, because call() may throw any exception.

Java
void consume() throws InterruptedException {
while (true) {
Task t = queue.take(); // InterruptedException propagates and ends the loop
handle(t);
}
}
Future<?> f = executor.submit(() -> { consume(); return null; }); // a Callable, so it may throw
f.cancel(true); // interrupts the worker; consume() exits by exception

Notice that this version has no try/catch at all, which is often the strongest sign that interruption is handled correctly: the signal flows upward without being touched.

5Handling Failures of handle() Separately

The original code may have caught InterruptedException because the loop must survive bad tasks. That is a real need, but it is a different exception. We catch runtime failures from handle() inside the loop and keep going, and we treat interruption as the stop signal.

Java
while (!Thread.currentThread().isInterrupted()) {
Task t;
try {
t = queue.take();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return; // stop request: leave
}
try {
handle(t);
} catch (RuntimeException e) {
log.error("Task {} failed", t.id(), e); // bad task: log and continue
}
}

So one bad task cannot kill the consumer, and one shutdown request always does.

6When Swallowing Is Acceptable

There is one legitimate case for catching InterruptedException without restoring the flag: when our code owns the thread and the interruption means end your work, and we act on that by ending it. For example, the run() method of a dedicated thread we created ourselves may catch it, close its resources and return, because there is no caller above it to inform. The original code fails even this test, because it neither restores the flag nor ends the work. Code that runs inside an executor never owns the thread, so it should always restore or propagate.

7Follow-up questions

Why not just use a volatile boolean running flag instead?

We can, and it is useful for a clean, explicit stop. But a boolean flag does not wake a thread blocked in take(), so the worker would only notice after the next task arrives, which may be never. Interruption both sets a flag and wakes blocked calls, so a robust worker responds to both, or uses poll() with a timeout and checks its flag between polls.

What happens if handle() itself catches and swallows InterruptedException?

The same bug moves one level down. When handle() is running and the interrupt arrives during one of its blocking calls, it clears the flag, and the loop's isInterrupted() check sees false. Every layer must restore or propagate, which is why the rule applies to all code, not only to the loop.

How would you test that the loop stops?

Start it on an executor, call shutdownNow(), and assert that awaitTermination() returns true within a second. Test both cases: the worker blocked in take() and the worker in the middle of handle().

8Conclusion

In this answer, we saw that catching InterruptedException clears the interrupt status, so a loop that logs it and continues can never be stopped, and shutdownNow() followed by awaitTermination() times out. We fixed it by restoring the flag with Thread.currentThread().interrupt() and returning, or by declaring throws InterruptedException and letting it propagate, and we separated the handling of task failures from the handling of the stop signal. Swallowing interruption is only acceptable in code that owns the thread and ends its work.

What to say in the interviewAbout 80 seconds aloud

Open with

The problem is in the catch block. When the thread is interrupted while blocked in take, take clears the interrupt status and throws InterruptedException. This code logs it and the while true loop calls take again, and because the flag is now false, take just blocks waiting for the next task.

Then, if they want more

So the stop request is received and thrown away, and the loop has no other way to end. In practice that means shutdownNow on the executor running it won't stop it: shutdownNow only interrupts the worker, awaitTermination returns false, and since pool threads are non-daemon, a plain Java process may never exit. The fix depends on where the code lives.

Inside a Runnable, I catch InterruptedException, call Thread.currentThread().interrupt() to restore the flag for whoever runs me, and return out of the loop. I'd also make the loop condition check isInterrupted. If it's a method I control, the cleaner fix is to declare throws InterruptedException and not catch it at all, so the caller decides.

If the original intent was to survive bad tasks, I'd catch RuntimeException around handle separately, log it and continue. The only time it's fine to swallow interruption is when my code owns the thread and the interruption means end the work, and I do end 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 "What is wrong with this code and how would you fix it?": https://scrivio-interview-library.netlify.app/java/threads/262fdb35d7/