BackendBench
Coffee
Spot the Bug #57

Double-checked locking without volatile

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

hardThreading and race conditionsbuggy line: 2

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

What is wrong

Without volatile, another thread can see a non-null reference to an object whose fields are not yet visible, because the write of the reference may be reordered with the constructor. The consumer then uses a half-constructed Registry.

The fix

private static volatile Registry instance;

How to avoid it next time

Declare the field volatile, or use the initialization-on-demand holder idiom or an enum singleton.

Want the background? Read Singleton pattern 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← #56#58 →

Frequently asked questions

What is the bug in "Double-checked locking without volatile"?

Without volatile, another thread can see a non-null reference to an object whose fields are not yet visible, because the write of the reference may be reordered with the constructor. The consumer then uses a half-constructed Registry. The faulty line is line 2: private static Registry instance;

How do I fix it?

Replace it with: private static volatile Registry instance;. Declare the field volatile, or use the initialization-on-demand holder idiom or an enum singleton.

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