BackendBench
Coffee
Spot the Bug #55

A volatile counter that loses clicks

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

easyThreading and race conditionsbuggy line: 5

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

What is wrong

volatile guarantees visibility but not atomicity. hits++ is read, add, write, and two threads can both read the same value, so increments are lost. The total under load is lower than the real number of calls.

The fix

private final java.util.concurrent.atomic.AtomicInteger hits = new java.util.concurrent.atomic.AtomicInteger(); public void record() { hits.incrementAndGet(); }

How to avoid it next time

Use AtomicInteger or LongAdder for counters, not volatile.

Want the background? Read volatile and atomic classes 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โ† #54#56 โ†’

Frequently asked questions

What is the bug in "A volatile counter that loses clicks"?

volatile guarantees visibility but not atomicity. hits++ is read, add, write, and two threads can both read the same value, so increments are lost. The total under load is lower than the real number of calls. The faulty line is line 5: hits++;

How do I fix it?

Replace it with: private final java.util.concurrent.atomic.AtomicInteger hits = new java.util.concurrent.atomic.AtomicInteger(); public void record() { hits.incrementAndGet(); }. Use AtomicInteger or LongAdder for counters, not volatile.

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