For concurrency control, our usual lock (Synchronized,lock) is a pessimistic strategy. It always assumes that each critical section operation will have a conflict, so you must be cautious about each operation. If multiple threads access critical section resources at the same time, they would rather sacrifice performance to allow the thread to wait, so the lock will block the thread execution.
In contrast, there is an optimistic strategy that assumes no conflict of access to resources. Since there is no conflict there is no need to wait, and all threads continue to execute without pausing. Well, if there's a problem. A lock-free policy uses a type of comparison Exchange (CAS Compare and swap) to identify thread conflicts, and once a conflict is detected, retry the current operation until there is no conflict. The CAS algorithm is non-blocking and inherently immune to deadlock problems, and it has superior performance over lock-based methods.
The process of the CAS algorithm is this: it contains three parameters CAs (v,e,n). V represents the variable to be updated, E represents the expected value, and n represents the new value. The value of V is set to n only if the V value equals the E value, otherwise nothing is done. The last CAs returns the value of the current v. The CAS algorithm requires you to give an extra expectation, which is what you think the variable should look like now, and if the variable is not what you think it is, it has been modified by someone else. You re-read it and try to modify it again.
The JDK also has a atomic package that implements some thread-safe types that directly use CAS operations. One of the most commonly used classes should be atomicinteger. Let's take this as an example of how to do thread safety without a lock.
Value
This is the core field of the Atomicinteger class, representing the current actual value, with volatile to guarantee the visibility of data between threads.
Ways to get internal data:
Public Final int get () { return value; }
Let's take a look at the internal implementation of Incrementandget ()
1 Public Final intIncrementandget () {2 for (;;) {3 intCurrent =get ();4 intNext = current + 1;5 if(Compareandset (current, next))6 returnNext;7 }8}
The second line of code uses a dead loop because the operations of CAs are not necessarily successful, so for unsuccessful situations we need to make constant attempts. The third line gets the current value, and then +1 gets the new value next. Here we use the two parameters required by CAS: expectation and new values. Use Compareandset () to write the new value next. The condition of success is that at the time of writing, the current value should be equal to what was just taken. If this is not the case, the value of Atomicinteger is modified by another thread between lines 3rd through 5th. The status you are currently seeing is an out-of-date state, so the return failure requires the next retry to know the success.
Public Final boolean compareandset (intint update) { return Unsafe.compareandswapint (This, Valueoffset, expect, update); }
The whole process is like this, using the CPU's CAS instruction, and using JNI to complete the Java non-blocking algorithm. Other atomic operations are done using a similar feature. The approximate logic should be this:
if ( This = = expect) {This = update returntrue Else { returnfalse
CAs can solve atomic problems efficiently, but CAs also brings 1 classic problems: the ABA problem.
Because CAs needs to check that the value is not changed when the value is manipulated, if it does not change, it is updated, but if a value is a, B, and a, then checking with CAS will show that its value has not changed, but actually it has changed.
The solution to the ABA problem is to use the version number. Append the version number before the variable, and add one to the version number each time the variable is updated, then A-b-a will become 1a-2b-3a.
A class atomicstampedreference is provided in the atomic package of the JDK starting with Java1.5 to solve the ABA problem. This class not only maintains the object values internally, but also maintains a timestamp (which can be any integer to represent the state value). When you set an object value, both the object value and the state value must meet the expectations before the write succeeds. Therefore, even if the object is read and written repeatedly, the write will be the original value, as long as the state value changes, can prevent inappropriate writing.
/**
*@paramExpectedreferenceExpectations
*@paramNewreferenceWrite new value
* @param expectedstamp Expected status value
* @param newstamp New status value
* @return True if successful
*/
Public BooleanCompareandset (v expectedreference, v newreference, intExpectedstamp,intNewstamp) {Pair<V> current =pair; returnexpectedreference= = Current.reference &&Expectedstamp= = Current.stamp &&((newreference= = Current.reference &&Newstamp= = Current.stamp) | |Caspair (Current, Pair.of (Newreference, Newstamp))); }
Concurrency Policy-cas algorithm