当前位置:网站首页>The picture shows you the relationship between volatile bottom layer and memory barrier

The picture shows you the relationship between volatile bottom layer and memory barrier

2020-12-07 09:07:48 Technical notes of little monkey

     Welcome to search “ Technical notes of little monkey ” Follow my public number , If you have any questions, you can communicate with me in time .

     To ensure the visibility of memory ,Java The compiler inserts memory barrier instructions at the appropriate locations in the generated instruction sequence to prevent certain types of processor reordering .JMM Divided by memory barrier instructions into 4 class (Load Express reading ,store Said to write ):

    LoadLoad Barriers: Insert a between two read instructions “LoadLoad” The memory barrier of , Make sure Load1 Data loading for , Precede Load2 Data loading for .

 Insert picture description here

    StoreStore Barriers: Insert a between two write instructions “StoreStore” The memory barrier of . Make sure Store1 First refresh the data to main memory , And the data is visible .Store1 Write data before Store2 Of writing data .  Insert picture description here

    LoadStore Barriers: Add a... Between the read and write instructions “LoadStore” barrier , Make sure Load1 Data loading of is prior to Store2 Of writing data .

 Insert picture description here

    StoreLoad Barriers: Add a word between writing and reading “StoreLoad” barrier , Make sure Store1 Data written to and flushed to memory prior to Load2.“StoreLoad” Will cause all memory access instructions before the barrier ( Storage and loading instructions ) When it's done , The memory access instructions after the barrier are executed . perform “StoreLoad” Barriers are expensive , Because the current processor usually flushes all the data in the write buffer into memory ( Small partners who don't understand the concept of write buffer , You can check out my last article 《 Why there is reordering ? What effect does it have on threads ?》).

 Insert picture description here

     If you have a knowledge of multithreading on your resume , Then the interviewer will most likely ask you volatile The problem with this keyword . Maybe you'll say ,volatile It solves the problem of memory visibility and prevents reordering . So do you know how it works at the bottom ?

     In order to achieve volatile Memory semantics of , When the compiler generates bytecode ,JMM Taking a conservative strategy will insert a memory barrier into the instruction sequence to prevent certain types of processor reordering .

    1. At every volatile Insert a... Before the write operation StoreStore barrier .

    2. At every volatile Insert a... After the write operation StoreLoad barrier .

    3. At every volatile Insert a... After the read operation LoadLoad barrier .

    4. At every volatile Insert a... After the read operation LoadStore barrier .

     The following figure will explain the relationship between the memory barrier of conservative strategy :  Insert picture description here

     Be careful : Aforementioned volatile Write and volatile The memory barrier insertion strategy for reading is very conservative . In fact, in actual execution , As long as it doesn't change volatile Write - Memory semantics of reading , The compiler can omit unnecessary barriers according to the specific situation . For example, the following example :

public class VolatileBarriersExample {
    int a;
    volatile int v1 = 1;
    volatile int v2 = 2;
    void readAndWrite() {
        //  first volatile read 
        int i = v1;
        //  the second volatile read 
        int j = v2;
        //  Common writing 
        a = i + j;
        //  first volatile Write 
        v1 = i + 1;
        //  the second volatile Write 
        v2 = j * 2;
    }
}

 Insert picture description here

     Be careful , final StoreLoad Barriers cannot be omitted , Because the second one volatile After writing , Method returns immediately . At this time, the compiler can not accurately determine whether there will be volatile Read or write . For safety's sake , The compiler usually inserts a StoreLoad barrier . Actually ,volatile Forbidding instruction reordering is implemented by using memory barrier as guarantee .

     understand volatile After the implementation of the underlying memory barrier , Let's take a look at one volatile When reading and writing variables , Changes in local memory and main memory where the shared variable is located ( It's about memory visibility ):

public class VolatileExample {
    int a = 0;
    volatile boolean flag = false;
    public void writer() {
        //  First step 
        a = 1;
        //  The second step 
        flag = true;
    }
    public void reader() {
        //  The third step 
        if (flag) {
            //  Step four 
            int i = a;
            System.out.println(i);
        }
    }
}

     Assuming that thread A First of all, I carried out writer() Method , Subsequent threads B perform reader() Method , that A The state diagram of shared variables after thread execution is as follows :

 Insert picture description here

     Conclusion : When you write a volatile variable ,JMM The shared variable values in the local memory corresponding to the thread will be refreshed to the main memory .  Insert picture description here

     Conclusion : When reading a volatile variable ,JMM The local memory for this thread is set to invalid . The thread will then read the shared variables from main memory .

     So we can draw a conclusion :volatile Memory visibility is if a thread modifies a shared variable , Then the shared variable will be immediately refreshed to main memory . meanwhile , Another thread holding the shared variable will be notified , Tell it that the shared variable has been modified , Stop using variable values in your working memory , Go to the main memory and retrieve it again .

     in general :volatile Memory barrier is used to prevent reordering of instructions , Use to refresh main memory , Notify other threads that shared variables in working memory are invalid , Make other threads force the main memory to get the latest value to ensure that , By volatile Memory visibility of decorated variables .

 Insert picture description here

版权声明
本文为[Technical notes of little monkey]所创,转载请带上原文链接,感谢
https://chowdera.com/2020/12/20201207090323688a.html