BackendBench
Coffee
Spot the Bug #36

The user who was still logged in

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

hardShared and static mutable statebuggy line: 6

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

What is wrong

In a thread pool the same thread serves many requests. The value stays in the ThreadLocal after the work ends, so a later request that does not set a user, or fails before setting it, sees the previous user's identity. It also keeps objects reachable and causes classloader leaks.

The fix

try { work.run(); } finally { USER.remove(); }

How to avoid it next time

Always remove ThreadLocal values in a finally block when threads are pooled, including servlet and executor threads.

Want the background? Read ThreadLocal and scoped values in the Java concepts library.

About shared and static mutable state

Static fields and singleton beans are shared by every request and thread. Mutable state kept there leaks data between users, makes tests order-dependent and creates race conditions that appear only under load.

In code review: Look for non-final static fields and instance fields in singleton beans that are written during a request. Prefer local variables, immutable objects and explicit synchronization.

More puzzles in this family

๐Ÿž Play today's puzzleAll 132 bugsโ† #35#37 โ†’

Frequently asked questions

What is the bug in "The user who was still logged in"?

In a thread pool the same thread serves many requests. The value stays in the ThreadLocal after the work ends, so a later request that does not set a user, or fails before setting it, sees the previous user's identity. It also keeps objects reachable and causes classloader leaks. The faulty line is line 6: work.run();

How do I fix it?

Replace it with: try { work.run(); } finally { USER.remove(); }. Always remove ThreadLocal values in a finally block when threads are pooled, including servlet and executor threads.

How do I catch shared and static mutable state in code review?

Look for non-final static fields and instance fields in singleton beans that are written during a request. Prefer local variables, immutable objects and explicit synchronization.

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