search
HomeJavajavaTutorial[Fighting Java Concurrency]-----Analysis of Java Memory Model Volatile

The previous blog [Fuck Java Concurrency] - In-depth analysis of the implementation principle of volatile has already explained the characteristics of volatile:

  1. volatile visibility; for a For volatile reads, you can always see the final write to this variable;

  2. volatile atomicity; volatile is atomic for a single read/write (32-bit Long, Double), but composite Except for operations, such as i++;

  3. The bottom layer of JVM uses "memory barrier" to implement volatile semantics

The following LZ uses the happens-before principle and The memory semantics of volatile introduce volatile in two directions.

volatile and happens-before

In this blog [Fuck Java Concurrency] - Java Memory Model Happend-Before, LZ explains that happens-before is used to determine whether to store data. The main basis for competition and thread safety, which ensures visibility in a multi-threaded environment. Let's take the classic example to analyze the happens-before relationship established by reading and writing volatile variables.

public class VolatileTest {

    int i = 0;    volatile boolean flag = false;    //Thread A
    public void write(){
        i = 2;              //1
        flag = true;        //2
    }    //Thread B
    public void read(){        if(flag){                                   //3
            System.out.println("---i = " + i);      //4
        }
    }
}

According to the happens-before principle, the following relationship is obtained for the above program:

  • According to the happens-before program sequence principle: 1 happens-before 2, 3 happens-before 4;

  • According to the volatile principle of happens-before: 2 happens-before 3;

  • According to the transitivity of happens-before: 1 happens -before 4

Operation 1 and operation 4 have a happens-before relationship, so 1 must be visible to 4. Some students may ask, operation 1 and operation 2 may be reordered, is it possible? If you have read LZ's blog, you will understand that in addition to ensuring visibility, volatile also prohibits reordering. Therefore, all shared variables visible to thread A before writing the volatile variable will become visible to thread B immediately after thread B reads the same volatile variable.

volataile's memory semantics and its implementation

In JMM, communication between threads is implemented using shared memory. The memory semantics of volatile are:

When writing a volatile variable, JMM will immediately refresh the shared variable value in the local memory corresponding to the thread to the main memory.
When reading a volatile variable, JMM will set the local memory corresponding to the thread to invalid and read the shared variable directly from the main memory.

So the write memory semantics of volatile are directly refreshed to the main memory. , the memory semantics of reading is to read directly from main memory.
So how are volatile memory semantics implemented? For general variables, they will be reordered, but for volatile variables, they will not be reordered. This will affect its memory semantics, so in order to achieve volatile memory semantics, JMM will limit reordering. The reordering rules are as follows:

The translation is as follows:

  1. If the first operation is a volatile read, no matter what the second operation is, it cannot be reordered. This operation ensures that operations after the volatile read will not be reordered by the compiler to before the volatile read;

  2. When the second operation is a volatile write, no matter what the first operation is, Neither can be reordered. This operation ensures that operations before volatile write will not be reordered by the compiler to after volatile write;

  3. When the first operation is volatile write and the second operation is volatile read, it cannot be reordered. .

The underlying implementation of volatile is by inserting memory barriers, but it is almost impossible for the compiler to find an optimal arrangement that minimizes the total number of inserted memory barriers, so, JMM adopts a conservative strategy. As follows:

  • Insert a StoreStore barrier before each volatile write operation

  • Insert a StoreLoad barrier after each volatile write operation

  • Insert a LoadLoad barrier after each volatile read operation

  • Insert a LoadStore barrier after each volatile read operation

StoreStore barrier can ensure that all ordinary write operations in front of it have been flushed to main memory before volatile writing.

The function of the StoreLoad barrier is to prevent volatile writes from being reordered by subsequent volatile read/write operations.

The LoadLoad barrier is used to prevent the processor from reordering the volatile read above and the normal read below.

The LoadStore barrier is used to prevent the processor from reordering volatile reads above and ordinary writes below.

Let’s analyze the VolatileTest example above:

public class VolatileTest {
    int i = 0;    
    volatile boolean flag = false;    
    public void write(){
        i = 2;
        flag = true;
    }    public void read(){        
    if(flag){
            System.out.println("---i = " + i); 
        }
    }
}

[Fighting Java Concurrency]-----Analysis of Java Memory Model Volatile

The memory barrier legend of the volatile instruction is slightly demonstrated through an example.

volatile's memory barrier insertion strategy is very conservative. In fact, in practice, as long as the volatile write-read memory semantics are not changed, the compiler can optimize according to the specific situation and omit unnecessary barriers. As follows (excerpted from Fang Tengfei's "The Art of Java Concurrent Programming"):

public class VolatileBarrierExample {
    int a = 0;    
    volatile int v1 = 1;    
    volatile int v2 = 2;    
    void readAndWrite(){        
    int i = v1;     //volatile读
        int j = v2;     //volatile读
        a = i + j;      //普通读
        v1 = i + 1;     //volatile写
        v2 = j * 2;     //volatile写
    }
}

The sample diagram without optimization is as follows:

[Fighting Java Concurrency]-----Analysis of Java Memory Model Volatile

Let's analyze what is in the above picture The memory barrier instruction is redundant

1: This must be retained

2: All normal writes below are prohibited from being reordered with the volatile reads above. However, due to the existence of a second volatile read, the normal read cannot bypass the second volatile read at all. So it can be omitted.

3: There is no ordinary reading below and can be omitted.

4: Reserved

5: Reserved

6: Followed by a volatile write, So

7 can be omitted: keep

8: keep

so 2, 3, and 6 can be omitted, the schematic diagram As follows:

[Fighting Java Concurrency]-----Analysis of Java Memory Model Volatile


## The above is the content of [Java Concurrency]-----Analysis of Java Memory Model Volatile, more For related content, please pay attention to the PHP Chinese website (www.php.cn)!



Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor