[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:
volatile visibility; for a For volatile reads, you can always see the final write to this variable;
volatile atomicity; volatile is atomic for a single read/write (32-bit Long, Double), but composite Except for operations, such as i++;
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:
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;
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;
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); } } }
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:
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:

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

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

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

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

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.
