Skip to main content

Welcome to a Grasp lesson

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

Lesson 1

Program vs. Execution Order in Java: A Reordering Example

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

Welcome to your first lesson in this course on advanced Java concurrency. Building on your existing knowledge of threading basics, we will now start our deep dive into the more subtle and powerful aspects of concurrent programming. Our first stop is the Java Memory Model (JMM), a critical topic for writing correct high-performance concurrent code.

This lesson focuses on a foundational concept: the difference between the order of instructions in your source code (program order) and the order in which they are actually executed by the machine (execution order). You'll learn why these can be different and see a practical demonstration of how this divergence, known as instruction reordering, can lead to unexpected behavior in a multithreaded program. Understanding this is the first step toward mastering the JMM.

The "As-If-Serial" Illusion

In a single-threaded world, you can comfortably assume your code runs line by line as you wrote it. While this is a useful mental model, it's not what actually happens. To maximize performance, the Java runtime (compilers, JIT, and even the CPU) is free to make aggressive optimizations, including changing the order of your instructions.

The only rule in a single-threaded program is that the final result must be the same as if the code had been executed sequentially. This is called "as-if-serial" semantics. As long as the runtime can maintain this illusion, it can perform any transformation it likes under the hood.

To explore this fundamental principle, let's turn to an article by Aleksey Shipilëv, a leading expert on the Java Memory Model and performance.

Close Encounters of The Java Memory Model Kind

This article provides a deep dive into the JMM. We'll start with a section that debunks the common myth that machines do exactly what we tell them to.

Please read the section "Myth: Machines Do What I Tell Them To Do." Focus on the text from the beginning of the section. The key takeaway is the concept of the "abstract machine" and the runtime's obligation to only produce results consistent with it, not to follow the source code literally.

This "as-if-serial" contract works perfectly for a single thread. However, when another thread enters the picture, it can observe the effects of these optimizations, and the illusion shatters, leading to counterintuitive results.


Why Reordering Happens

Instruction reordering is not a bug; it's a critical performance feature. It occurs at multiple levels:

  1. Compiler Reordering: The javac and Just-In-Time (JIT) compilers analyze code and reorder instructions to optimize execution. For example, they might move an instruction that takes a long time to an earlier point to hide its latency.
  2. Hardware Reordering: Modern CPUs also reorder instructions to keep their internal execution units busy. This is known as out-of-order execution.

The following video segments explain that the "program order" you write is defined not by line numbers, but by dependencies between operations. Instructions without dependencies are free to be reordered.

Concurrency Concepts in Java by Douglas Hawkins

This presentation by Douglas Hawkins offers a clear, practical overview of why reordering is a natural consequence of both compiler and hardware design.

Please watch the following clips: The "as-if" rule: A concise recap of the principle we just read about. Program order explained: This is a key segment. It clarifies that order is determined by data and control dependence, and independent instructions (like the shared y variable in the example) can be freely reordered. Hardware reordering: This part emphasizes that CPUs have been reordering instructions for decades to maximize performance.


A Practical Reordering Example

Now, let's see how these optimizations can break a simple concurrent program. Consider a classic scenario where a "producer" thread prepares some data and then sets a flag to signal that it's "done," while a "consumer" thread waits for the flag before using the data.

// Shared state, initially
private int a = 2;
private boolean flg = false;

// Executed by Thread 1 (Producer)
a = 1;
flg = true;

// Executed by Thread 2 (Consumer)
if (flg) {
  System.out.println("a = " + a);
}

Looking at this code, you would naturally assume that if Thread 2 sees flg as true, it must also see a as 1, because the assignment a = 1; happens before flg = true; in the program order. Therefore, the only possible outputs should be nothing (if flg is false) or "a = 1".

However, since the two assignments in Thread 1 are independent of each other from the perspective of that single thread, the compiler or CPU is free to reorder them. The execution order could become:

// Reordered execution in Thread 1
flg = true;
a = 1;

If Thread 2 runs between these two reordered instructions, it will see flg as true, enter the if block, but read the original value of a, which is 2. This leads to the surprising output: "a = 2".

The following diagram perfectly illustrates this scenario.

This diagram shows a classic data race caused by instruction reordering. Thread 1 intends to set a value (`a = 1`) and then a flag (`flg = true`). Thread 2 checks the flag and then reads the value. A programmer expects that if Thread 2 sees `flg` as `true`, it must also see `a` as `1`. However, because the compiler or CPU can reorder the two instructions in Thread 1, it's possible for Thread 2 to see the new value of `flg` but the old, initial value of `a`, leading to the unexpected output `a = 2`.

This exact producer-consumer reordering is a well-known problem, as shown in this final clip from the Hawkins video.

Concurrency Concepts in Java by Douglas Hawkins

Let's confirm our understanding with the video's explanation of this classic producer-consumer problem.

Watch the segment on reordering memory stores. It precisely matches the example we are discussing, showing how the shared done flag can be set before the shared data is ready.


Observing Reordering with Litmus Tests

Demonstrating instruction reordering empirically can be tricky, as it depends on the specific JVM, hardware, and runtime conditions. Concurrency experts use "litmus tests"—small, carefully crafted programs—to coax these behaviors out into the open. The jcstress framework, which we'll encounter later in the course, is built for this purpose.

The following blog post uses a simple litmus test to illustrate reordering.

Understanding Java Memory Model

This post uses concise litmus tests to demonstrate memory model behaviors. We'll use it to see how reordering manifests.

First, to establish a baseline, quickly review the definition of Sequential Consistency. This is the intuitive model where instructions are not reordered within a thread, and thread operations are simply interleaved. Next, focus on the first litmus test, Message Passing. Pay close attention to the table that shows the outcome r1 = 1, r2 = 0 is impossible under sequential consistency but is possible in plain Java. This is a direct consequence of the compiler being able to reorder the writes to x and y.

As you've seen, what you write is not always what gets executed. These reorderings, while beneficial for performance, break the intuitive model of how concurrent code should behave. The Java Memory Model provides rules and tools to control this behavior.

Aleksey Shipilëv demonstrates this causality violation in his workshop and introduces the fundamental rule used to prevent it, which gives us a sneak peek at the solutions we'll be studying.

Aleksey Shipilev — Workshop: Java Concurrency Stress (JCStress). Part 1

Aleksey Shipilëv, creator of the jcstress tool, demonstrates a causality violation and the "safe publication" rule that prevents it.

Watch the segment on Causality. He uses a litmus test very similar to the one you just read about and shows that the "forbidden" outcome 1, 0 does happen in practice on certain hardware. Then, pay close attention to the Safe Publication rule. This is a crucial concept. It introduces the idea that a special kind of write (a "releasing store") can guarantee that all prior writes are visible to a thread performing a special kind of read (an "acquiring read").

This idea of "acquire" and "release" semantics forms the basis of the happens-before relationship, which is the cornerstone of reasoning about concurrency in Java.


Key Takeaways

  • Program Order vs. Execution Order: The sequence of instructions in your source code does not dictate the final execution order.
  • Reordering is a Feature: Compilers and CPUs reorder independent instructions to maximize performance.
  • Concurrency Breaks Illusions: While optimizations are invisible in a single thread ("as-if-serial"), their effects become visible and can cause bugs when multiple threads are involved.
  • The Problem in Practice: We saw how reordering data = 42; and ready = true; can cause a consumer thread to read stale data (data = 0) after seeing the ready flag.

What's Next

Now that we have demonstrated the problem of instruction reordering, our next lesson will introduce another fundamental challenge: memory visibility. We'll investigate how CPU caches can prevent one thread from seeing updates made by another, even when no reordering occurs. These two concepts—reordering and visibility—are the primary problems that the Java Memory Model, and tools like the volatile keyword, are designed to solve.