Course contentsShow
← Java
Lesson 2682 of 2,87049. Synchronization and LockingFree lesson

Happens-Before Relationship for volatile Writes and Reads

Explore the formal memory ordering guarantee: all writes before a volatile write are visible to threads after a volatile read.

Happens-Before Relationship for volatile Writes and Reads

What You'll Learn

You'll understand the formal memory ordering guarantee that makes volatile variables a powerful synchronization tool: all writes before a volatile write become visible to threads after reading that volatile variable.

The Formal Memory Guarantee

When you mark a variable as volatile, you're not just preventing caching — you're establishing a happens-before relationship that enforces memory ordering across threads.

Here's the guarantee: If thread A writes to a volatile variable, and then thread B reads that same volatile variable, all variables that thread A modified before the volatile write are guaranteed to be visible to thread B after the volatile read.

This is stronger than just making the volatile variable itself visible. It creates a "memory barrier" or "fence" that flushes all pending writes to main memory and forces a fresh read of all variables.

Why This Matters

Consider this scenario:

class DataHolder {
    private int data = 0;
    private volatile boolean ready = false;
    
    // Thread A
    void publish() {
        data = 42;           // Write #1
        ready = true;        // volatile write #2
    }
    
    // Thread B
    void consume() {
        if (ready) {         // volatile read
            int value = data; // Guaranteed to see 42
        }
    }
}

Even though data is not volatile or synchronized, the happens-before relationship guarantees that thread B will see data = 42 once it reads ready = true. The volatile write acts as a release, and the volatile read acts as an acquire — creating a synchronization point.

Without volatile on ready, thread B might read ready = true but still see the old cached value of data.

Key Takeaway:
A volatile write makes all prior writes visible to any thread that subsequently performs a volatile read of that same variable, establishing a happens-before edge that synchronizes memory across threads.