Fundamentals 13 min read

Why Java’s Memory Model Matters: Atomicity, Visibility, and Ordering Explained

This article breaks down the Java Memory Model, detailing how atomicity, visibility, and ordering work in multithreaded programs, illustrating the impact of instruction reordering, and showing how synchronized, volatile, and happens‑before rules ensure correct concurrent behavior.

Senior Brother's Insights
Senior Brother's Insights
Senior Brother's Insights
Why Java’s Memory Model Matters: Atomicity, Visibility, and Ordering Explained

Atomicity

Atomicity means an operation or a group of operations cannot be interrupted; once a thread starts an action, no other thread can interleave. For example, when two threads assign different values to a static int variable, each thread’s write completes without interference, guaranteeing that the final value is either the first or the second assignment.

The Java Memory Model guarantees atomicity for basic read/write actions such as read, load, assign, use, store, and write. Primitive type accesses are generally atomic (except for the historic "half‑word" issue with long and double, which is rarely observed). To obtain larger‑scope atomicity, developers use the synchronized keyword, which also provides atomicity for the enclosed block.

Visibility

Visibility ensures that when one thread modifies a shared variable, other threads can immediately see the change. The JMM synchronizes variable updates to main memory and forces reads to refresh from main memory, using the main memory as the communication medium.

Both ordinary and volatile variables follow this rule, but volatile guarantees that writes are instantly flushed to main memory and reads always fetch the latest value, while ordinary variables do not provide this guarantee.

In addition to volatile, synchronized and final can also provide visibility. synchronized achieves visibility by flushing shared variables to main memory before unlocking, and by clearing the thread’s working memory on lock, forcing a fresh read. final fields become visible to other threads after the constructor finishes, provided the constructor does not leak this.

Ordering

Ordering means that within a single thread, operations appear to execute sequentially, but across threads the JVM may reorder instructions for performance, leading to out‑of‑order execution. This reordering can break the intuitive expectation that operations happen in program order.

Both volatile and synchronized can be used to enforce ordering between threads.

Instruction Reordering

After compilation, the CPU and compiler may reorder instructions while preserving single‑thread semantics. Three main sources of reordering are:

Compiler optimizations that rearrange statements without changing single‑thread behavior.

CPU instruction‑level parallelism that overlaps execution of independent instructions.

Memory system reordering where caches and write buffers make loads and stores appear out of order.

Example code demonstrates a possible reordering where a write to flag may become visible before the write to a, causing another thread to observe flag == true while a == 0:

class ReOrderDemo {
    int a = 0;
    boolean flag = false;

    public void write() {
        a = 1; //1
        flag = true; //2
    }

    public void read() {
        if (flag) { //3
            int i = a * a; //4
            // …
        }
    }
}

If thread A executes write() and thread B executes read() without synchronization, the value read for a is nondeterministic because the JMM does not guarantee ordering or visibility for these operations.

JMM Solutions

To guarantee atomicity, visibility, and ordering, the JMM provides:

Use synchronized or ReentrantLock for method‑level or block‑level atomicity.

Use synchronized or volatile to solve visibility problems caused by delayed synchronization between working memory and main memory.

Use volatile to prevent instruction reordering and ensure ordering as well as visibility.

The JMM also defines a set of happens‑before rules that together guarantee these properties without relying solely on synchronized or volatile.

Happens‑Before Principle

If only synchronized and volatile were used, writing correct concurrent code would be cumbersome. The JMM therefore introduces happens‑before rules, which serve as the basis for determining data races and thread safety.

Program order rule: actions earlier in a thread happen before later actions in the same thread.

Monitor lock rule: an unlock on a monitor happens before a subsequent lock on the same monitor.

Volatile variable rule: a write to a volatile variable happens before any later read of that variable.

Thread start rule: calling Thread.start() happens before any action in the started thread.

Thread join rule: a thread’s termination happens before a successful return from join().

Thread interruption rule: an interrupt call happens before the interrupted thread detects the interruption.

Finalizer rule: object construction completes before its finalize() method begins.

Transitivity: if A happens before B and B happens before C, then A happens before C.

Applying these rules to the earlier ReOrderDemo example shows that none of the eight rules apply, so the program is not thread‑safe and the read result is unpredictable.

Conclusion

The article introduced key JMM concepts—atomicity, visibility, ordering—and explained how synchronized, volatile, and the happens‑before principle work together to provide correct concurrent behavior in Java programs.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaconcurrencyorderingvolatileMemory ModelatomicityHappens-beforevisibility
Senior Brother's Insights
Written by

Senior Brother's Insights

A public account focused on workplace, career growth, team management, and self-improvement. The author is the writer of books including 'SpringBoot Technology Insider' and 'Drools 8 Rule Engine: Core Technology and Practice'.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.