Volatile variable, volatile
For volatile, I found a bunch of materials and looked at it. After reading it, I wanted to find a method for testing. I tested it for a long time and felt like I did not.
This book "a deep understanding of the Java Memory Model" provides a metaphor for the volatile description. The following Code shows that reading and writing to a is equivalent to synchronizing reading and writing to B.
Public volatile int a = 0; private int B = 0; public synchronized int getB () {return B;} public synchronized void setB (int B) {this. B = B ;}
That is to say, volatile only ensures synchronization between reading and writing. Each read operation gets the latest value, and each write operation overwrites the latest value.
This implies that the read/write of non-volatile variables is not the latest value, because each thread has its own independent memory to store copies of the variables, rather than reading the public memory variables immediately.
Now, the truth is clear. Next we will mainly look at the scenarios and conditions it uses.
The write value cannot depend on the read value. For example, a ++ is a "read first, calculate, and write later" step. The write value depends on the read value.
If it requires synchronization of reading and writing, and other synchronization operations, other synchronization operations will undoubtedly require the help of synchronized. If the frequency of reading and writing is much higher than that of other synchronous operations, you can use volatile and synchronized.
For other usage, please refer to this Article "correct use of Volatile variables". Today I will first understand this. If you have any in-depth knowledge, please share with me. Thank you.