What does volatile in Java mean

Source: Internet
Author: User

The volatile modifier in Java is a special mechanism for ensuring the interaction between different threads. When One thread modifies a volatile variable, another thread can see the change. The first thread notifies the second thread that a variable has been modified.

This is explained in the following diagram:

Ready is a volatile Boolean variable with the initial value set to False. Answer is a non-volatile int variable with an initial value of 0.

The first thread prepares to modify the ready variable, which is the sender of two threads of communication. The second thread reads the ready variable, gets the value modified by the first thread, and therefore it is the receiver. When thread 1 modifies the ready variable in two threads, all variables in memory are visible to thread 1, and thread 2 is prepared to read the value of the prepare variable to true, all variables in memory must be visible to threads 2.

This ensures that if a thread is to output something, it is 42.

If ready is not volatile, what will happen? There will be no noticeable communication between thread 1 and Threads 2.

Thread 1 modifies the value after ready (now Non-volatile) may be passed to thread 2, so the thread may be able to read the value of ready to true. However, thread 1 may not pass the modified ready value to thread 2,answer's value or to thread 2, then thread 2 will output 0.

Resources:

Http://jeremymanson.blogspot.jp/2008/11/what-volatile-means-in-java.html

What does volatile in Java mean

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.