Volatile variable understanding via "Java Concurrency Programming Combat"

Source: Internet
Author: User
Tags volatile

Chapter 3rd: Sharing of objects

    • The understanding of the volatile keyword

a volatile variable that is used to ensure that a variable's row action is notified to other threads. When a variable is declared as a volatile type, the compiler and the runtime will notice that the variable is shared, so the operation on that variable is not reordered with other memory operations. Volatile variables are not cached to registers or other processors where they are not visible, so the most recent write value is always returned when reading a variable of type volatile. The volatile keyword can be understood as a weak synchronization mechanism for Java (compared to synchronized). Volatile also guarantees the atomicity of 64-bit read/write operations. It is much more expensive to read volatile variables at the same time (not without an intuitive impression).

    • The difference between the locking mechanism (synchronized) and the volatile

The locking mechanism ensures that both visibility and atomicity are guaranteed, but volatile variables ensure visibility only.

    • Conditions for using volatile variables

The write to the variable does not depend on the current value of the variable (volatile does not guarantee the atomicity of the operation on that variable).

The variable is not included in the invariant condition.

No lock is required when accessing variables.

Volatile variable understanding via "Java Concurrency Programming Combat"

Related Article

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.