Volatile keywords and thread safety

Source: Internet
Author: User
Tags cas modifier visibility volatile

The volatile keyword and the thread-safe volatile keyword, which have two semantics: 1.volatile modified variables can be immediately perceived by other threads when the value of a variable modified by the volatile modifier is changed for other threads with immediate visibility. For normal variables, the value changes, you need to go through the store, the write process to write the variables from the current thread's working memory to the main memory, the other threads from the main memory through read, load the variable to their own working memory, due to the above process time impact, may lead to thread insecurity. Of course, it is not entirely true that variables modified with volatile are thread-safe. Because the volatile is to be divided into the scene: If multiple threads manipulate volatile modified variables, and the "operation" at this time is atomic, then it is thread-safe, otherwise not. Such as:
volatile int i=0; thread 1 execution: for (; i++;i<100); thread 2 execution: for (; i++;i<100);
The result of the last I is not necessarily 200 (thread insecure) because the i++ operation is not atomic, it involves three sub-operations: Remove I from main memory, i+1, and synchronize the results back to main memory. Then it is possible that a thread gets the latest value and is starting to perform a second sub-operation, and the second thread has already got the same value to begin the second sub-operation when the value has not yet changed. In this way, it is possible that two threads add a 1 to the same value, so even a volatile modifier can be a weakness. At this point, we should use the Synchronize or concurrent atomic class to guarantee the atomicity of the "operation". Therefore, the use of volatile scenarios should be: modified variables related to the operation of the atomic nature of the time. For example, modify a control flag bit:
volatile Boolean tag=true; thread 1 while (tag) {}; thread 2 while (tag) {};
When Tag=false, two threads can immediately perceive and stop the while loop because a simple assignment statement is atomic (given a specific value rather than a variable) and it is only responsible for synchronizing the main memory's tag to true. Keywords that can achieve visibility in addition to volatile, synchronize and final,synchronize are because variables are synchronized to main memory (with visibility) before they perform the unlock operation, and final is the variable that is modified by it, once initialized, And if the constructor does not pass the this reference outside, the other thread can see its value (because it never changes). 2. Prohibit order reordering new an object can be decomposed into the following 3 lines of pseudo-code
memory=allocate ();//1: Allocates the object's memory space ctorinstance;//2: Initialize object instance=memory;//3: Set instance point to the memory address just allocated
The above 3 lines of code between 2 and 3 may be reordered (on some JIT compilers, this reordering is true). The execution timings after reordering between 2 and 3 are as follows
memory=allocate ();//1: Allocating the object's memory space instance=memory;//3: Set instance to the memory address just allocated, note that the object has not been initialized ctorinstance (memory); 2: Initializing Objects
If a reorder occurs, another thread B that executes concurrently may have taken instance before the object operation has been initialized, but the object may not have been actually initialized by the thread, so this thread is unsafe. Java antecedent principle: 1. Rules of Procedure Order: in a thread, according to the Order of the program code (accurately said to be control flow order), first write first occurrence, after writing occurs. 2. Pipe lock rule: An unlock operation precedes the lock operation behind the lock. 3.volatile variable rule: A write operation to a volatile variable takes precedence over a read operation that faces this variable. 4. Thread Initiation rule: the Start () method of the thread object precedes each action on this thread. 5. Thread termination rule: All operations of the thread are preceded by termination detection for this thread. 6. Thread break rule: the invocation of the thread interrupt () method occurs when the code of the interrupted thread detects that the interrupt event occurred. The thread.interrupted () method can be used to detect if an interrupt will occur. 7. Object termination rule: Initialization of an object takes place prior to the beginning of its finalize () method. 8. Transitivity: If operation a precedes b,b before C, then a precedes c. Cases:
private int value=0;public void setValue (int value) {This.value=value;} public int GetValue () {return this.value;}
If thread 1 calls the SetValue (1) method and thread 2 calls GetValue (), then the resulting value is 0 or 1, which is indeterminate. Because it does not meet the above-mentioned antecedent principle: because it is not in a thread, it does not conform to the rules of program order, because there is no synchronization block, there is no lock and unlock, and therefore does not conform to the pipe lock rule, there is no volatile modification, there is no volatile variable rules, There is no subsequent thread-related rules and transitivity to speak of. For this, the following modifications can be made: the above setter, getter method is decorated with synchronize, so that it satisfies the pipe lock rule, or use the volatile modification, because SetValue () is the basic assignment operation, is an atomic operation, Therefore, a volatile usage scenario is met. Note: 1. In summary, thread safety generally requires at least two features: atomicity and visibility. 2.synchronize is atomic and visible, so if you use synchronize-modified operations, you bring visibility and no need for volatile to guarantee visibility. 2. For the above code, if you want to implement the self-increment and decrement of thread-safe numbers, you can also use the Java.util.concurrent.atomic package for non-locking atomic operation. In its underlying implementation, such as Atomicinteger, volatile is also used to ensure visibility, and using unsafe calls the native local method Cas,cas the use of bus lock or cache lock to ensure atomicity. Reference: (Java concurrency Programming: volatile keyword parsing) http://www.importnew.com/18126.html

Volatile keywords and thread safety

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.