Reading Notes on The Art of Java Concurrency Programming: JMM

Because of visibility issues, different CPU cores can see memory operations in different orders, so it looks as if instructions were reordered.

The JMM forbids specific types of compiler reordering at compile time, and inserts memory barriers between instructions to forbid specific types of processor reordering at runtime. That way, differences in reordering rules across compilers and CPU architectures won’t cause unexpected results.

Modern processors don’t write straight to main memory on every store. They write to their own local write buffers first. Because every core has its own buffer, buffered data and main memory can fall out of sync. Take Core A running two instructions: instruction 1 updates x, and instruction 2 reads y. Core A writes the new x to its buffer, then reads y from main memory. Meanwhile Core B runs two instructions: instruction 1 updates y, and instruction 2 reads x. Core B writes the new y to its buffer, then reads x from main memory. Because neither buffer has been flushed yet (or only one has), both cores can end up reading stale values. At the instruction level, it looks like instruction reordering happened, even though the real cause is visibility, which is why people also call this memory-system reordering.

Starting with JDK 1.5, Java adopted the JSR-133 memory model (JSR-133 is the Java Memory Model and Thread Specification, part of JSR-176). JSR-133 introduced the happens-before principle to describe ordering relationships between operations. If operation A happens-before operation B, then the result of A is guaranteed to be visible to B. A and B can be in the same thread or in different threads.

Note that happens-before is a partial order. It only requires the result of the first operation to be visible to the second; it does not guarantee that the first operation physically executes before the second. For example, if A happens-before B, and B executes first while needing to read data written by A, happens-before guarantees B reads the right data, not that A literally ran before B in time.

When A happens-before B, the JMM doesn’t require A to execute before B. It only requires that A’s result is visible to B, and that A is ordered before B in the program’s logical execution flow.

as-if-serial semantics mean that in a single-threaded environment, no matter how instructions are reordered, the execution result never changes. You can think of it as looking like sequential execution, even though things may have been reordered under the hood.

When operations have a control dependency between them, it limits instruction-level parallelism. To work around that, compilers and processors use speculative execution. Take if (flag) { a = a + b; }: the processor may compute a + b ahead of time and hold the result temporarily in the Reorder Buffer (ROB); if flag turns out to be true, it writes that result to a.

So even when instructions have a control dependency, compilers and processors will still reorder them. In a multithreaded environment, that reordering can break expected program behavior, so you need synchronization primitives like locks, volatile, or final to constrain it. In a single thread, as-if-serial holds, so the outcome won’t change.

The sequential consistency memory model is an idealized theoretical model with two main properties: (1) all instructions within a single thread must execute in program order; (2) regardless of whether the program is synchronized, all threads see the same order of instruction execution, and every operation executes atomically and becomes visible to all threads immediately.

In the JMM, however, unsynchronized programs get no guarantee that all threads see the same execution order, nor real-time visibility. Enforcing that would heavily restrict compiler and processor optimizations. Instead, the JMM uses locks and other synchronization primitives to guarantee correct multithreaded results. Even inside a critical section, instructions can still be reordered, which gives a big boost to execution speed.

You can roughly think of volatile as wrapping a single variable’s reads and writes in a lock. For reads and writes of a single variable, volatile guarantees atomicity. Notice the scope: a single variable. On a 32-bit platform, writing a 64-bit long can be split by the JMM into two 32-bit writes (high 32 bits and low 32 bits separately), which can cause word tearing. (Since JDK 1.5, reads of 64-bit variables are already required to be atomic, executed in a single bus transaction, which mostly solves word tearing on reads, though writes can still be split.) volatile guarantees atomicity for such single-variable reads and writes, but it cannot make operations across multiple variables or compound operations atomic. a++, for instance, is three steps (read a, add 1, write back a), and volatile cannot make those three steps atomic together.

Under the happens-before rules, the result of a volatile write is visible to any subsequent volatile read. During compilation, the compiler inserts a write memory barrier after a volatile write and a read memory barrier before a volatile read. (Exact placement depends on the strategy: the most conservative strategy places barriers both before and after reads and writes, while the compiler optimizes away redundant ones where it can keep correctness and improve performance.) The write barrier forces written values to be flushed to main memory; the read barrier forces local memory to refresh from main memory, guaranteeing visibility. Also, the read barrier stops reads from being reordered ahead of writes, and the write barrier stops writes from being reordered ahead of reads.

If you don’t need atomicity across an entire critical section, you can use volatile instead of a lock. It’s lighter weight and faster, with no context-switching overhead.

Releasing a lock has the same memory semantics as a volatile write (flushing data to main memory); acquiring a lock has the same memory semantics as a volatile read (refreshing local memory from main memory).

The JMM gives programmers happens-before rules to specify memory visibility, while internally splitting the reorderings forbidden by happens-before into two groups: those that change the execution result and those that don’t. For the second group, the JMM actually allows the reordering. So the happens-before rules and what the JMM enforces under the hood are not identical.

The JMM follows one basic rule: as long as the execution result doesn’t change, the compiler and processor can optimize however they like. For example, if a lock is only ever accessed by a single thread, the compiler will strip it out completely (lock elimination). Likewise, if a volatile variable is only ever accessed by a single thread, the compiler will treat it as an ordinary variable.