This is the sixth day of my participation in the August More text Challenge. For details, see:August is more challenging
1.CAS guarantees concurrency, but multiple comparisons are required
The loop takes a long time and is expensive, so let’s look at the code in the core getAndAddInt method
public final int getAndAddInt(Object var1, long var2, int var4) {
int var5;
do {
var5 = this.getIntVolatile(var1, var2);
} while(!this.compareAndSwapInt(var1, var2, var5, var5 + var4));
return var5;
}
Copy the code
If the CAS operation does not succeed (this.compareAndSwapInt(var1, var2, var5, var5 + var4)) then false will be returned, so that because of the addition! Number, the do while part will try all the time, and if the CAS is not successful for a long time, it may put a heavy burden on the CPU
No locks, allowing multiple threads to change concurrently, but requiring multiple comparisons
2. Only one atomic operation can be guaranteed for a shared variable.
We can use the cyclic CAS to guarantee atomicity when we operate on one shared variable, but when we operate on multiple shared variables, the cyclic CAS cannot guarantee atomicity. In this case, we can use the lock to guarantee atomicity. An alternative approach is to encapsulate multiple shared variables into an object and use the AtomicReference class to ensure atomicity between referenced objects. (Starting with Java 1.5, the JDK provides an AtomicReference class to ensure atomicity between referenced objects.)
3.ABA problems (emphasis)
The T2 thread changed A to B and wrote B in the working memory back to the main physical memory, but the T2 thread changed the value in the working memory to A and wrote B back to the main physical memory. At this time, the value in the main physical memory was still B. After 10 seconds, the T1 thread began to compare the expected value and the actual value, and found that there was no change, and the CAS operation succeeded. But the value in the main physical memory is actually modified.
The beginning and end are the same, but the intermediate data may have been modified many times
An important premise of CAS algorithm is to extract the data in memory at a certain moment and compare and replace it at the current moment, so the change of data may be found in this time difference.
Such as A thread T1 from memory location V A, then another thread T2 also from memory to retrieve A, and thread T2 some after operation and V position data into A, the threads T1 for CAS operation was found in the memory is still A, then thread T1 operation is successful Although thread T1 for CAS operation is successful, But that doesn’t mean the process isn’t problematic.