Special rules for in-depth understanding of Java Virtual Machine notes---volatile variables

Source: Internet
Author: User

When a variable is defined as volatile, it will have two features: the first is to ensure that the variable is visible to all threads, where the "visibility" means that when a thread modifies the value of the variable, the new value is immediately known to other threads, and the value of the variable is passed through the main memory. For example, if thread a modifies the value of an ordinary variable and then writes back to the main memory, and the other thread, B, finishes a write-back, and then reads from main memory, the value of the new variable is visible to thread B.
With regard to the visibility of volatile variables, many people mistakenly assume that the following description is true: "volatile is immediately visible to all threads, and all writes to volatile variables are immediately returned to other threads, in other words, the volatile variable is consistent across threads, Therefore, the operation based on volatile variables is safe in concurrency. " There is nothing wrong with the argument in this sentence, but the argument does not come to the conclusion that "based on volatile variables, operations are safe in concurrency." The volatile variable does not have a consistency problem in the working memory of each thread (the volatile variable can also be inconsistent in the working memory of each thread, but because it is refreshed before each use, the execution engine does not see the situation, so there is no consistency problem). But the operation in Java is not atomic, and the operation of the volatile variable is as insecure as it is in concurrency.

Because volatile variables can only guarantee visibility, it is still necessary to lock to ensure atomicity in the scenario where the following conditional rules are not met.
1. The result of the operation does not depend on the current value of the variable, or can ensure that only a single thread changes the value of the variable.
2. Variables do not need to participate in invariant constraints with other state variables.

The second semantics of using a volatile variable is to suppress the order reordering optimization, which only guarantees that the correct result is obtained in all dependent places of the execution of the method, without guaranteeing that the order of the variable's assignment is consistent with the order of execution in the program code. Because this is not perceptible during the execution of a method of a thread, this is the so-called "line range that behaves as a serial semantics" described in the Java memory model (Within-thread as-if-serial sematics).


Map configoptions;char[] configtext;//This variable must be defined as Volatilevolatile boolean initialized = false;//assume that the following code executes//emulates read configuration information in thread a , when the read is complete//set initialized to True to notify other threads that the configuration is available configoptions = new HashMap (); configtext = Readconfigfile (fileName); Processconfigoptions (Configtext, configoptions); initialized = true;//assume that the following code is executed in thread B//And such threads a waits for initialized to True, Represents that thread A has initialized configuration information to completion while (!initialized) {sleep ();} Use the configuration information initialized in thread a dosomethingwithconfig ();


The above is a pseudo-code, which describes the scene is very common, but we do not normally occur when processing the configuration file concurrency. If the initialized variable is defined without the use of a volatile modifier, it is possible that the code "initialized = True" in the last sentence of thread A is executed in advance because of the optimization of the command reordering, so that code that uses configuration information in threads B may have errors , and the volatile keyword avoids the occurrence of such situations.
Special rules for defining volatile variables in the Java memory model. Assuming that T represents a thread, and V and W represent two volatile variables respectively, the following rules are required for the read, load, use, assign, store, write operations:
1. The thread t can perform the use action on the variable v only if the previous action of the thread T on the variable v is load, and the thread T can perform the load operation on the variable v only if the latter action of the thread T is performed on the variable v. The use of the thread T on the variable v can be considered to be associated with the load and read operations of the variable V for the thread T, and must appear consecutively. This rule requires that in working memory, the latest value must be refreshed from main memory before each use of the variable V to ensure that the modified values of the variable v are visible to other threads.
2. The thread T can perform a store operation on the variable v only if the previous action of the thread T on the variable v is assign, and the thread T can perform a assign operation on the variable v only if the latter of the thread T executes on the variable v is the store operation. The assign operation of the thread t to the variable v can be considered to be associated with the store and write operations of the variable V for the thread T, and must appear consecutively. This rule requires that in working memory, each change to V must be immediately synchronized back to main memory to ensure that other threads can see their own modifications to the variable v.
3. Assume that action A is a use or assign action on a variable v implemented by a thread t, assuming that operation F is the load or store operation associated with Operation A, assuming that the operation P is the read or write operation of the variable v corresponding to the operation F; type, Assuming that action B is the use or assign action of the thread T to the variable w, it is assumed that operation G is the load or store operation associated with Operation B, assuming that the operation Q is a read or write operation to the variable v corresponding to the Operation G. If a precedes B, then p is preceded by Q. This rule requires that variables modified by Valitile are not optimized by instruction reordering, ensuring that the code executes in the same order as the program.

Special rules for in-depth understanding of Java Virtual Machine notes---volatile variables

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.