Java Volatile keyword Introduction

Source: Internet
Author: User
Volatile decorated member variables are forced to reread the value of the member variable from shared memory each time it is accessed by the thread.

also, when a member variable changes, the thread is forced to write the change value back to the shared memory.

so at any given moment, two different threads always see the same value for a member variable.

The Java language Specification states that in order to achieve optimal speed, the thread is allowed to save private copies of shared member variables, and only when a thread enters or leaves a synchronized code block, it is compared to the original value of the shared member variable. This way, when multiple threads interact with an object at the same time, it is important to notice that the thread gets the change in the shared member variable in a timely manner.

The volatile keyword is the hint VM: You cannot save its private copy for this member variable, but you should interact directly with the shared member variable.

Recommendation: Use volatile on member variables accessed by two or more threads. You do not have to use when the variable you want to access is already in a synchronized code block, or it is a constant. Because using volatile masks the necessary code optimizations in the VM, it is less efficient, so use this keyword when necessary.

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.