Threads ·
‹ Previous Next ›
⏱ 5 min read Modified: 2026-11-24

volatile in Java: Java Memory Model and happens-before

volatile in Java is a field modifier that guarantees two things: a write to the field becomes visible to every thread that reads it afterwards, and the compiler, the JIT and the CPU don't move ordinary reads and writes across a volatile access. What the Java volatile keyword does not give you is mutual exclusion or atomicity of compound operations: reading and writing a volatile variable are atomic (including long and double), but count++ is not.

private volatile boolean running = true; // one thread writes, others read

public void stop() {
    running = false;  // the write becomes visible to the thread checking the flag
}

Without volatile, a flag like this may not work at all. A thread spins in while (running), the main thread writes false a second later, and the loop keeps going forever: no exception, no compiler warning. Even Thread.sleep(1000) inside the loop guarantees nothing, because JLS §17.3 explicitly lets the compiler read such a field only once. The breakdown is in The Visibility Problem.

The Visibility Problem: A Stop Flag Without volatile

The visibility problem is when one thread writes a new value to a shared field and another thread keeps reading the old one, because nothing synchronizes the two. The classic example is a stop flag: without volatile, the worker thread is allowed to never see running = false.

The typical use of volatile is exactly that: a stop flag written by one thread and read by another.

public class StopFlag {
    private static volatile boolean running = true;

    public static void main(String[] args) throws InterruptedException {
        Thread worker = new Thread(() -> {
            long n = 0;
            while (running) {
                n++;
            }
            System.out.println("Stopped, iterations: " + n);
        });
        worker.start();
        Thread.sleep(1000);
        running = false;
        worker.join();
    }
}
Stopped, iterations: 1873455620

The iteration count differs on every run, but the program finishes after about a second.

Remove volatile, and on HotSpot the program often never finishes: the JIT sees that running doesn't change inside the loop and reads it once. In effect the loop becomes if (running) { while (true) n++; }. To be clear, that isn't the only possible outcome. While the method still runs in the interpreter, the field is re-read on every iteration, and the program may stop; the same goes for another JVM or different launch flags. The JMM simply promises nothing here, and a program that "sometimes hangs" is worse than one that always does.

Here's a less obvious case. Add System.out.println(n) to the loop without volatile, and the program will most likely stop. There's a lock inside println, and the JIT doesn't hoist the field read out past it. But that's a property of the implementation, not a guarantee: the main thread never enters that monitor, so there's no happens-before between the write and the read. Remove the debug output and the hang is back. In code review, a "bug that disappears when you add logging" almost always turns out to be a missing volatile.

Why a Thread Doesn't See Another Thread's Write

A thread can miss another thread's write for three reasons: the JIT keeps the field's value in a CPU register instead of re-reading memory, a CPU write first lands in that core's store buffer and cache, and the compiler, JIT and CPU reorder independent operations for speed. Inside one thread none of this is noticeable; from another thread it is.

Let's go through the layers from the top down.

The JIT compiler. Single-threaded reasoning lets it conclude: "nobody writes running in this loop, so I can read it once." It's the same optimization that hoists array.length out of a loop, and it's exactly what breaks StopFlag without volatile.

The CPU. Each core has its own caches and a store buffer. A written value sits in the core's buffer for a while and isn't visible to other cores. Hardware cache coherence doesn't save you: it kicks in once the write has reached the cache, and without memory barriers neither the moment that happens nor the order in which other cores see different writes is defined.

Reordering. If two operations don't depend on each other within a thread, they can run in either order. What does this code print if t1 and t2 start at the same time?

static int x = 0, y = 0;
static int r1, r2;

// thread t1         // thread t2
x = 1;               y = 1;
r1 = y;              r2 = x;

Intuition says at least one thread must read a 1. Yet r1 = 0, r2 = 0 is a legal outcome: each thread read the other variable before its own write became visible to the other core. Stress tests reproduce it on ordinary x86 processors. Declare x and y volatile, and 0, 0 is ruled out: all volatile operations in the program fall into a single total order that is consistent with each thread's program order.

Older textbooks and tutorials explain this through a thread's "working memory" and "main memory". That's an abstraction from the first edition of the Java specification, not a description of real hardware: a thread has no separate copy of all variables. The current memory model describes rules rather than mechanisms, namely which writes a read is allowed to see.

The Java Memory Model (JMM)

The Java Memory Model (JMM) is the part of the language specification (JLS, chapter 17) that defines which values a read of a shared variable may return in a multithreaded program. Its central concept is the happens-before relation: if action A happens-before action B, then B is guaranteed to see the results of A.

The current model arrived in Java 5 with JSR-133. Before that, the specification contradicted itself, and even volatile couldn't rescue some idioms, double-checked locking among them. The rules of chapter 17 have barely changed since, so everything below applies equally to Java 5 and Java 21.

The name is misleading. Happens-before doesn't mean "happened earlier in time"; it's a guarantee of visibility and ordering. Two actions may run one after the other by the clock, but if there's no happens-before between them, the second is allowed not to see the first. Conversely, the JVM may reorder operations as long as no thread can observe it.

From this, JLS §17.4.5 defines a data race: two accesses to the same variable from different threads, at least one of them a write, that aren't ordered by happens-before. The key practical consequence: a program without data races behaves as if all operations of all threads ran one at a time in some single order (sequential consistency). Your job is to put happens-before edges wherever threads exchange data; everything else the JVM is free to optimize.

The memory model isn't the stack and the heap

"Java Memory Model" is often confused with the JVM's memory structure. The JMM is a set of visibility rules between threads; the stack, the heap and Metaspace are memory areas where data lives. If you were looking for where objects and local variables are stored, see Java Memory Structure: Stack and Heap.

happens-before Rules in Java

A happens-before relation in Java arises only in a few strictly defined cases: program order within a thread, unlocking and locking the same monitor, writing and reading the same volatile field, starting a thread, a thread terminating and join(), and interruption. All of them are transitive, so you can chain them.

Rule What happens-before what What it gives you in practice
Program order Each action of a thread happens-before every action that follows it in that thread's code Reordering is invisible within one thread. Other threads are not promised this order
Monitor Unlocking a monitor happens-before every subsequent lock of the same monitor What was written inside synchronized is seen by the next thread entering synchronized on the same object (details)
volatile A write to a volatile field happens-before every subsequent read of that same field The reader sees not only the new flag value but everything the writer did before the write
Thread.start() A call to t.start() happens-before any action in thread t Data prepared before start() is visible to the thread without synchronization (about start())
Thread termination Any action of thread t happens-before another thread successfully returns from t.join() or sees t.isAlive() == false After join() you can read the thread's results without volatile (example)
interrupt() A call to t.interrupt() happens-before t detects the interrupt (InterruptedException, isInterrupted()) The interrupted thread sees what the interrupting thread wrote before the call
final fields (JLS 17.5) Not happens-before in the strict sense but a separate guarantee: values of final fields written in the constructor Visible to any thread that obtains a reference to the object, as long as the constructor didn't leak this (immutable classes)
Transitivity If A hb B and B hb C, then A hb C Lets ordinary fields "ride along" on a single volatile write — see the next section

The key word in every rule is "same": the same monitor, the same field, the same thread. A write to volatile field a guarantees nothing to a thread reading volatile field b. Classes in java.util.concurrent provide the same kind of guarantees through their methods: the Javadoc of each has a "Memory consistency effects" section — for example, putting an element into a BlockingQueue happens-before taking it out.

Safe Publication with volatile

Safe publication means handing data to another thread so that it sees the data in full. With volatile it works like this: the thread fills in ordinary fields, then writes a volatile flag; a thread that reads the new flag value is guaranteed to see the ordinary fields too. This follows from program order, the volatile rule and transitivity.

public class Publication {
    private static int data;                  // plain field
    private static volatile boolean ready;    // publication flag

    public static void main(String[] args) throws InterruptedException {
        Thread reader = new Thread(() -> {
            while (!ready) {
                Thread.onSpinWait();          // hint to the CPU, Java 9+
            }
            System.out.println("data = " + data);
        });
        reader.start();

        data = 42;      // (1) plain write
        ready = true;   // (2) volatile write: everything above travels with it
        reader.join();
    }
}
data = 42

The chain goes like this: (1) happens-before (2) by program order, (2) happens-before the read that sees ready == true by the volatile rule, and that read happens-before the read of data by program order in the reader thread. So data = 42 is visible to the reader. This technique is sometimes called piggybacking: riding on someone else's synchronization.

The order of lines (1) and (2) matters. Swap them, and the reader may see ready == true and data == 0: the write to data now comes after the volatile write, and the rule doesn't cover it. Remove volatile from ready, and both bad outcomes become possible at once: the loop may never end, or it may end and print data = 0.

The guarantee is one-directional. It covers writes before the volatile write and reads after the volatile read. If the writer changes data again after ready = true, the reader may not see that change.

volatile and Atomicity: count++, long and double

volatile makes only individual reads and writes of a field atomic. Read-modify-write operations (count++, count += 5, flag = !flag) are still three steps, and another thread can slip in between them, so a volatile int count loses updates just like a plain int.

Here's how one increment gets lost even though both threads see the freshest value:

Step Thread 1 Thread 2 count in memory
1 Reads count: 41 — 41
2 — Reads count: 41 (a fresh value, volatile did its job) 41
3 Writes 41 + 1 — 42
4 — Writes 41 + 1 42 instead of 43

Visibility has nothing to do with it: the problem is that there's no mutual exclusion between the read and the write. The counter from the synchronization lesson still ends up below 200,000 with volatile (the example itself is in Race condition). Compound operations need synchronized or an atomic class such as AtomicInteger.incrementAndGet() (see Atomic Classes: AtomicInteger and CAS).

long and double without volatile

There is one case where you need volatile specifically for atomicity. Under JLS §17.7, a write to a plain (non-volatile) long or double field may be performed as two separate 32-bit writes. Another thread can then read a "torn" value: the high 32 bits from one write and the low 32 bits from another. For volatile long and volatile double tearing is forbidden, and writes and reads of references and all other primitives are always atomic.

On 64-bit JVMs (and you'll hardly meet any other kind today) HotSpot writes a long with a single instruction, and tearing doesn't show up in practice. But the specification allows it, and code that relies on one particular JVM's behaviour isn't portable. If one thread writes a long without synchronization and another reads it, declare the field volatile or use AtomicLong.

volatile vs synchronized

volatile gives visibility and ordering for a single variable without locking, while synchronized gives visibility plus mutual exclusion for any block of code. That's why volatile fits flags and publishing references, and anything that has to read and change data atomically or keep several fields consistent needs synchronized or the classes from java.util.concurrent.

Property volatile synchronized
Applies to Fields only (not local variables, not methods) Methods and blocks (not fields)
Visibility of changes Yes, for the write to this field and everything written before it Yes, for everything written under the monitor, to the next thread that acquires the same monitor
Atomicity Single reads and writes only; count++ is not atomic The whole block runs as one unit relative to other blocks on the same monitor
Blocking None: threads never wait for each other Yes: other threads wait in the BLOCKED state; with several monitors a deadlock is possible
Cost A read costs about as much as a plain field read but blocks some optimizations; a write is more expensive because of the memory barrier An uncontended monitor is cheap; under contention threads sit idle
Typical use Stop flag, publishing a ready immutable object, one writer and many readers Counters, check-then-act, invariants spanning several fields

A common interview question is "can I replace synchronized with volatile to make it faster?" Only if the block's sole job is to make a write visible and the operation itself is already atomic: a single assignment that doesn't read the old value. As soon as the code does "read, decide, write", volatile is no longer enough. How the monitor works is covered in Thread Synchronization in Java.

Double-Checked Locking and volatile

Double-checked locking in Java is a way to create a singleton lazily while acquiring the monitor only on the first call. Without volatile on the reference field the idiom is broken: another thread can get a reference to an object whose constructor hasn't finished. With volatile (since Java 5) it is correct.

The broken version looks perfectly reasonable:

public class Config {
    private static Config instance;      // NOT volatile - bug
    private int port;

    private Config() {
        port = 8080;
    }

    public static Config getInstance() {
        if (instance == null) {                    // 1st check, no locking
            synchronized (Config.class) {
                if (instance == null) {            // 2nd check, under the monitor
                    instance = new Config();
                }
            }
        }
        return instance;
    }

    public int getPort() {
        return port;
    }
}

The line instance = new Config() is memory allocation, the constructor, and the reference write. The creating thread sees them in order, but another thread does its first check outside synchronized, and its read has no happens-before relation with the constructor's writes. It can see a non-null reference and still get port == 0. The bug shows up rarely, on specific hardware and under load, which is why the idiom lived in production code for years.

The fix is one word:

public class Config {
    private static volatile Config instance;
    private int port;

    private Config() {
        port = 8080;
    }

    public static Config getInstance() {
        Config result = instance;                  // a single volatile read on the fast path
        if (result == null) {
            synchronized (Config.class) {
                result = instance;
                if (result == null) {
                    instance = result = new Config();
                }
            }
        }
        return result;
    }

    public int getPort() {
        return port;
    }
}

Now the reference write is a volatile write, and everything the constructor did happens-before any read that sees that reference. The local variable result isn't needed for correctness; it just saves a second volatile read once the object exists.

The Holder Idiom: Laziness Without volatile

It's simpler and safer not to write the double check at all and let the JVM handle lazy initialization:

public class Settings {
    private Settings() {
    }

    private static class Holder {
        static final Settings INSTANCE = new Settings();
    }

    public static Settings getInstance() {
        return Holder.INSTANCE;   // Holder is initialized on the first call
    }
}

The nested Holder class is initialized only on the first call to getInstance(), and class initialization under JLS §12.4.2 runs exactly once under an internal JVM lock and is visible to all threads. There's no volatile or synchronized in the code, and the fast path is a plain static field read. If you don't need laziness, a single-element enum gives the same guarantees.

When volatile Is Enough and When It Isn't

volatile is enough when a write to the field doesn't depend on its current value and the field isn't part of an invariant with other variables. In practice that means status flags, one-time publication of a ready immutable object, and the "one thread writes, many read" pattern. Anything built on "check, then act" needs a lock or atomic classes.

Scenario Is volatile enough? Why / what to use instead
Stop flag, shutdownRequested Yes A single assignment; the new value doesn't depend on the old one
Reference to a ready immutable object (configuration, cache snapshot) that is replaced as a whole Yes The new object is fully built before the volatile write of the reference
One thread writes sensor readings, many threads read them Yes There's one writer, so writes don't race with each other
A counter incremented by several threads No count++ isn't atomic — AtomicInteger, LongAdder or synchronized
"If not initialized yet, initialize" No Two threads can both see false and both run the initialization — synchronized, AtomicBoolean.compareAndSet, the holder idiom
Two related fields: lower <= upper No Each field is visible, but the pair can end up inconsistent — a shared monitor or one immutable object behind a volatile reference

The last row shows a handy technique. Two volatile fields lower and upper can't be changed atomically together: thread A sets lower = 5, thread B sets upper = 4, and the range is now impossible even though each check passed on its own. Put both values into an immutable record Range(int lower, int upper) and keep it in a single volatile reference (or an AtomicReference), and a reader always gets a consistent pair.

One more limitation. A volatile flag works for "is it time to stop?" checks, but not for waiting on an event: a while (!ready) {} loop keeps a CPU core busy. If a thread should sleep until data shows up, use wait()/notify() or a BlockingQueue — see wait(), notify() and notifyAll() in Java.

If volatile isn't fine-grained enough: since Java 9 (JEP 193), java.lang.invoke.VarHandle offers finer access modes on a field — getOpaque, getAcquire/setRelease, getVolatile, plus compareAndSet on ordinary fields. The java.util.concurrent classes are built on them; application code rarely needs them.

Frequently Asked Questions

Can a local variable be volatile, or a field be final volatile?

No, both are compile errors. Local variables belong to one thread — each method call has its own copy on the stack, so they don't need cross-thread visibility. javac rejects final volatile with "illegal combination of modifiers: final and volatile": a final field doesn't change after the constructor, and JLS 17.5 already guarantees the visibility of its value.

Does volatile make array elements volatile?

No. private volatile int[] data makes only the array reference volatile: assigning a new array is visible to everyone, but data[0] = 5 is a plain write with no visibility guarantee. For per-element volatile semantics use AtomicIntegerArray, AtomicLongArray, AtomicReferenceArray or MethodHandles.arrayElementVarHandle(...). The trick from the publication section also works: fill a new array, write its reference into a volatile field, and never modify it again.

Do I need volatile if a field is only read and written inside synchronized?

No. If every access to the field happens under the same monitor, visibility is already provided by the rule "unlocking a monitor happens-before the next lock of it". volatile is needed where at least one read happens outside the lock, like the first check in double-checked locking.

Does volatile slow a program down much?

Usually not. On x86 a volatile read is the same instruction as a plain read; the cost is that the JIT can't keep the value in a register or hoist the read out of a loop. Writes cost more: the JVM emits a memory barrier after them, and the core waits for its store buffer to drain. You'll notice it only in hot loops with frequent writes. Don't make every field volatile "just in case" — it hides real synchronization bugs.

Comments

Please log in or register to have a possibility to add comment.