JMM Happens-Before

JMM Happens-Before

Controlling complexity is the essence of computer programming.

Brian Kernighan

Happens-before is a set of rules established by the Java Memory Model (JMM) to define ordering constraints and visibility guarantees in multithreaded execution of a Java program.

As-if-Serial Semantics

A key concept to keep in mind is “as-if-serial”. When a program runs in a single-threaded Java application, its execution must appear as if it were executed sequentially. In this situation, the compiler, the JVM, and the CPU are free to reorder instructions freely, as long as they preserve the observable behavior of the original program.

“As-if-serial” means that instructions may be reordered, primarily to improve performance, but still have to behave as if the code had no instruction reordering.

Let’s say that your Java Code has these instance variables:

int anotherVariable = 0;
String loadedData;
boolean isLoaded = true;

The code could run the three lines in any order, given that they do not depend on each other. In a single-threaded environment, it shouldn’t be a problem, because of the As-if-Serial semantics, but when more threads are involved, maybe a thread sees isLoaded as true before loadedData is actually loaded, but we’ll see more about that later on.

The improvements in performance, as we’ve started to discuss, may lead to visibility and ordering issues for a program running in a multithreaded environment when threads share state.

There are two main forces acting to pose problems to multitreaded applications in Java. Reordering and Visibility (Memory)

Reordering

As we’ve briefly discussed, the compiler, the JVM and even the CPU are free to reorder operations, unless that would violate a happens-before relationship and as long as they keep the as-if-serial semantics. So, when reading multithreaded Java code, it is important not to trust the apparent order of the operations blindly.

Reordering, alongside memory caching, is what causes threads to observe inconsistent states.

Let’s isolate the effect of reordering with a thought experiment. Assume an imaginary system with perfect visibility, in which every write is immediately observable by all threads (i.e., no stale reads). In such a system, the only remaining source of unexpected behavior is the ordering of operations. Consider the example below:

class ReorderingExample {
    static int x = 0, y = 0, a = 0, b = 0;

    public static void main(String[] args) throws InterruptedException {
        var threadA = new Thread(() -> {
            a = 1;  // will this happen before x=b?
            x = b;
            /* From this thread perspective, the order of operations is
               irrelevant. So as-if-serial semantics is maintained even
               if x=b happens before a=1 */
        });

        var threadB = new Thread(() -> {
            b = 1;  // will this happen before y=a?
            y = a;
            /* From this thread perspective, the order of operations is
               irrelevant. So as-if-serial is semantics maintained even
               if y=a happens before b=1 */
        });

        threadA.start();
        threadB.start();

        threadA.join();
        threadB.join();

        /* 
           If you think order would be maintained, then
           CASE 1: threadA ran entirely before threadB
           You'd expect x==0 rather than y==1

           CASE 2: threadB ran entirely before threadA
           You'd expect y==0 rather than x==1


           CASE 3: Each thread performed its first operation before either
           performed the second
           You'd expect x==1, y==1
        */
        System.out.printf("x=%d, y=%d%n", x, y);

        /* 
           But given that there is no happens-before relationship,
           The order of operations within each thread may have been
           reordered.


           x=b may have happened before a=1, and 
           y=a may have happened before b=1.
           This is one possible execution allowed by the system.

           So, one possible interleaving of operations could behave as follows:
           ThreadB: y=a;
           ThreadA: x=b;
           ThreadA: a=1;
           ThreadB: b=1; 

           Surprisingly, the result x==0 and y==0 is also a valid outcome.
         */
    }
}

In this scenario, the surprising outcome (x==0 and y==0) can only occur if operations are executed out of their original program order.

In the real world, though, the unexpected behavior could arise not only because of reordering of operations, but also due to memory related issues.

As we’ll discuss shortly, there are ways to obtain some guarantees related to the order of operations in the code execution.

Visibility

We talked about visibility without explaining what we meant about it. It is all about shared memory.

Let’s talk briefly about Memory before diving into the Visibility concept.

Memory Architecture

The image above shows a simplified example of memory architecture. L1 caches are per core (private), L2 are usually also private, and L3 are usually shared. RAM is shared, but it is slow compared to the other caches.

Remember that when we write to or read from memory, it very likely goes through layers of cache and a write to shared variables is not guaranteed to become immediately visible to other threads. This happens because when Thread 1 writes to memory, it will go through the cache layers, and when Thread 2 tries to read from that variable, it is possible that its own caches still don’t have the newest value. So the thread does not see it.

Wait, but don’t the CPUs keep the caches coherent? Yes, of course, but not necessarily immediately visible, and also, without ordering guarantees.

Visibility, therefore, means that a write performed by one thread becomes observable (or visible) to other threads.

Publication

Making a variable visible and ensuring that its state is fully and correctly observable by other threads is called publication. We’ll see how to accomplish that shortly.

public class UnsafePublicationExample {
static class AnswerHolder {
int answer;

        AnswerHolder() {
            answer = 42;  // Yes, the answer to everything
        }
    }

    // Shared variable
    static AnswerHolder holder = null;

    public static void main(String[] args) throws InterruptedException {
        var writer = new Thread(() -> {
            holder = new AnswerHolder();
        });

        var reader = new Thread(() -> {
            /*
             The compiler or JVM could think: wait, holder is null, so I can 
             create a local copy and never look at the original again.
             Because there is no happens-before relationship, the 
             compiler and the JVM are allowed to assume the value does 
             not change.
            */
            while (holder == null) {  // This could loop forever
                // wait
            }

            var localAnswer = holder.answer;

            if (localAnswer != 42) {  // it could be 0! Initialization could have not yet run
                System.out.printf("Observed partially initialized value: %s%n", localAnswer);
            }
        });

        // Let's start these Threads
        writer.start();
        reader.start();

        // And wait form them to finish
        writer.join();
        reader.join();
    }
}

The Volatile Keyword

When we mark a shared variable (instance or static) to be volatile, we are establishing some guarantees: - All writes to this variable happen before any subsequent read of the same variable (it does not skip caches, it sets some memory barriers). - All writes that happen before the volatile write “piggyback” the write operation, becoming visible to the reading thread. Imagine some other variables — not marked with the volatile keyword — have already been written to, but are still travelling through the caches; When there is a write to a volatile variable, all these variables also become automatically observable by all other threads. This is what enables safe publication. - Operations before the volatile write cannot be reordered after it - Operations after the volatile read cannot be reordered before it.

int anotherVariable = 0;
String loadedData = loadValue();
// --- MEMORY BARRIER
// --- memory flush (both anotherVariable and loadedData are published)
volatile boolean isLoaded = true;

With volatile, we are telling the CPUs and the compiler to stop trying to be clever and just do what we told them to, preventing the compiler and the CPU from applying certain optimizations that could break visibility guarantees.

In the example of UnsafePublicationExample, declaring the static variable holder as volatile, would have solved the publication problem. First, it does not allow the compiler to be overly smart and think that the holder will never change and therefore create a local variable for the reader thread that never changes. Second, after the writer creates the object, it guarantees that any subsequent read sees a fully initialized object, meaning that the 42 is now guaranteed to be seen by any thread.

Happens-Before rules

Programs are meant to be read by humans and only incidentally for computers to execute.

Donald Knuth

“”

So far, we’ve seen the problems: reordering and visibility. Happens-before is the mechanism that allows us to regain control and reason correctly about shared state.

Let’s now formalize the rules, building on what we’ve covered so far.

I don’t know about you, but I have trouble remembering these rules, so I came up with phrase that is a bit easier to remember:

  1. Please: Program Order So, within a thread, each action happens-before every subsequent action in that thread.

  2. Thread Start A call to thread.start() happens-before any action in the started thread.

  3. Thread Join All actions in a thread happen-before another thread successfully returns from join() on that thread.

  4. Vast: Volatile A write to a volatile variable happens-before every subsequent read of that same variable. All writes that occur before the volatile write also become visible to the thread that performs the volatile read. This is often referred to as the “piggyback” effect.

  5. Majority: Monitor Lock Rule An unlock (exit from a synchronized block) happens-before every subsequent lock (entry into a synchronized block) on the same monitor.

    A call to notify() / notifyAll() on an object happens-before the return from wait() on the same object (We’ll talk more about this one on another post)

  6. Friends: Final (object construction) Field Rule Writes to final fields in a constructor are guaranteed to be visible to other threads after the constructor completes, as long as the object is properly constructed and does not escape during construction.

If none of these rules establish a happens-before relationship between two operations, the behavior is not guaranteed, and threads may observe unexpected results. In that case, the behavior is not just unpredictable — it is formally undefined by the Java Memory Model.

One last point to highlight is the transitivity property. If A happens-before (hb) B and B hb C, then A hb C.

Atomicity

This is also a point to have in mind. Not everything that appears to be one single operation actually is. The ++ operator is not atomic. It is compiled into multiple operations at the bytecode level: reading the current value, adding 1 to it, and writing the result back to the variable. In other words, it is both a read and a write operation.

Because of this, multiple threads executing the same operation may interleave in unexpected ways. This can lead to lost updates when multiple threads operate on the same variable.

Remember: happens-before guarantees visibility and ordering, but not atomicity.

That is one of the reasons to use atomic classes such as AtomicInteger, which provide operations that are both thread-safe and atomic.

Understanding happens-before is essential because it defines when multithreaded code is correct — without it, correctness is simply not guaranteed.

Test your knowledge

Multiple choice questions

Q1: Which of the following establishes a happens-before relationship? (one or more correct answers) - A. Writing to a normal variable - B. Writing to a volatile variable - C. Calling thread.start() - D. Reading from a field

B and C. Writing to a volatile variable and calling thread.start() both establish happens-before relationships.

Q2: What does happens-before guarantee? (one or more correct answers) - A. Atomicity - B. Visibility - C. Ordering - D. Thread scheduling

B and C Happens-before guarantees ordering and visibility, but not atomicity or thread scheduling.

Q3: Which of the following are true about volatile? (one or more correct answers) - A. It guarantees atomicity - B. It prevents certain reordering - C. It guarantees visibility - D. It replaces synchronization entirely

B, C Volatile establishes a happens-before relationship, which guarantees visibility and prevents certain reorderings. It does not guarantee atomicity.

Q4: Which scenario can lead to an infinite loop? (one or more correct answers) - A. Using volatile - B. No happens-before relationship - C. Using synchronized - D. Using final fields Q5: What problem does AtomicInteger solve? - A. Visibility B. Ordering C. Atomicity D. Scheduling

Interview questions

Q1: What is the happens-before relationship, and what does it guarantee?

Q2: Explain the difference between: as-if-serial semantics happens-before

Q3: Why is reordering not a problem in single-threaded code, but becomes a problem in multithreaded code?

Q4: What are the two main sources of issues in multithreaded programs described in the text?

Q5: What is publication, and why is it important?

Q6: What does volatile guarantee, and what does it NOT guarantee?

Q7: If I remove all caches from the system, can I still get unexpected results in multithreaded code?

Spot-the-Problem (Code Questions)

For each piece of code, tell what could go wrong, why and how to fix it. Declare your assumptions about the code.

Q1:

int data = 0;
boolean ready = false;

var writer = new Thread(() -> {
    data = 42;
    ready = true;
});

var reader = new Thread(() -> {
    if (ready) {
        System.out.println(data);
    }
});

Q2:

class Holder {
    int value = 42;
}

static Holder holder;

var writer = new Thread(() -> {
    holder = new Holder();
});

var reader = new Thread(() -> {
    while (holder == null) {}
    System.out.println(holder.value);
});

Q3:

int count = 0;  // assume this compiles (it is not effectively final)

var t1 = new Thread(() -> count++);
var t2 = new Thread(() -> count++);

System.out.println(count);

Q4:

volatile boolean ready = false;
int data = 0;

var writer = new Thread(() -> {
    data = 42;
    ready = true;
});

var reader = new Thread(() -> {
    if (ready) {
        System.out.println(data);
    }
});

Answers

Multiple choices questions:

Q1: B and C: Writing to a volatile variable and calling thread.start() both establish happens-before relationships.

Q2: B and C: Happens-before guarantees ordering and visibility, but not atomicity or thread scheduling.

Q3: B, C: Volatile establishes a happens-before relationship, which guarantees visibility and prevents certain reorderings. It does not guarantee atomicity.

Q4: B: Without a happens-before relationship, there are no guarantees about visibility. In a loop, the compiler, JVM, or CPU may treat the variable as if it never changes, which can result in an infinite loop.

Q5: C: AtomicInteger provides atomic operations, preventing lost updates in concurrent scenarios.

Interview questions:
Q1: The happens-before relationship is a set of rules defined by the Java Memory Model that establish ordering constraints between operations. If one operation happens-before another, then the effects of the first (such as writes to shared variables) are guaranteed to be visible to the second.

Q2: As-if-serial semantics applies to single-threaded execution. It allows the compiler, JVM, and CPU to reorder instructions as long as the observable behavior of the program remains the same.

Happens-before, on the other hand, applies to multithreaded execution. It defines ordering and visibility guarantees between operations performed by different threads.

In short, as-if-serial ensures correctness within a single thread, while happens-before ensures correctness across threads.

Q3: Reordering is not a problem in single-threaded code because of as-if-serial semantics. The compiler, JVM, and CPU are allowed to reorder operations as long as the observable behavior of the program remains the same. Since there is only one thread, no other observer can detect these changes.

In multithreaded code, however, other threads may observe the effects of these operations. Without a happens-before relationship, there are no guarantees about ordering or visibility, so operations may appear out of order and threads may see stale data.

Q4: Reordering and Visibility issues, such as stale reads due to memory caching.

Q5: Publication is the act of making a variable visible to other threads and ensuring that its state is fully and correctly observable.

It is important because, without proper publication, other threads may see stale values or even partially initialized objects.

Q6: Volatile guarantees visibility and ordering. A write to a volatile variable happens-before any subsequent read of that same variable, ensuring that the most up-to-date value is seen.

It also guarantees that all writes that occur before the volatile write are visible to the reading thread (the “piggyback” effect).

However, it does not guarantee atomicity. Operations like ++ can still interleave between threads and produce incorrect results.

Q7: Yes. Even without caches, reordering alone can lead to unexpected results if there is no happens-before relationship.

Spot-the-problem (Code questions) Q1: I’ll assume data and ready are shared fields, and that both threads are started and joined by the main thread.

There are two main problems here:

  1. There is no happens-before relationship between the writer’s actions and the reader’s actions. Because of that, the compiler, JVM, or CPU may reorder the writer’s operations so that ready = true becomes observable before data = 42. In that case, the reader may enter the if block and print 0.

  2. Even if the writer executes in program order, the updated values may still not be visible to the reader thread. The reader may see ready == false and print nothing, or it may see ready == true while still seeing the old value of data.

So the core issues are lack of ordering guarantees and lack of visibility guarantees.

For a solution proposal, check Q4.

Q2: I’ll assume Holder is a nested class and that both the writer and reader threads are started and joined by the main thread.

  1. There is no happens-before relationship between the writer and reader threads, so the code lacks ordering and visibility guarantees.

  2. Because there is no happens-before relationship, the compiler, JVM, or CPU may treat repeated reads of holder as if the value never changes. That can cause the while (holder == null) {} loop to run forever.

  3. Even if holder becomes visible to the reader thread, the object may not have been safely published yet. As a result, the reader could observe a partially initialized object and print 0 instead of 42.

The simplest solution is to declare the shared static variable holder as volatile. That establishes the necessary visibility and ordering guarantees for safe publication: once the reader sees a non-null reference, it is guaranteed to observe a fully initialized object. In that case, the printed value would be 42.

Q3: I’ll assume count is a shared field and that t1 and t2 are started and joined by the main thread before printing.

One might wrongly assume that the only possible result is 2, but that is not the case.

The problem is that count++ is not atomic. It is actually a read-modify-write sequence: read the current value, add 1, and write the result back.

Because of this, the two threads may interleave these steps in such a way that both read the same original value and both write back the same incremented value. In that case, one update is lost, and the final result can be 1.

So the main issue here is the lack of atomicity.

Use an AtomicInteger and its incrementAndGet() method to ensure the increment is atomic and avoid lost updates.

Q4: I’ll assume that ready and data are shared fields, and that both writer and reader are started and joined by the main thread.

Because ready is declared volatile, a write to ready happens-before any subsequent read of that same variable.

This also gives us the “piggyback” guarantee: all writes that occur before ready = true — in this case, data = 42 — become visible to any thread that later reads ready as true.

So if the reader enters the if block, it is guaranteed to print 42, not 0.

However, the code is still not fully correct if the intention is to always print the value, because interleaving is still possible. For example, the reader may run before the writer sets ready = true, observe ready == false, and skip printing entirely.

So volatile fixes the visibility and ordering issue, but it does not guarantee that the reader will actually wait for the writer.

The simplest solution to ensure the value is always printed would be to wait in a loop until ready becomes true. That is not the best solution, though, but we can leave that for a later discussion.