Related articles
Java concurrent Programming (i) thread definitions, states, and properties
Java Concurrent Programming (ii) synchronization
Android multithreaded (one) thread pool
Android Multithreading (ii) asynctask source code Analysis
Preface
Sometimes it is too expensive to use synchronization just to read or write one or two instance domains, and the volatile keyword provides a lock-free mechanism for synchronizing access to the instance Domain. Assuming that a domain is volatile, the compiler and the virtual machine know that the domain is likely to be updated concurrently with one Thread.
Before we talk about the volatile keyword, we need to look at the related concepts of the memory model and the three features in concurrent programming: atomicity, visibility, and Ordering.
1. Java memory model and Atomicity. Visibility and Ordering
The Java memory model stipulates that all variables are present in main memory, and each thread has its own working memory. All thread-to-variable operations must be performed in working memory. Instead of directly manipulating main memory. And each thread cannot access the working memory of other THREADS.
In Java. Run the following statement:
int i=3;
The running thread must first assign a value to the cache row where the variable I resides in its own worker thread, and then write to the master Store. Instead of directly writing the value 3 to main memory.
So what are the guarantees that the Java language itself provides for atomicity, visibility, and ordering?
Atomic Nature
Read and assign operations to variables of the base data type are atomic operations. That is, these operations cannot be interrupted or Run. Or do not Run.
Take a look at the following code:
10; //语句1y = x; //语句2x++; //语句31; //语句4
Only Statement 1 is an atomic operation, and the other three statements are not atomic in Nature.
Statement 2 actually includes 2 operations, it first to read the value of x, and then write the value of x to the working memory, although the value of reading X and writing the value of X to the working memory of the 2 operations are atomic operations, but it is not atomic operation is Combined.
The same, x + + and × = x+1 include 3 operations: reads the value of x. To add 1 operations. Writes a new Value.
That is, simply reading, assigning (and having to assign a number to a variable, the reciprocal assignment of a variable is not an atomic Operation) is the atomic Operation.
There are very many classes in the Java.util.concurrent.atomic package that use very efficient machine-level instructions (rather than using Locks) to ensure the atomicity of other Operations. For example, the Atomicinteger class provides methods Incrementandget and decrementandget, which atomically increment and decrement an integer individually. The Atomicinteger class can be safely used as a shared counter without Synchronization.
In addition this package also includes Atomicboolean. Atomiclong and Atomicreference These atomic classes are used only by the system program apes that develop concurrency Tools. Application apes should not use these Classes.
Visibility of
Visibility refers to the visibility between threads, the state of a thread churn, and a thread that is Visible. That is, the result of a thread churn. There is one more thread that can be seen right away.
When a shared variable is modified by volatile, it guarantees that the changed value is immediately updated to main memory. So it is visible to other threads, and when another thread needs to read it, it will read the new value in Memory.
Common shared variables do not guarantee visibility, since common shared variables are Changed. When the memory is written to main memory is indeterminate, and when other threads go to read it may still be the original old value and therefore cannot guarantee visibility.
Order of
In the Java memory model, the compiler and processor are agreed to reorder the Instructions. however, The reordering process does not affect the operation of single-threaded procedures, but it can affect the correctness of multi-threaded concurrency Operation.
Be able to guarantee a certain "order" through the volatile Keyword.
In addition to the ability to maintain order through synchronized and lock, it is clear that synchronized and lock guarantee that every moment there is a thread running the synchronization Code. The equivalent is to let the thread sequence run the synchronization Code. Nature guarantees the Order.
2. volatile keyword
Once a shared variable (A member variable of a class, a static member variable of a class) is modified by volatile, then there are two layers of semantics:
- The visibility of this variable is ensured by a thread that changes the value of a variable, which is immediately visible to other THREADS.
- Command reordering is Prohibited.
Look at the code first, if thread 1 runs first, thread 2 runs:
//线程1booleanfalse;while(!stop){ doSomething();}//线程2true;
A lot of people might use such a tagging method when they interrupt a thread. But in fact, this code will be completely run correctly? Is it bound to break the thread? Not necessarily. Perhaps most of the time, this code can break the Thread. however, There is also the possibility of failure to break the thread (although the probability is very small, but only if this happens will cause a cycle of death).
Why is it possible to break the thread? Each thread has its own working memory during the Run. When thread 1 is running, a copy of the value of the stop variable is placed in its own working memory.
Then when thread 2 changes the value of the stop variable, it has not yet been written to main memory. Thread 2 Go to do other things, then thread 1 because you do not know the thread 2 changes to the stop variable, so it will continue to loop.
however, after being modified with the volatile, it becomes different:
- Using the volatile keyword forces the changed values to be written to main memory immediately.
- Use the volatile keyword Word. When thread 2 is changed, it causes thread 1 to work in-memory cache variable stop cache row is invalid;
- Because thread 1 works in-memory cache variable stop cache line is invalid, thread 1 reads the value of the variable stop again when it reads from main memory.
does volatile guarantee atomicity?
We know that the volatile keyword guarantees the visibility of the operation, but does volatile guarantee that the operation of the variable is atomic?
public classTest { public volatile intinc =0; public void Increase() {inc++; } public Static void Main(string[] Args) {final Test test =NewTest (); for(intI=0;i<Ten; I++) {NewThread () { public void Run() { for(intj=0;j< +; j + +) Test.increase (); }; }.start (); }//ensure that the previous threads are running out while(thread.activecount () >1) Thread.yield(); System. out. println (test.inc); }}
This code every time the result is inconsistent, is a number less than 10000, as mentioned earlier, the self-increment operation is not atomic, it includes reading the original value of the variable, adding 1 operations, writing to the working memory. So the three sub-operations of the self-increment operation may be cut Open.
If at some point the value of the variable inc is 10, thread 1 self-increment The variable, thread 1 reads the original value of the variable inc first, then thread 1 is blocked, then thread 2 self-increment the variable, and thread 2 reads the original value of the variable Inc. Because thread 1 simply reads from the variable inc, it does not alter the VARIABLE. therefore, the cache line of the working in-memory Cache Variable Inc does not cause thread 2 to be invalid. So thread 2 will go directly to main memory to read the value of inc, find the value of INC 10, then add 1 operations and write 11 to the working memory. Finally write to main memory. Thread 1 then adds 1, because the value of the INC has been read, and note that at this point the value of INC in working memory for thread 1 is still 10. therefore, Thread 1 to Inc adds 1 to the value of 11 and then writes 11 to working memory. Finally write to main memory.
Then two threads were once self-increment Operation. Inc just added 1.
The self-increment operation is not atomic, and volatile does not guarantee that the operation of the variable is ATOMIC.
does volatile Guarantee order?
The volatile keyword mentioned above can prohibit the order Reordering. therefore, volatile can be guaranteed to a certain degree of order.
The volatile keyword prohibit command reordering has two layers of meaning:
- When a program runs to a read or write operation of a volatile variable, the change in its preceding operation must have been made, and the result is already visible to the subsequent operation, and the operation behind it must not have been performed.
- In the case of instruction Optimization. You cannot run a statement that has access to a volatile variable after it has been interviewed. It is also not possible to put the statements that follow the volatile variable before it runs.
3. Use the volatile keyword correctly
The Synchronized keyword is to prevent multiple threads from running a piece of code at the same time. Then it will greatly affect the efficiency of the program, and the volatile keyword in some cases performance is better than synchronized, but note that the volatile keyword can not replace the synchronized keyword, Because the volatile keyword does not guarantee the atomicity of the Operation.
In general, the following 2 conditions are required to use volatile:
- A write to a variable does not depend on the current value
- The variable is not included in the invariant with other variables
The first condition is that it cannot be a self-increment or decrement operation, and the above mentioned that volatile does not guarantee Atomicity.
The second condition, let's take a sample. it includes an invariant: the nether is always less than or equal to the upper bound
public classNumberrange {Private volatile intlower, upper; public int Getlower() {returnLower } public int Getupper() {returnUpper } public void Setlower(int value) {if(value> Upper)Throw NewIllegalArgumentException (...); Lower =value; } public void Setupper(int value) {if(value< Lower)Throw NewIllegalArgumentException (...); Upper =value; }}
Such a way restricts the state variables of the scope, so defining the lower and upper fields as volatile types does not fully implement the thread safety of the class, and it still requires synchronization.
otherwise, Assuming that two threads are running Setlower and setupper at the same time using inconsistent values, the scope will be in an inconsistent state.
For example, assuming that the initial state is (0, 5), at the same time, thread A calls Setlower (4) and thread B calls Setupper (3), It is clear that the values crossed by these two operations are not eligible, then two threads will pass the check to protect the invariant, so that the final range value is (4 , 3), which is obviously not true.
In fact, to ensure that the atomicity of the operation can use volatile, using volatile mainly has two scenarios:
Status Flag
volatileboolean shutdownRequested;...publicvoidshutdown() { true; }publicvoiddoWork() { while (!shutdownRequested) { // do stuff }}
It is very likely that the shutdown () method is called from outside the Loop-that is, in a thread-so there is a need to run some kind of synchronization to ensure that the visibility of the shutdownrequested variable is properly implemented. however, It is much more cumbersome to write loops using synchronized blocks than to write with volatile state flags. Because volatile simplifies coding, and status flags do not depend on any other state in the program, it is well suited to use Volatile.
double check mode (DCL)
public Class Singleton {private volatile static Singleton instance = null ; public static Singleton getinstance () {if (instance = = null ) {synchronized (this ) { if (instance = = null ) {instance = new Singleton (); }}} return instance; } }
Using volatile here can affect performance more or less, but with the correctness of the program in Mind. Sacrificing this performance is worth it.
The DCL has the advantage of high resource Utilization. Singleton objects are instantiated the first time getinstance is Run. High Efficiency. The disadvantage is that the response is slightly slower the first time it is Loaded. In the high Concurrency environment also has certain FLAW. Although the probability of occurrence is very small.
DCL Although in some degree to overcome the depletion of resources and redundant synchronization, line Cheng problems, But he still in some cases will fail, that is, DCL failure, in the "java concurrency programming practice," The book suggested using the following code (static internal class singleton Mode) to replace the Dcl:
publicclass Singleton { privateSingleton(){ } publicstaticgetInstance(){ return SingletonHolder.sInstance; } privatestaticclass SingletonHolder { privatestaticnew Singleton(); }
About double check to see http://blog.csdn.net/dl88250/article/details/5439024
4. Summary
Volatile variables, compared to locks, are a very easy but very fragile synchronization mechanism, which in some cases provides better performance and scalability than locks. It is assumed that strictly following the use of volatile conditions is that the variable is truly independent of the other variables and its own values, and in some cases can use volatile instead of synchronized to simplify the Code. however, code that uses volatile is often more prone to error than code that uses locks. This article describes the two most common use cases that can be used to replace synchronized with volatile, and in other cases we might as well use Synchronized.
Java concurrency Programming (iii) volatile domains