Volatile variable, volatile

Source: Internet
Author: User

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.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.