What negotiation resources should we have when interviewing with volatile keywords?

Time:2019-11-28

Find more exciting content in advance, please visit personal blog
Find more exciting content in advance, please visit personal blog
Find more exciting content in advance, please visit personal blog

Written in front

In visibility ordering, happens before is one of the principles of happens before: volatile variable rule

For the writing of a volatile domain, happens before will read the volatile domain in any subsequent time

It’s enough to understand this rule, but interviewers like to ask questions thoroughly. In order to understand the memory semantics and read-write semantics of volatile more thoroughly, to interview more information and get some bonus items, and to fill the hole left by the previous article as early as possible, so this article was born with embarrassment

Volatile variable rules of happens before

Do you remember the form below? (yes, you remember)

Can I reorder Second operation Second operation Second operation
First action Normal read / write Volatile read Volatile write
Normal read / write NO
Volatile read NO NO NO
Volatile write NO NO

The above table is JMM’s customized volatile reordering rules for compilers. How does JMM prohibit reordering? The answer isMemory barrier

Memory barriers / fences

It doesn’t matter whether you’ve heard the term or not. It’s very simple. Let’s see

In order to implement the memory semantics of volatile, the compiler inserts a memory barrier in the instruction sequence when generating bytecode to prohibit the reordering of specific types of processors

This sentence is a little abstract. Try to imagine that the memory barrier is a high wall. If there is a barrier between two variables, then they can’t exchange positions (reorder). Variables have read and write (store). When there are pre and post operations, JMM will roughly divide the memory barrier insertion strategies into four types:

  1. Insert a storestore barrier in front of each volatile write
  2. Insert a storeload barrier after each volatile write
  3. Insert a loadload barrier after each volatile read operation
  4. Insert a loadstore barrier after each volatile read operation

1 and 2 are graphically described and corresponding table rules are as follows:

What negotiation resources should we have when interviewing with volatile keywords?

3 and 4 are graphically described and corresponding table rules are as follows:

What negotiation resources should we have when interviewing with volatile keywords?

In fact, graph is also the embodiment of table content. It just tells you how the memory barrier prohibits the reordering of instructions, so you just need to remember the table content

The reading and writing of a program is usually not as simple as the above two situations. How do these barriers work together? In fact, it’s not difficult at all. We just need to bring these instructions into the table at the beginning of the article, and then splice the instructions according to the program order

Let’s look at a short procedure:

public class VolatileBarrierExample {

    private int a;
    private volatile int v1 = 1;
    private volatile int v2 = 2;

    void readAndWrite(){
        Int i = V1; // first volatile read
        Int j = V2; // second volatile read
        A = I + J; // normal write
        V1 = I + 1; // the first volatile write
        V2 = J * 2; // second volatile write
    }
}

This is how barrier instructions are brought into the program:

What negotiation resources should we have when interviewing with volatile keywords?

Let’s look at the above figure from several perspectives:

  1. Color is the whole content that the barrier instructions are brought into the program, that is, generated by the compiler“Safest”Scheme
  2. Obviously, there are many barriers that are redundant. The barrier pointed by the dotted box on the right can be“Optimization”Removed barriers

Here you should know how volatile ensures that programs are not “arbitrarily” sorted through the memory barrier. How does volatile ensure visibility?

Memory semantics of volatile write read

Review the program in the previous article. Suppose thread a executes the writer method first, and then thread B executes the reader method

public class ReorderExample {

    private int x = 0;
    private int y = 1;
    private volatile boolean flag = false;

    public void writer(){
        x = 42; //1
        y = 50; //2
        flag = true;    //3
    }

    public void reader(){
        if (flag){  //4
            System.out.println("x:" + x);   //5
            System.out.println("y:" + y);   //6
        }
    }
}

Do you still remember the JMM mentioned before? Yes, you still remember that when thread a executes the writer method, see the following figure:

What negotiation resources should we have when interviewing with volatile keywords?

Thread a writes local memory changed variables back to main memory

Memory semantics for volatile reads:

When reading a volatile variable, JMM will invalidate the local memory corresponding to the thread. The thread will then read the shared variable from main memory.

So when thread B executes the reader method, the graph structure becomes this way:

What negotiation resources should we have when interviewing with volatile keywords?

The local memory variable of thread B is invalid. Reading the variable from the main memory to the local memory will get the result after thread a changes. This is how volatile ensures visibility

If you have read the previous article, it is not difficult for you to understand the above two pictures. To sum up:

  1. Thread a writes a volatile variable, which is essentially a message sent by thread a to a thread that will read the volatile variable next
  2. Thread B reads a volatile variable. Essentially, thread B receives a message sent by a previous thread (modifying the shared variable before writing the volatile variable).
  3. Thread a writes a volatile variable, and then thread B reads the volatile variable. This process is essentially that thread a sends messages to thread B through main memory.

Here, when interviewing for volatile, you should have some conversation and have a deeper understanding of the semantics of volatile

Egg

The previous article mentioned the following sentence:

From the perspective of memory semantics, volatileWrite readLocksRelease getIt has the same memory effect; volatile write and lock release have the same memory semantics; volatile read and lock acquisition have the same memory semantics

Remember the last two figures in the article. When we talk about synchronized, you will suddenly understand the meaning of this sentence. If you are interested, you can first understand the write read semantics of synchronized

Next, we will talk about lock related content, please look forward to

Soul questioning

  1. If volatile returns directly after writing, will the storeload instruction be generated?
  2. How is synchronized optimized?

Efficiency tools

What negotiation resources should we have when interviewing with volatile keywords?

tool.lu

Https://tool.lu is an online tool integrated with many functions, which basically meets the needs of daily development

What negotiation resources should we have when interviewing with volatile keywords?


Recommended reading

  • Please don’t miss this time in the world of concurrency
  • To learn concurrent programming, a thorough understanding of these three cores is the key
  • There are three sources of concurrent bugs. Please open your eyes to see them
  • Visibility order, happens before
  • Solve the atomic problem? The first thing you need is a macro understanding

Welcome to continue to pay attention to the public address: “daily arch one soldier”.

  • Leading edge Java technology dry goods sharing
  • Summary of efficient tools and reply to tools
  • Interview question analysis and answer
  • Receive technical data and reply “data”

Learn knowledge about Java technology stack with ease and interest in reading detective stories, gradually decompose technical problems based on the principles of simplifying complex problems, concreting abstract problems and graphing, and keep updating technology. Please keep paying attention

What negotiation resources should we have when interviewing with volatile keywords?