Java volatile keyword implementation principle

Scene introducing the visibility problem

First look at a map:

The above chart is a simplified version of Java memory model, a thread has its own working memory, as well as a shared main memory.

When the thread 1 and thread 2 reads data data, starting with the main memory load value data variables into the working memory before you can use that value.

Suppose now that thread 1 revised data variable is 1, then this write changes to their working memory. Then the working memory at this time, the thread 1 in the data value 1, or 0 and the value of the data in the main memory. Working memory data value of the thread 2 is also zero.

This is embarrassing, thread 1 and thread 2 is operated with a variable data, but because of thread local cache, resulting in one pair of data to modify the thread variable, Thread 2 can not be seen in time.

This is Java Concurrency in the visibility of the problem : When a thread modifies the value of a shared variable, other threads can immediately know whether this modification.

It is worth noting that the above Java memory model is extremely simplified, the real situation is far more complicated it.

The principle and the role of volatile

To solve the above problems visibility, we can use the volatile keyword.

After adding the volatile keyword, threads 1 modify data as long as the value of the variable, it will at the same time to modify the working memory data variable values, forced to modify flushed to main memory. While at the same time, thread 2 needs to read data variables to force a refresh of the value of main memory into the working memory, thus ensuring Thread 2 every time the value of the latest reading. As shown below:

volatile working principle described above, in which the principle underlying JVM implementation involves concepts memory barrier . In simple terms, JVM in the face volatile time variables, insert a store barrier after its write operation, insert a load barrier before it is read.

Guess you like

Origin www.cnblogs.com/bluemilk/p/11269505.html