Table of Contents
volatile and happens-before
volataile's memory semantics and its implementation
Home Java javaTutorial [Fighting Java Concurrency]-----Analysis of Java Memory Model Volatile

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

Feb 24, 2017 am 10:07 AM
java volatile memory model

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
        }
    }
}
Copy after login

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); 
        }
    }
}
Copy after login

[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写
    }
}
Copy after login

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 of this Website
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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

See all articles