The understanding of volatile in Java

Source: Internet
Author: User

First we know that the memory model in Java

That is: Thread working memory--Main memory

Working memory is thread-private, and main memory is thread-shared

The initialization of the variable is generated in the main memory, and the working memory is loaded from the main memory only when the variable is used

Total of eight atomic operations, Read,load,use,assign,store,wirte,lock,unlock

The Java Virtual Machine specification does not allow a thread (which we call thread a) to discard its most recent assign operation, meaning that the variable (which we call X) needs to be synchronized to the main memory after it has been modified in working memory, but does not specify a synchronization time

Non-volatile variables are too easy to cause inconsistencies between threads, so don't give an example

So volatile must be able to achieve synchronization effect? Not necessarily, or most of the cases, cannot be

The JVM specification declares volatile variables with two attributes:

1. Immediate visibility after modification

2. Prohibition of command (assembly or level of machine instructions) rearrangement

The first article is about the read-write atomicity of the volatile variable, meaning that the volatile will be read&load before it is read and will store&wirte after writing.

So like X + + this operation, why not

Analysis:

X + + operations are actually

  • temp = x;
  • temp = temp + 1;
  • x = temp;

Here 1,3 are atomic operations, but the whole of the three-to-one is not an atomic operation, that is, the thread A, B, is performing x + + operations, the following may occur:

A:temp = x;

B:temp = x;

A:temp = temp + 1;

a:x = temp;

B:temp = temp + 1;

b:x = temp;

Above, there is a problem!

The understanding of volatile in Java

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.