BackendBench
Coffee
Spot the Bug #32

The customer who saw someone else's data

A easy 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.

easyShared and static mutable statebuggy line: 5

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

What is wrong

A Spring @Service is a singleton shared by every request thread. The instance field is overwritten by each caller, so under concurrency one request can read the customer name that another request just stored. The bug shows up only with parallel traffic.

The fix

public String render(String customer) { return "Invoice for " + customer; }

How to avoid it next time

Keep singleton beans stateless. Pass data through parameters and local variables.

Want the background? Read Spring beans and dependency injection 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โ† #31#33 โ†’

Frequently asked questions

What is the bug in "The customer who saw someone else's data"?

A Spring @Service is a singleton shared by every request thread. The instance field is overwritten by each caller, so under concurrency one request can read the customer name that another request just stored. The bug shows up only with parallel traffic. The faulty line is line 5: private String currentCustomer;

How do I fix it?

Replace it with: public String render(String customer) { return "Invoice for " + customer; }. Keep singleton beans stateless. Pass data through parameters and local variables.

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