Fundamentals 20 min read

Why a Simple Singleton Answer Failed an Alibaba Interview: The Real Role of volatile, Memory Barriers, and Happens‑Before

The article dissects an Alibaba interview question about the volatile modifier, showing why answering only with a lazy‑loaded singleton is insufficient, and explains how volatile prevents instruction reordering, establishes memory barriers, and creates happens‑before relationships to make double‑checked locking safe.

Tech Freedom Circle
Tech Freedom Circle
Tech Freedom Circle
Why a Simple Singleton Answer Failed an Alibaba Interview: The Real Role of volatile, Memory Barriers, and Happens‑Before

Interview Question Overview

An interviewee was asked three related questions: (1) practical uses of the volatile modifier, (2) the underlying principle of the happens‑before rule, and (3) how volatile achieves visibility and ordering.

Problem with a Naïve Answer

Answering only with the classic double‑checked locking (DCL) singleton without mentioning memory barriers or happens‑before leads to interview failure because the candidate does not demonstrate understanding of the JVM memory model.

Why volatile Is Required

Without volatile : DCL is not thread‑safe; instruction reordering can produce a half‑initialized object.

With volatile : The write to the instance field is a memory barrier, preventing other threads from reading the reference before the object is fully constructed.

Object Creation Is Not Atomic

The statement instance = new Singleton7(); is split into three CPU instructions:

Allocate memory.

Initialize the object (run the constructor).

Assign the reference to instance.

The JVM may reorder them to 1 → 3 → 2, causing another thread to see a non‑null reference to an incompletely initialized object.

Failure Scenario Without volatile

Thread A executes new Singleton() and the JVM reorders to allocate memory and assign the reference before initialization.

Thread B sees instance != null and returns the half‑initialized object.

Thread B then uses the object, leading to NullPointerException or corrupted state.

Although the probability is low, the bug is extremely hard to reproduce in production.

What volatile Actually Does

Prevents instruction reordering : Guarantees the order 1 → 2 → 3 for object creation.

Introduces memory barriers :

Write barrier (StoreStore + StoreLoad) ensures all normal writes become visible before the volatile write.

Read barrier (LoadLoad + LoadStore) forces a volatile read to see the latest value before any subsequent reads.

These barriers establish a happens‑before relationship: a write to a volatile variable happens‑before any later read of that variable.

Code Example

public class Singleton7 {
    // Must be volatile to prevent reordering
    private static volatile Singleton7 instance = null;
    private Singleton7() {}
    public static Singleton7 getInstance() {
        if (instance == null) { // first check, no lock
            synchronized (Singleton7.class) {
                if (instance == null) { // second check
                    instance = new Singleton7();
                }
            }
        }
        return instance;
    }
}

Key Points of the Implementation

Double‑checked if provides high concurrency performance (no lock on the fast path). synchronized guarantees atomic creation of the instance. volatile eliminates the reordering bug, making DCL safe on JDK 1.5+.

JDK Version Requirement

The fix relies on the JMM changes introduced in JDK 1.5 (JSR‑133), which gave volatile proper memory‑semantic guarantees.

Limitations

volatile

does not replace locks; it only provides visibility and ordering. It cannot guarantee atomicity of compound actions.

Conclusion

In modern Java (JDK 1.5+), the only correct way to implement a lazy‑loaded, thread‑safe singleton with double‑checked locking is to combine volatile, a class‑level lock ( synchronized), and the double‑check pattern. Understanding the underlying memory barriers and happens‑before rule is essential for any concurrency interview.

JavaconcurrencyvolatileJMMhappens-beforememory barrierdouble-checked locking
Tech Freedom Circle
Written by

Tech Freedom Circle

Crazy Maker Circle (Tech Freedom Architecture Circle): a community of tech enthusiasts, experts, and high‑performance fans. Many top‑level masters, architects, and hobbyists have achieved tech freedom; another wave of go‑getters are hustling hard toward tech freedom.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.