Detailed explanation of volatile visibility

Detailed explanation of volatile visibility

Volatile is a lightweight synchronization mechanism provided by the java virtual machine with the following characteristics:

1.1. Ensure visibility

2.2. Atomicity is not guaranteed

1.3. Prohibition of order rearrangement

​ Next, let's look at the visibility characteristics of volatile and the explanation of the underlying principles. Before studying the underlying principles of volatile, we must first study a new knowledge-JMM. Well, this topic is not finished yet. , Brother Hou, why do you pull out a new knowledge point JMM? At this time, please follow the teacher’s requirements to study. Listen to a compulsory topic JVM on the interview questions in 17 and 18 last year or even the year before. This is a java virtual machine. As long as you are a java programmer, everyone on the earth knows it, but recently this For a year or two, because of the JVM problem, for example, if you say a word does not agree, let you draw a JVM memory diagram, everyone has learned it by heart, then the employer cannot pick the best java engineer, so he said the problem Upgrade, especially now that you are paying great attention to it. Did you work on a high-concurrency project or a stand-alone system in your last current company. If it is a high-concurrency system, there will naturally be frequent problems. In order to solve these problems, you have to study At the bottom level, when you study the bottom level, you will naturally come to a thing called JMM (java memory model), which is not a java virtual machine. Now major manufacturers will basically talk to you about JMM. If you don’t know, then there is no way you must not be too high. Concurrency, you must have never done JUC programming. You are the legendary programmer for adding, deleting, modifying, checking, and this is the same thing about your business. It's not that you can't find a job, but it is difficult to break through 18, 20 or even 25. We are going to chat about what is the Java memory model, and what does it have to do with our volatile? The first question is to talk about your understanding of volatile.

First of all, we have an in-depth analysis of JMM. Look at the text between the horizontal lines below, and simply read it through:


​ JMM (Java Memory Model, JMM for short) itself is an abstract concept and does not really exist . It describes a set of rules or specifications. Through this set of specifications, various variables in the program (including instance fields, static Fields and elements that make up the array object)

JMM regulations on synchronization:

1. Before the thread is unlocked, the value of the shared variable must be refreshed back to the main memory

2. Before the thread locks, it must read the latest value of the main memory to its own working memory

3. Locking and unlocking are the same lock

​ Because the entity of the JVM running program is a thread, and when each thread is created, the JVM will create a working memory for it (some places are called stack space). The working memory is the private data area of ​​each thread, and the Java memory model stipulates All variables are stored in the main memory, the main memory is a shared memory area, all threads can access, but the thread's operations on the variables (read assignment, etc.) must be performed in the working memory, first copy the variables from the main memory Go to your own working memory space, and then operate on the variables. After the operation is completed, the variables are written back to the main memory . You cannot directly manipulate the variables in the main memory. The working memory of each thread stores a copy of the variable copy of the main memory , so Different threads cannot access each other's working memory. The communication (passing values) between threads must be completed through the main memory. The brief access process is as follows:
Insert picture description here


​ Well, everyone read this paragraph through. OK, I believe that after reading it, you will either have a silly face or a silly face. Anyway, it is all in Chinese, and you can understand what is incomplete, and you can’t understand all the meaning, but You have to say that you don’t understand a bit, and you can feel a little bit of it. Then, at this time, look at everyone’s dumbfounded state, stop reading, the first time, the teacher’s request, the first time, and the third time, why? ? After reading this side, then I will tell you that assuming this is a book, I will prove to everyone why you have to learn from Brother Monkey now, why do you learn by yourself and become a master by reading books, that is impossible, no teacher will take it You, if you don’t hang around, then basically your growth is limited, OK, let’s start:

After reading the above text, several slightly obscure names appeared: main memory, own working memory

​ First of all, no matter how much the students understand, don’t read it. Let’s start, let’s solve the JMM model first. Okay, so first of all, we all understand that the rate of data transfer and storage in our work is basically In this way, it is hard disk<memory. Needless to say, our MySQL database is installed on the hard disk, but after the data storage needs to be accessed on a large scale, we all understand that the disk has a hardware that cannot be bypassed called IO, which is pure hardware. , It has its online and restrictions. After reaching a certain threshold, it is difficult to break through, unless it is a hardware breakthrough, good, but our data will not spare you because you store it on the hard disk, especially now In the era of big data, data reading, writing and storage are required to be fast. Finally, we understand the truth that some data should not be stored on the hard disk. Where? In the memory, it seems that one piece of hardware corresponds to one piece of software. What the hell is this memory? Then we have learned the distributed memory database Redis before. Everyone knows that the reading speed of memory is faster than that of hard disk? Okay, so what's faster than memory next? ? ? This is the time for the CPU. At this time, some students said: Ang, then I understand, it is a big mistake to store the data in the CPU. The CPU is responsible for the calculation and no matter the storage. Why at this time? There is a situation, assuming that the CPU is faster than the memory, then in the middle, during this period of time, the reading speed, the CPU's computing power is super strong, and the calculation is completed but the data cannot be shipped. Is the CPU just consuming? That won't work. This is the time we must understand that there is still a little space between the CPU and the memory to read the storage, then this space is the so-called cache.

If the CPU speed is greater than the memory, this is necessary. If the CPU has been idle, will it cause a decrease in CPU performance? After calculating a part of the data, let’s save it in the cache first, which can be abstractly understood as: First of all, our data is in the memory. Every student now has a memory stick in your memory slot, such as you The memory is 8G, which is a piece of hardware we plugged into the motherboard. Note: This hardware is commonly known as our main memory . Every new object of us generally exists in this main memory.

Insert picture description here

​ For example, we have a Student object age=25 in our main memory. We have only one copy of this object in physical memory. Then, in the era of high concurrency, multiple threads, just like we buy tickets, suppose we He has to change his age. Can you change this age in multiple threads? It's totally possible. So everyone, because the CPU is too fast, there are three threads in the cache; all of them need to operate age. Should they directly manipulate this object? ? ? surely not. First of all, each thread will copy the 25 in the main memory to its own thread. This is the working memory of the respective thread. That is to say, the thread needs to change, not directly modify the data in the main physical memory, but A copy of a thread variable, copy this variable 25 back to their respective work, that is, each of the three threads has a copy of 25, and then the first thread t1 changes 25 to 27, and the change is over, but There is no way between threads t2 and t3. I don’t know that t1 changes 25 to 37. Next, write the modified 37 back to the main memory in the t1 thread, but I’m sorry, at this time t2 and t3 don’t know The value of the main physical memory has been changed from 25 to 37. We must have a mechanism. As long as one thread modifies the value of its own work space and writes it back to the main memory, other threads must be notified in time. The situation is commonly known as the first important feature in the JMM memory model, commonly known as visibility . Can you understand? ? ? That is to say, after you modify the value in a thread and write it back to the main memory, another thread must immediately know that the 25 in my hand is no longer the latest value. It is invalid and needs to be returned to the main memory to get it. Can you understand the latest value? ? At this time, please follow the teacher to familiarize yourself with what is visibility? That is, one thread modifies the value of the main physical memory, and the value of the main physical memory is modified. Other threads will be notified immediately. Assuming that we need to add a class tonight, as long as Brother Hou tells the class teacher, is the class teacher in the WeChat group right away? Can everyone see and know that there will be additional classes tonight? Otherwise you may ask for leave tonight. In other words, as long as there is a change, everyone can see it immediately and receive the latest news immediately . This mechanism is called visibility .

OK, read it again at this time, the content between the horizontal lines, see what effect?

Code verification instructions for visibility:

package com.lagou.test;
import java.util.concurrent.TimeUnit;
class MyData{
    
        
    volatile int number = 0;    
    public void addTo60(){
    
            
        this.number = 60;    
    }
}
/**
  * 验证volatile的可见性 
  * 1.1 假如int number = 0 ; number变量之前根本没有添加volatile关键字修饰 
  */
public class VolatileDemo {
    
        
    public static void main(String[] args) {
    
    //main是一切方法的运行入口        
        MyData myData = new MyData();//资源类        
        new Thread(() ->{
    
                					
             System.out.println(
            	Thread.currentThread().getName()+"\t come in");            
         	//暂停一会儿线程            
             try {
    
    
                 TimeUnit.SECONDS.sleep(3);
             } catch (InterruptedException e) {
    
    
                 e.printStackTrace(); 
             }            
             myData.addTo60();            			       
             System.out.println(
                 Thread.currentThread().getName()+
                 "\t update number value:"+ myData.number); 
             },"AAA").start();        
        //第二个线程就是我们的main线程        
        while (myData.number == 0){
    
                
            //main线程就一直在这里等待,直到number值不再等于0        
        }        
        System.out.println(Thread.currentThread().getName()+
                           "\t mission is over, main get number value:"+myData.number);    
    }
}

explain:

If the number variable in the resource class MyData is not modified by volatile, the operation result:

Insert picture description here

If volatile modification is added, the operation result:

Insert picture description here

Because of the volatile modification, it has visibility. After the number is modified in the AAA thread, the main thread will be notified immediately. If the value of the number is changed to 60, the infinite loop will be exited and "main mission is over, main get number value" will be printed. :60"

Guess you like

Origin blog.csdn.net/weixin_44796239/article/details/108322955
Recommended