"
CAS mechanism
"
refers to Compareandswap or Compareandset, is an atomic operation that implements the atomic class of this mechanism that records the current value of an offset address stored in memory, comparing the true Value V in memory with the old expected value a. If the inconsistency indicates that the value in memory has been modified by another thread, returns false, otherwise the new value b is stored in memory.
Inside Java is implemented using local calling class unsafe.
The underlying principle of Java atom class is to use CAS mechanism.
What may be the problem
- ABA issues:
thread 1 remove a 2 put in memory a b a at this point the thread 1 resuming execution, taking the in-memory a a
But at this time both A Although it may be the same, but in fact, it has been modified. For example, thread 1 needs to replace the top of a stack, from a to B, but to execute the front 2 preemption to the time slice , a series of stack operations on the stack, and then a into the stack, when thread 1 Recovery, found that the stack top or a, so replace the B, but at this point the stack is no longer the original stack.
Solution --Version number:
Add version number comparisons when comparing, and also modify the version number each time you modify it.
The atomicstampedreference that 1.5 started is the version number comparison that was used.
- High execution overhead:
CAS If the long-time unsuccessful will always spin the loop, it will incur a lot of execution overhead. and to avoid memory order collisions at the end of the spin,theCPU will rearrange the pipelining, which can seriously affect CPU performance.
Solution Idea -pause command:
The Pause command allows the CPU to sleep for a short period of time while spinning fails, which makes the frequency of the read operation much lower, and the cost of pipelining is much smaller for resolving memory order conflicts.
Memory Order Conflicts -When the spin lock is about to be released, the lock thread will have a store command, and the spinning thread will emit its own load command, and there is no happen-before ordering, so the processor is executed in a random order, Therefore, in order to prevent load from appearing in the store before the pipeline emptying and re-ordering, will seriously affect the CPU efficiency, the role of the pause instruction is to reduce the number of parallel load, thus reducing the time spent reordering. (Do not know the load and store can go to see JMM (Java memory model) data)
- Only the atomic operation of a shared variable can be guaranteed:
The solution --1.5 start atomicreference can guarantee the atomic nature of the reference, can put the multi-variable into the object for atomic operation.
Copy from your own word notes, no pictures, and a lot of problems with the format, there is time to fill.
A detailed explanation of the problems caused by CAS mechanism in Java and the resolution-memory sequence conflicts