Introduction to volatile variables of Java concurrent programming _java

Source: Internet
Author: User

Volatile provides a weak synchronization mechanism to ensure that variable updates are notified to other threads. Volatile variables are not cached in registers or are not visible to other processors, and therefore always return the most recently written value when reading volatile variables. The following semantics can be imagined, but volatile is a more lightweight synchronization mechanism. Volatile only ensures visibility, but does not guarantee atomicity. This means that volatile variables, such as i++, cannot be used in a composite operation.

Copy Code code as follows:

Public synchronized void SetValue (int value) {

This.value = value;

}
public synchronized int GetValue () {

return value;

}


You can use the volatile variable when all of the following conditions are true
1. Write operations on variables do not depend on the current value of the variable, or you can ensure that only a single thread updates the value of the variable.
2. This variable does not incorporate invariant conditions with other state variables
3. The access variable is not required to lock

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.