Java thousand ask _03 Basic grammar (014) _volatile keyword What's the use

Source: Internet
Author: User
Tags volatile

Click to enter _ more _java thousand ask

1. What is the use of volatile keywords

Volatile is a keyword in the Java language and is a variable modifier. It is designed to modify variables that are accessed and modified by different threads.

The role of volatile is to ensure that this directive is not optimized by the compiler as an instruction keyword, and that all threads applied to read the variable have the same value.

Simply put, the compiler is prevented from optimizing the code, forcing all threads to read the variable from shared memory (instead of reading the backup in the register), and forcing the variable to be stored in shared memory when it changes.

The Java memory model requires the following rules: Atomicity (atomicity), Visibility (Visibility), and sortable (ordering).
Variables modified with volatile will have visibility and do not allow internal caching and reordering of threads, but it cannot make variables atomic.

Learn about the Java memory model look here: What is the Java memory model
In the current era of multi-threaded use, it is not recommended to use this low-reliability, and the developer or the scenario requires a high level of multi-threaded operation, because volatile is easy to be misused for atomic operations, if used improperly will be wrong frequency.

Java thousand ask _03 Basic grammar (014) _volatile keyword What's the use

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.