BackendBench
Coffee
Spot the Bug #56

Two threads, one key, two values

A medium Java puzzle in the threading and race conditions family. One line below contains a real bug. Try to spot it first, then read why it fails and how to fix it.

mediumThreading and race conditionsbuggy line: 7

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

What is wrong

Each method of ConcurrentHashMap is thread-safe, but the sequence is not atomic. Two threads can both see the key missing and both put, so different callers receive different session objects and one is lost.

The fix

return sessions.computeIfAbsent(id, Session::new);

How to avoid it next time

Use atomic operations such as computeIfAbsent, putIfAbsent and merge instead of check-then-act sequences.

Want the background? Read Concurrent collections in the Java concepts library.

About threading and race conditions

Without synchronization, threads can see stale values and interleave read-modify-write sequences. A volatile field gives visibility but not atomicity, and check-then-act sequences are never atomic by themselves.

In code review: For every shared variable ask who writes it, who reads it, and what protects it. Prefer atomic classes, concurrent collections and immutable objects.

More puzzles in this family

๐Ÿž Play today's puzzleAll 132 bugsโ† #55#57 โ†’

Frequently asked questions

What is the bug in "Two threads, one key, two values"?

Each method of ConcurrentHashMap is thread-safe, but the sequence is not atomic. Two threads can both see the key missing and both put, so different callers receive different session objects and one is lost. The faulty line is line 7: if (!sessions.containsKey(id)) {

How do I fix it?

Replace it with: return sessions.computeIfAbsent(id, Session::new);. Use atomic operations such as computeIfAbsent, putIfAbsent and merge instead of check-then-act sequences.

How do I catch threading and race conditions in code review?

For every shared variable ask who writes it, who reads it, and what protects it. Prefer atomic classes, concurrent collections and immutable objects.

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