Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is volatile?

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

The main content of this article is to explain "what is volatile". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn what volatile is.

I have nothing to do today and have a chat with my colleague, Uncle Mac.

SoWhat: uncle Mai heard that you secretly met Ali. How was your face?

Uncle wheat: on the one hand, it was very simple. I mainly asked some basic data structures and algorithms, and also asked the ten common basic questions of HashMap. I have all the answers, but also asked me the JDK7 ring, thanks to your HashMap ring drawing is good, I answered well, let me prepare the second side.

SoWhat: two-sided class?

Uncle wheat: the second side asked me some questions about JVM, asked me about my understanding of the JVM memory model, and the common understanding of GC, and finally asked me about the loading mechanism of the lower class. I see that you have been in this JVM series before, so you have answered it according to the gourd painting, so let me prepare three sides.

SoWhat: uncle Mak is fine with this wave. What are the three-sided questions?

Uncle Mac: he asked me about the underlying implementations of CAS, Lock, AQS and ConcurrentHashMap. He also asked me about the seven parameters and four rejection strategies of the downthread pool, as well as points for attention. I see that you have been through the concurrent programming series, so you have answered it.

Sowhat: impressive! this is the rhythm you have to pass!

Uncle Mac: after a hammer, the director on three sides finally asked me about my basic principle of volatile. Damn you, I answered some basic visibility and weak atomicity, and then I felt that the interviewer was not satisfied.

Sowhat: well, I'll hurry up and write down another one about the use of volatile.

Use

I believe you all know that the volatile variable itself has the following characteristics:

Visibility. When reading a volatile variable, you can always see (any thread) the last write to the volatile variable.

Atomicity: reading / writing to any single volatile variable is atomic, but composite operations like volatile++ are not atomic.

The second point can be understood as regarding a single read / write to a volatile variable as synchronizing these individual read / write operations using the same lock, similar to the SoWhat and SynSoWhat functions below.

Class SoWhat {volatile int i = 0; / volatile-modified variable public int getI () {return iPlacabash / read of a single volatile variable} public void setI (int j) {this.i = j; / / Writing of a single volatile variable} public void inc () {int I = 0 volatile synchronized int getI () {return I } public synchronized void setI (int j) {this.i = j;} public void inc () {/ / ordinary method call int tmp = getI (); / / call synchronized method tmp = tmp + 1 tmp / ordinary write method setI (tmp); / / call synchronized method}} write understanding

The memory semantics written by volatile are as follows:

When you write a volatile variable, JMM flushes the value of the shared variable locally corresponding to the thread to main memory.

Public class VolaSemanteme {int a = 0 flag volatile boolean flag = false; / / this is the key point. Public void init () {a = 1; flag = true; / /.} public void use () {if (flag) {int I = a * a } / /.}}

Thread A calls the init method, and thread B calls the use method.

Reading comprehension

The memory semantics of volatile reads are as follows:

When reading a volatile variable, JMM sets the local memory for that thread to be invalid. The thread then reads the shared variable from the main memory.

Public class VolaSemanteme {int a = 0 flag volatile boolean flag = false; / / this is the key point. Public void init () {a = 1; flag = true; / /.} public void use () {if (flag) {int I = a * a } / /.}}

The flowchart looks something like this:

Volatile instruction rearrangement

The memory visibility of volatile variables is based on the memory barrier (Memory Barrier). The specific explanation of the memory barrier has been written before and will not be repeated. JMM is forced to be invisible here. To sum up, there will be instruction rearrangement within JMM, and there will be af-if-serial and happen-before concepts to ensure the correctness of instruction replay. The memory barrier forbids instruction rearrangement based on four assembly-level keywords, and the replay rules for volatile are as follows:

When the first is a read operation, the second any operation cannot be reordered before the first.

When the second is a write operation, the first any operation cannot be reordered after the second.

When the first is a write operation, the second read and write operation does not run a reorder.

Volatile writes the underlying implementation

Memory Barrier insertion Strategy of JMM to volatile

Insert a StoreStore barrier in front of each volatile write operation. Insert a StoreLoad barrier after each volatile write operation.

Volatile read bottom layer

Memory Barrier insertion Strategy of JMM to volatile

Insert a LoadLoad barrier after each volatile read operation. Insert a LoadStore barrier after each volatile read operation.

One of the key points is why volatile is followed by a LoadLoad. Join me to have the following code AB two threads to execute, thread B's flag to get the following read ahead of time.

The realization principle of volatile

Shared variables decorated with volatile variables use the Lock prefix instruction provided by CPU when writing. The functions at the CPU level are as follows:

Writes the data of the current processor cache row back to system memory

This write-back operation will tell you to re-share the memory the next time you use it when the variables you get are invalid in other CPU.

We can disassemble the simple code in detail through jitwatch.

Package com.sowhat.demo;public class VolaSemanteme {int unvloatileVal = 0x volatile boolean flag = false;public void init () {unvloatileVal = 1BoFlag = true; / / Line 9} public void use () {if (flag) {int LocalA = unvloatileVal;if (LocalA = = 0) {throw new RuntimeException ("error");}} public static void main (String [] args) {VolaSemanteme volaSemanteme = new VolaSemanteme () VolaSemanteme.init (); volaSemanteme.use ();}}

Assignment to a normal variable:

The assignment operation to the volatile variable.

By comparison, volatile-decorated variables do have an extra lock addl $0x0, (% rsp) instruction.

0x0000000114ce95cb: lock addl $0x0, (% rsp); * putfield flag;-com.sowhat.demo.VolaSemanteme::init@7 (line 9) so far, I believe you have a better understanding of "what volatile is". You might as well do it in practice! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report