BackendBench
Coffee
Spot the Bug #41

The worker that cannot be stopped

A hard Java puzzle in the exception handling mistakes family. One line below contains a real bug. Try to spot it first, then read why it fails and how to fix it.

hardException handling mistakesbuggy line: 7

Highlighted: line 7. Play this one as a puzzle without the answer.

What is wrong

When a thread is interrupted during sleep, the interrupted flag is cleared and InterruptedException is thrown. Ignoring it means the loop condition sees a clear flag and keeps running, so shutdown requests are lost and the pool never terminates.

The fix

} catch (InterruptedException e) { Thread.currentThread().interrupt(); return; }

How to avoid it next time

On InterruptedException either rethrow it or restore the flag with Thread.currentThread().interrupt() and stop work.

Want the background? Read Interruption and InterruptedException in the Java concepts library.

About exception handling mistakes

Swallowed exceptions, lost causes and returns in finally blocks hide failures until the data is already wrong. The program keeps running and nobody knows why the result is missing.

In code review: An empty catch block, a catch that only prints, or an exception rethrown without its cause are all red flags. Log with the exception object and rethrow or handle meaningfully.

More puzzles in this family

๐Ÿž Play today's puzzleAll 132 bugsโ† #40#42 โ†’

Frequently asked questions

What is the bug in "The worker that cannot be stopped"?

When a thread is interrupted during sleep, the interrupted flag is cleared and InterruptedException is thrown. Ignoring it means the loop condition sees a clear flag and keeps running, so shutdown requests are lost and the pool never terminates. The faulty line is line 7: } catch (InterruptedException e) {

How do I fix it?

Replace it with: } catch (InterruptedException e) { Thread.currentThread().interrupt(); return; }. On InterruptedException either rethrow it or restore the flag with Thread.currentThread().interrupt() and stop work.

How do I catch exception handling mistakes in code review?

An empty catch block, a catch that only prints, or an exception rethrown without its cause are all red flags. Log with the exception object and rethrow or handle meaningfully.

Is there a new puzzle every day?

Yes. The daily Spot the Bug puzzle picks one of these snippets for each UTC day, with the difficulty set by the weekday. Your streak is stored only in your browser.

More tools you might need