Skip to content

Try “polymorphism”, “TCP handshake” or “git rebase”.

    Java / Concurrency

    The Java Memory Model: Visibility and volatile

    For speed, each core has its own caches and registers (01howcomputerswork.md Ch 5–6), and both the JIT compiler and the CPU may

    Chapter 4 of 127 min readOften asked in interviews

    The Plain Picture#

    Two colleagues each keep a personal notepad copy of the office whiteboard, because walking to the whiteboard is slow. You update the whiteboard: "MEETING CANCELLED". Your colleague keeps reading their notepad, which still says the meeting is on — and turns up to an empty room. Nothing forces them to look at the whiteboard again.

    The Real Names#

    • For speed, each core has its own caches and registers (How Computers Work Ch 5–6), and both the JIT compiler and the CPU may reorder instructions or keep a variable in a register instead of re-reading memory — as long as a single thread can't tell the difference.

    • So without synchronization, one thread's write may never become visible to another thread, or may become visible in a surprising order. This is the visibility problem.

    • The Java Memory Model (JMM) is the set of rules saying when a write by one thread is guaranteed to be seen by another. Its key idea is happens-before: if action A happens-before action B, then B sees everything A did.

    • Main happens-before rules:

      • releasing a lock happens-before the next acquisition of that lock (synchronized, Lock);

      • a write to a volatile variable happens-before every later read of that variable;

      • thread.start() happens-before anything the new thread does; everything a thread does happens-before another thread's join() on it returns;

      • putting an object into a concurrent collection happens-before taking it out (Ch 7–8).

    • volatile marks a field whose reads and writes always go to main memory in order, and can't be cached away or reordered around.

    Under the Hood — the invisible flag, for real#

    Java
    static boolean running = true; // plain field
    
    static volatile boolean vRunning = true; // volatile field
    
    Thread spinner = new Thread(() -> {
        long n = 0;
        while (running) {
            n++;
        }
        System.out.println("plain flag: loop stopped");
    });
    
    spinner.setDaemon(true);
    
    spinner.start();
    
    Thread.sleep(200);
    
    running = false;
    
    spinner.join(1000);
    
    // plain flag: thread still running after 1s? true        ← it NEVER stopped
    
    Thread vs = new Thread(() -> {
        long n = 0;
        while (vRunning) {
            n++;
        }
        System.out.println("volatile flag: loop stopped");
    });
    
    vs.start();
    
    Thread.sleep(200);
    
    vRunning = false;
    
    vs.join(1000);
    // volatile flag: loop stopped
    // volatile flag: still running? false

    The main thread set running = false, yet the spinning thread looped forever. The JIT saw that the loop never writes running, so it read it once and turned the loop into while (true) — perfectly legal under the JMM, because nothing established happens-before. Adding volatile (or reading the flag under a lock) forbids that, and the loop stops.

    This bug is real and common: "stop" flags, "is initialised" flags, config reloaded by one thread and read by others.

    volatile is not atomic#

    Java
    volatile int count;
    
    count++; // STILL a race: read, add, write are three steps (02_operating_systems.md Ch 8)

    volatile gives visibility and ordering, not mutual exclusion. Use it for a single write, many readers situation — a flag, a reference to an immutable config object. For read-modify-write, use a lock or an atomic (Ch 5).

    volatilesynchronized / LockAtomicInteger etc.
    Visibility✅✅✅
    Mutual exclusion❌✅— (single-variable atomic ops)
    Safe for count++❌✅✅
    Can block threadsnoyesno (spins/retries)
    Typical usestop flags, publishing a referencemulti-step invariantscounters, single-value updates

    Double-checked locking — a famous case that needs volatile#

    Java
    class AiClient {
        private static volatile AiClient instance; // volatile is REQUIRED
    
        static AiClient get() {
            if (instance == null) {
                // 1st check: no lock (fast path)
                synchronized (AiClient.class) {
                    if (instance == null) {
                        // 2nd check: under the lock
                        instance = new AiClient();
                    }
                }
            }
            return instance;
        }
    }

    Without volatile, the write of the reference could be reordered before the constructor finishes, so another thread could see a non-null but half-built object. (Simpler, equally lazy and safe alternatives: an enum singleton, or a static nested "holder" class — Creational Patterns (coming soon).)

    Check yourself

    5 questions
    1

    Why did the plain-flag loop never stop?

    Show answer

    With no happens-before relation, the JIT was allowed to read the flag once and loop forever; the write was never guaranteed to be seen.

    2

    What does "happens-before" mean? Name three rules.

    Show answer

    If A happens-before B, B sees A's effects. Rules: unlock → later lock of the same monitor; volatile write → later read; start() → the thread's actions; thread's actions → join() returning.

    3

    Is volatile int count; count++; thread-safe? Why?

    Show answer

    No — count++ is read-modify-write; volatile gives visibility, not atomicity.

    4

    When is volatile the right tool?

    Show answer

    One writer (or independent writes) and many readers of a single variable, like a stop flag or publishing an immutable object.

    5

    Why does double-checked locking need volatile?

    Show answer

    Without it, another thread can see the reference before the object's construction has completed (reordering).