BackendBench
Coffee
Spot the Bug #35

The cache that never forgets

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

mediumShared and static mutable statebuggy line: 4

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

What is wrong

Entries are added for every user and never removed, so memory grows until the JVM throws OutOfMemoryError. A plain HashMap is also not safe for concurrent access. A cache needs a size limit or expiry policy.

The fix

private static final Cache<String, byte[]> CACHE = Caffeine.newBuilder().maximumSize(10_000).expireAfterWrite(Duration.ofMinutes(30)).build();

How to avoid it next time

Use a real cache with eviction (Caffeine, Spring Cache) instead of a static map.

Want the background? Read In-memory caches (Caffeine, Guava, Ehcache) 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โ† #34#36 โ†’

Frequently asked questions

What is the bug in "The cache that never forgets"?

Entries are added for every user and never removed, so memory grows until the JVM throws OutOfMemoryError. A plain HashMap is also not safe for concurrent access. A cache needs a size limit or expiry policy. The faulty line is line 4: private static final Map CACHE = new HashMap<>();

How do I fix it?

Replace it with: private static final Cache CACHE = Caffeine.newBuilder().maximumSize(10_000).expireAfterWrite(Duration.ofMinutes(30)).build();. Use a real cache with eviction (Caffeine, Spring Cache) instead of a static map.

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