Fundamentals 11 min read

Fundamentals of the Java Memory Model and Concurrency

This article explains the core concepts of the Java Memory Model, including atomicity, visibility, ordering, instruction reordering, sequential consistency, volatile semantics, lock mechanisms, happens‑before rules, and double‑checked locking for lazy initialization.

Full-Stack Internet Architecture
Full-Stack Internet Architecture
Full-Stack Internet Architecture
Fundamentals of the Java Memory Model and Concurrency

1. Basics of Java Memory Model

Two key issues in concurrent programming: how threads communicate and how they synchronize.

Thread communication mechanisms: shared memory and message passing; Java adopts a shared‑memory model.

Abstract structure of the Java Memory Model:

The Java Memory Model is built around three characteristics: atomicity, visibility, and ordering.

Atomicity: an operation cannot be interrupted by the CPU; it either completes fully or does not happen at all.

Visibility: when one thread modifies a shared variable, other threads can immediately see the change.

Ordering: program execution follows the order written in the source code.

2. Reordering

Overview: compilers and processors may reorder instructions to improve performance, but such reordering can produce results that differ from the programmer’s expectations, so mechanisms like volatile , synchronized , and locks are required to enforce correct synchronization.

Considerations:

What problems can reordering cause?

How should reordering be handled?

Operations without data dependencies may be reordered; this has no effect on single‑threaded code but can introduce hazards in multithreaded programs.

Three principles to obey when dealing with reordering:

1. Data Dependency

Definition: if two operations access the same variable and at least one is a write, a data‑dependency exists. The three categories are write‑after‑read, write‑after‑write, and read‑after‑write.

Compilers and processors must preserve the order of operations that have a data‑dependency.

Data dependency applies only within a single processor’s instruction stream and a single thread.

2. As‑if‑Serial Semantics

Meaning: regardless of any reordering performed by the compiler or processor, the result of a single‑threaded program must remain unchanged.

This semantics lets single‑thread programmers ignore reordering and memory‑visibility concerns.

3. Program Order Rule

4. Effects of Reordering

Overview: in a single‑threaded program, reordering of control‑dependent operations does not change the result (the reason as‑if‑serial semantics permits such reordering); however, in a multithreaded program, reordering of control‑dependent operations may alter the program’s behavior.

3. Sequential Consistency

Overview: sequential consistency is a theoretical reference model; both processor memory models and language memory models are designed with it as a reference.

Concept: a program’s execution result matches the result under a sequential‑consistency memory model.

1. Data Race and Sequential Consistency

2. Sequential Consistency Memory Model

Overview: it provides strong visibility guarantees but prevents many hardware or compiler optimizations; therefore, relaxed memory‑order models have been proposed.

It specifies two things:

1. All operations in a thread must be executed in program order.
2. (Regardless of synchronization) all threads must see a single total order of operations; each operation must be atomic and immediately visible to all threads.

JMM’s implementation principle: allow compiler and processor optimizations as long as correctly synchronized program results remain unchanged.

3. Sequential‑Consistency Effect of Synchronized Programs

4. Characteristics of Unsynchronized Programs

Java provides the volatile and synchronized keywords to guarantee ordering between threads.

4. Volatile Memory Semantics

Semantics:

Ensures visibility of a variable’s new value to all threads.

Prohibits instruction reordering involving the volatile variable.

Implementation:

Locks are the most important synchronization mechanism in Java concurrent programming.

5. Lock Memory Semantics

Make critical sections mutually exclusive.

When a lock is released, the releasing thread sends a signal to any thread acquiring the same lock.

6. final Memory Semantics

Describes memory visibility between operations involving final fields.

7. Happens‑Before

Overview:

Concept: “happens‑before”.

Java Memory Model defines eight rules that guarantee a happens‑before relationship:

1. Program order rule: within a single thread, earlier actions happen‑before later actions.
2. Monitor lock rule: an
unlock
operation happens‑before a subsequent
lock
on the same monitor.
3. Volatile variable rule: a write to a volatile variable happens‑before any subsequent read of that variable.
4. Thread start rule: a call to
Thread.start()
happens‑before any action in the started thread.
5. Thread termination rule: all actions in a thread happen‑before another thread detects its termination (e.g., via
join
).
6. Thread interruption rule: a call to
interrupt()
happens‑before the interrupted thread detects the interrupt.
7. Object finalization rule: the completion of an object’s constructor happens‑before its
finalize()
method begins.
8. Transitivity: if A happens‑before B and B happens‑before C, then A happens‑before C.

Relation to the JVM:

Note: a happens‑before relation does not require the first operation to execute before the second; it only requires the result of the first to be visible to the second.

Interpretation: each happens‑before rule corresponds to one or more compiler and processor reordering rules.

8. Double‑Checked Locking and Lazy Initialization

In Java multithreaded programs, lazy initialization reduces the overhead of class loading and object creation; double‑checked locking is a common technique for implementing lazy initialization.

Considerations:

Why is lazy initialization needed?

How is double‑checked locking implemented?

How does it relate to the memory model?

Author: LeeRuJun

Source: http://www.cnblogs.com/free-will/

Copyright statement: Content originates from the web and is owned by the original author. Reproduction requires retaining this notice and providing a link to the original article.

JavaconcurrencyvolatileMemory ModelLocksHappens-BeforeReordering
Full-Stack Internet Architecture
Written by

Full-Stack Internet Architecture

Introducing full-stack Internet architecture technologies centered on Java

0 followers
Reader feedback

How this landed with the community

login 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.