Special rules for volatile variable types
Volatile is the most lightweight synchronization mechanism provided by a Java virtual machine, and when a variable is defined as volatile, it will have two features, the first of which is to ensure that the variable is visible to all threads, where "visibility" means that when a thread changes the value of the variable, The new value is immediately known to other threads, and the second semantics is to prohibit the reordering of commands, and ordinary variables only guarantee that the correct results will be obtained in the execution of the method, with all dependent on the result of the assignment, without guaranteeing that the order of the variable assignment is consistent with the order of execution in the program code.
A description often misunderstood by developers: "Volatile variables are immediately visible to all threads, and write operations on volatile variables can immediately react to other threads, in other words, volatile variables are 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 cannot be drawn to the conclusion that operations based on volatile variables are safe in concurrency. Volatile variables do not have a consistency problem in the working memory of each thread, but the operation in Java is not atomic, and the operation of the volatile variable is as unsafe as concurrency. Like the following code:
12 |
volatile int race =0; race++ |
We know that race++ this operation is not an atomic operation, it will be compiled into a number of bytecode instructions, so the multi-threaded calculation will appear when the results do not meet the expected situation.
Since volatile variables can only guarantee visibility, we still need to lock to ensure atomicity in an operation scenario that does not conform to the following two rules:
- 1) The result of the operation does not depend on the current value of the variable, or can ensure that only a single thread modifies the value of the variable
- 2) variables do not need to participate in invariant constraints with other state variables
12345678910111213141516 |
Map configoptions;char[] Configtext;volatile boolean initialized = false;//assume the following code executes//analog 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; Suppose the following code executes while (!initialized) {sleep () in thread B;} Dosomethingwithconfig (); |
The code above is a pseudo-code, and the scenarios described are very common, except that we generally do not have concurrency when working with configuration files. If you do not use the volatile modifier when defining a initialized variable, 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 an error. The volatile keyword avoids the occurrence of such situations.
Then look at the special rules for volatile variables defined in the Java memory model, assuming that T represents a thread, and V and W represent two volatile variables respectively, then in the Read,load,use,assign, The following rules are required for store and write operations:
- 1) the thread T performs the use action on the variable v only if the previous action of the thread t to the variable v is load, and the thread T executes the load action on the variable v only if the last action that the thread T performs on the variable V is use. The use action of the thread T on the variable v can be considered to be associated with the load and read actions of the variable V for the thread T, and must appear consecutively. (This rule requires that in working memory, the most recent value must be refreshed from main memory before each use of V to ensure that the modified values of the variable v are visible to other threads)
- 2) thread T performs a store action on the variable v only if the previous action of the thread T on the variable v is assign, and the thread T performs a assign action on the variable v only if the last action that the thread T performs on the variable V is store. The Assign action of the thread t to the variable v can be considered to be associated with the store and write actions of the variable V for the thread T, and must appear consecutively. (This rule requires that in working memory, it must be synchronized back to main memory every time the V is modified 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 action F is a load or store action associated with a, assuming that the action P is a read or write action corresponding to the variable V of the action F; Assuming that action B is the use or assign action of the thread T to the variable W, the action G is assumed to be the load or store action associated with B, assuming that the action Q is the read or write action of the corresponding V to the action G. If a precedes B, then p is preceded by Q (This rule requires that volatile-modified variables are not ordered to be re-sorted by instructions, ensuring that the code executes in the same order as the program)
Atomicity, visibility, and ordering
- 1) atomicity
The atomic variable operations that are guaranteed directly by the Java memory model include the Read,load,use,assign,store,write 6, and we can roughly assume that the access read and write of the basic data type is atomic (except long and double).
If a wider range of atomicity guarantees is required, the Java memory model also provides lock and unlock operations to meet this requirement, and the corresponding bytecode directives are monitorenter and monitorexit, corresponding to the Java code, which is synchronized, However, refer to the Java Virtual Machine specification and the Java language Specification for instructions on how the Moniorenter and monitorexit directives correspond to the lock and unlock operations.
- 2) Visibility
Visibility is when a thread modifies the value of a variable-shared variable, and other threads can immediately know the change.
Volatile guarantees the visibility of variables during multi-threaded operations.
Synchronized and final are also visible, and the visibility of the synchronization block is obtained by synchronizing the variable back to the main memory before performing a unlock operation on a variable. The final keyword visibility means that the final field's value can be seen in other threads once it is initialized in the constructor and the constructor does not pass a reference to "this". (This refers to escaping is a very dangerous thing, other threads may have access to initialize the "half-initialized" object)
- 3) Order
The natural ordering of Java programs can be summed up in one sentence: If you look inside this thread, all operations are orderly, and if you look at another thread in a thread, all operations are unordered. The first half of the sentence refers to the "line range expression as a serial semantics", the latter sentence refers to the "order reordering" phenomenon and "working memory and main memory synchronization delay" phenomenon.
The Java language provides volatile and synchronized two keywords to ensure the ordering of operations between threads.
Principle of antecedent occurrence (Happen-before)
The first occurrence is a partial-order relationship between two operations defined in the Java memory model, and if operation a precedes operation B, it is said that the effect of operation A can be observed by Operation B before Operation B, "Impact" includes modifying the values of shared variables in memory, sending messages, calling methods, etc.
The "natural" antecedent in the Java memory model:
- 1) Procedural Order rules (Program order rule)
Within the same thread, the code in the program is written in the preceding operation first, which is written in the following line. Precisely, because it is the control flow order rather than the program code order, because the branch, loop and other structures to consider.
- 2) Tube Lock rule (Monitor lock rules)
The unlock operation of a lock occurs before the lock operation that faces the same lock. It must be emphasized that the same lock, where the "back" refers to the chronological order. That is, if a lock is already locked, then only the other thread can lock the lock after it is unlock. In the code, if it is a synchronization method, if a thread has entered the synchronization method, only if the thread exits the synchronization method (unlock operation), the other thread can enter the synchronization method.
- 3) volatile variable rules (volatile Variable rule)
The write operation of a volatile variable takes precedence over the reading of the variable, and the "back" here also refers to the chronological order. That is, when a thread writes a value to a volatile variable, it can be read by another thread immediately.
- 4) Thread-start rules (thread start rule)
The start method of the Thread object takes precedence over each action of this thread.
- 5) thread termination rules (thread termination rule)
All operations in the thread occur first in the termination detection of this thread, and we can detect whether the thread has been terminated by means of the Thread.Join () method end, the return value of thread.isalive (), and so on.
- 6) Thread break rules (thread interruption rule)
The invocation of the thread interrupt () method first occurs when the code of the interrupted thread detects that the interrupt event occurred, and can be detected by the thread.interrupted () method.
- 7) object Finalization rule (Finalizer rule)
The initialization of an object (the end of the execution of the constructor) occurs first at the beginning of its finalize () method.
- 8) transitivity (transitivity)
If the operation a first occurs in operation B, Operation B first occurs in Operation C, it can be concluded that the operation a precedes operation C.
Among them, procedural order rules, tube lock rules, volatile variable rules, transitive rules are often used to infer antecedent sex.
It is important to note that there is not much relationship between the first occurrence and the chronological order.
The order of time does not lead to an antecedent relationship, the sample code is as follows:
1234567 |
private int value=0;public void setValue (int value) { this.value=value;} public int GetValue () {return value;} |
Assuming thread A and thread B are present, thread a first (in time) calls "SetValue (1)", then thread B invokes the "GetValue ()" of the same object, then thread B receives a return value that is indeterminate due to the delay in working memory and main memory synchronization. Also due to the possible reordering phenomenon. Although the SetValue () operation of time-line A is preceded by the GetValue () operation of thread B, it is not possible to infer that the SetValue () operation of thread A takes precedence over the GetValue () operation of threads B, and if there is such an antecedent relationship, Then you can infer the value obtained by the GetValue () operation of the thread B.
If we add the Synchronized keyword to the GetValue () method and the SetValue () method, we can infer that the SetValue operation of thread A takes precedence over the getvalue operation of threads B, using the pipe lock rule. Or we can define value as a volatile variable, or we can infer the antecedent relationship using the volatile variable rule.
The first occurrence of a relationship does not infer the sequential order of execution of the time, as shown in the sample code:
According to the rules of program order, we can infer that the operation of "int I=1" takes place in "int j=2" operation, but the code of "int j=2" is completely possible to be executed by the processor first (in time order), this is the reordering, the virtual machine specification allows this feature to exist, Virtual machines can take advantage of this feature to improve performance.
Re-order
Operations in the same thread are executed sequentially (in fact, by the control flow), but in a thread that looks at other lines thread, it is executed in a disorderly order. The sample code is as follows:
1234567891011121314151617181920212223242526272829 |
public class Possiblereording {private static int x = 0, y = 0;private static int a = 0, b = 0; public static void Main (St Ring[] args) throws interruptedexception {thread one = new Thread () {@Overridepublic void run () {a = 1;x = b;}}; Thread other = new Thread () {@Overridepublic void run () {b = 1;y = A;}};o Ne.start (); Other.start (); One.join (); Other.join (); System.out.println ("(" + x + "," + y + ")");}} |
What is the result of the execution of this piece of code? We do not consider the work memory and main memory synchronization problem, assuming a sequence of execution, one thread executes first, then the other thread executes, then the sequence of operations will be a=1, X=b, B=1, y=a; At this point the output will be (0,1) assume another execution order, the other thread executes first, the one thread executes, then the sequence of operations is b=1,y=a,a=1,x=b, the output is (1,0), if the one thread and the other thread is executed alternately, a=1,b= 1,y=a,x=b, the result of this error is (in).
But it is hard to imagine the result of such an output (0,0). This is the phenomenon caused by reordering. One possible reordering of the execution order is as follows:
Thread A executes the a=1 first, then executes X=b, but X=b executes after a=1 because of the reason for reordering.
The order of this section refers to the time of succession, according to the memory model of the program sequence rules, thread A in the a=1 or first occurred in X=b.
Resources
"In-depth understanding of Java Virtual Machines" Chapter 12th Java memory model and threading
Java multithreaded design mode Appendix B the memory model of Java.
Reprint http://www.cloudchou.com/softdesign/post-637.html
Java memory Model (ii)