Java vloatile Keywords

Source: Internet
Author: User

The use of the volatile keyword in Java involves the Java memory model, JMM. Simply put, each thread has a local memory (virtual), and the thread-shared variables are stored in main memory, and the heap is present in the master. The memory access method is as shown.

The effect of volatile is summarized as follows:

(1) Visibility: Reading a volatile variable will always be able to see (any thread) the last write to the variable, which is able to read the most recent value.

(2) Atomicity: Read/write C operations for Vloatile variables are atomic, but composite operations are not atomic.

The operation procedure described in the above diagram

(1) Thread A writes: The value of n is updated in thread A, the value of flag, the update to n is only in local memory, but after the flag is written, flag is volatile, causing the two shared variables in local memory A to be updated by thread A to be flushed into main memory. This ensures that the most recent write value of the volatile variable is kept in main memory.

(2) thread B reads: When thread B reads a variable of type volatile, JMM will place the local memory as invalid, and the thread will then read the shared variable from main memory. This guarantees that the most recent value in main memory is read.

Java vloatile Keywords

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.