Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 5

Understanding Happens-Before for Thread Safety in Java

This lesson is built with resources from youtube.com, dzone.com and 1 more site.

Welcome back! In our last session, you fixed a visibility bug by applying the volatile keyword, and we introduced a key concept from the Java Memory Model: the volatile variable rule. This rule establishes a happens-before relationship, which guarantees that writes to a volatile variable are visible to subsequent reads of that same variable.

This lesson expands on that idea significantly. volatile is just one of several ways to create a happens-before relationship. Today, we will explore the complete set of rules that govern this relationship. Mastering these rules will provide you with a formal and powerful framework to analyze the thread-safety of any concurrent Java code, moving beyond intuition to predictable, provable correctness.

What is the Happens-Before Relationship?

At its core, the Java Memory Model (JMM) is a specification that describes what behaviors are permissible in a concurrent program. It doesn't dictate how a specific JVM or CPU must implement things; rather, it defines an abstract machine and a set of rules. If the result of a program's execution is indistinguishable from one of the valid behaviors of this abstract machine, it's considered a legal outcome.

The happens-before relationship is the central concept in the JMM for reasoning about memory visibility. It is a partial ordering of all actions (like reads and writes of variables) in a program. The rule is simple yet profound:

If action A happens-before action B, then the effects of action A are guaranteed to be visible to and ordered before action B.

This doesn't mean A must physically execute before B. Compilers and CPUs are still free to reorder instructions for performance. However, they are forbidden from performing any reordering that would change the outcome in a way that violates the happens-before guarantee.

To get a precise, formal overview of the JMM's components, the following resource from Aleksey Shipilëv, a leading expert on Java performance, is invaluable.

Close Encounters of The Java Memory Model Kind

This post provides a masterclass in the JMM. For now, we'll focus on the initial recap of the model's core concepts.

Please read the "Model Recap" section. Focus on the definitions of the first three orders (Program Order, Synchronization Order, Synchronized-with) and, most importantly, the definition of Happens-before order (HB) and its consistency rule.


The Rules of the Road

The happens-before relationship isn't magic; it's established by a concrete set of rules defined in the Java Language Specification. Any two actions are ordered by happens-before if and only if they can be linked by one or more of these rules.

Java Concurrency: The Happens-Before Guarantee

This DZone article provides a clear, concise list of the primary happens-before rules, each with a small code example.

Please read the section titled "Rules", which lists the five main guarantees. Then, review the explanations and code snippets for each rule that follow, up to the end of the article.

Let's summarize and consolidate these crucial rules:

  1. Program Order Rule: Within a single thread, if statement A appears before statement B in the source code, then any action from A happens-before any action from B. This is the foundation that ensures single-threaded code behaves as expected.

  2. Monitor Lock Rule: An unlock on a monitor (e.g., exiting a synchronized block) happens-before every subsequent lock on that same monitor (e.g., another thread entering a synchronized block on the same object). This is the core guarantee that makes synchronized work for visibility.

The Monitor Lock rule ensures that when Thread B acquires a lock that Thread A has just released, all memory writes made by Thread A before releasing the lock are visible to Thread B.
  1. Volatile Variable Rule: A write to a volatile variable happens-before every subsequent read of that same volatile variable. As you saw in the last lesson, this forces changes to be flushed to and read from main memory.

  2. Thread Start Rule: A call to Thread.start() on a thread object happens-before any action in the started thread. This ensures that the parent thread's state is visible to the new child thread when it begins execution.

  3. Thread Join Rule: All actions in a thread happens-before any other thread successfully returns from a Thread.join() on that thread. This guarantees that all results of a completed thread are visible to the thread that joins it.

  4. Transitivity: If action A happens-before action B, and B happens-before C, then A happens-before C. This is the "glue" that allows us to chain the other rules together to reason about visibility across different threads and synchronization mechanisms.


Analyzing Code with Happens-Before

Let's use these rules to analyze a classic "safe publication" idiom. This is where your practical experience as an engineer meets the formal model.

Consider this code:

// Thread 1 (Writer)
int x = 0;
volatile boolean ready = false;

public void writer() {
    x = 42;
    ready = true;
}

// Thread 2 (Reader)
public void reader() {
    if (ready) {
        System.out.println(x);
    }
}

Can the reader method ever print 0? Let's build a happens-before chain to find out.

  1. x = 42 happens-before ready = true (within Thread 1, by the Program Order Rule).
  2. If the reader thread sees ready as true, it means the write ready = true happens-before the read if (ready) (by the Volatile Variable Rule).
  3. The read if (ready) happens-before the read System.out.println(x) (within Thread 2, by the Program Order Rule).

Now, let's connect the chains using transitivity:

  • From (1) and (2), we get: x = 42 →hb→ ready = true →hb→ if (ready).
  • Chaining this with (3), we get: x = 42 →hb→ if (ready) →hb→ System.out.println(x).
  • Therefore, x = 42 happens-before System.out.println(x).

Conclusion: According to the happens-before consistency rule, the read of x must see the write x = 42 (or a later write). It is therefore impossible for the reader to see ready as true and x as 0. The outcome 0 is forbidden.

This pattern of "writes to normal variables, followed by a write to a special volatile variable" is a fundamental technique for safely publishing data between threads.

This diagram illustrates our analysis. The write to `x` (Action A) happens-before the volatile write to `v` (Action B) due to program order. The volatile write `v=true` happens-before the volatile read `v==true` (Action C) due to the volatile rule. By transitivity, Action A happens-before Action C, guaranteeing that the subsequent read of `x` will see the value 42.

The video below gives a fantastic walkthrough of the JMM's formalisms and reinforces this concept of safe publication through "release-acquire" semantics, which is a more practical way of thinking about happens-before.

GeeCON 2018: Aleksey Shipilëv - Java Memory Model Unlearning Experience

Aleksey Shipilëv's GeeCON talk, "Java Memory Model Unlearning Experience," cuts through common misconceptions. This segment defines happens-before and uses it to explain safe publication.

Watch the following segments: Happens-Before Definition: This part formally defines happens-before as the transitive closure over program order and synchronizes-with, and walks through a proof. Safe Publication: This is the key takeaway. It simplifies the formal rules into the practical "release-acquire" pattern, which is exactly the idiom we just analyzed. Golden Rules: This summarizes the core principles for writing correct concurrent code based on happens-before.


Common Pitfalls: Breaking the Chain

The happens-before rules are precise. A small deviation from the correct pattern breaks the guarantee. Understanding these failure modes is critical for debugging.

Let's look at a common mistake: releasing in the wrong order.

// Thread 1 (Writer)
int x = 0;
volatile boolean ready = false;

public void writer_wrong() {
    ready = true; // Volatile write comes FIRST
    x = 42;       // Regular write comes AFTER
}

// Thread 2 (Reader)
public void reader() {
    if (ready) {
        System.out.println(x);
    }
}

Can the reader print 0 now? Yes!

  • The write ready = true happens-before the read if (ready).
  • However, there is no happens-before edge from x = 42 to ready = true. The Program Order Rule goes the other way.
  • The chain is broken. The JVM is free to reorder x = 42 to happen after the reader has already checked ready and is about to read x. The result is a data race, and the reader might see the default value of 0.

This and other common errors are brilliantly demonstrated with JCStress tests in Shipilëv's article.

Close Encounters of The Java Memory Model Kind

This part of the article moves from theory to practice, showing exactly how misusing happens-before leads to observable bugs.

Please read the sections titled "Pitfall: Releasing in Wrong Order" and "Pitfall: Acquiring in Wrong Order". Pay close attention to the code examples and the explanation of why the "bad" outcomes are possible. You have experience with JCStress, so the test results should be familiar.


Conclusion

In this lesson, we moved from the specific case of volatile to the general theory of memory consistency in Java. You now have a complete toolkit for analyzing visibility guarantees.

Key Takeaways:

  • The happens-before relationship is the JMM's formal guarantee of memory visibility. If A happens-before B, the effects of A are visible to B.
  • This relationship is built upon a set of specific rules: Program Order, Monitor Lock, Volatile Variable, Thread Start/Join, and Transitivity.
  • By chaining these rules together, you can formally prove whether a piece of concurrent code is thread-safe with respect to visibility.
  • The common "release-acquire" pattern (writes to shared variables followed by a write to a synchronization variable) is a practical application of happens-before for safely publishing data.
  • Deviating from these patterns, such as writing to a volatile variable before the data it's meant to publish, breaks the happens-before chain and leads to data races.

In our next lesson, we will address a crucial limitation of volatile and the happens-before guarantees we've discussed. While they provide visibility and ordering, they do not provide atomicity. We will diagnose scenarios where volatile is insufficient and explore the mechanisms Java provides for atomic, compound operations.