Home > Back-end >  How about atomic classes AtomicInteger with CAS implementation on the (getAndIncrement ()) questions
How about atomic classes AtomicInteger with CAS implementation on the (getAndIncrement ()) questions

Time:10-30


/* ** Atomically increments by one, the current value. 
*
* @ the return to the previous value
*/
Public final int getAndIncrement () {
Return the unsafe. GetAndAddInt (this, valueOffset, 1);
}
//===========
Public final int getAndAddInt (Object o, long offset, int delta) {
Int v.
Do {
V=getIntVolatile (o, offset);//-- -- -- -- -- -- -- -- -- -- -- -- 0 -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
} while (! CompareAndSwapInt (o, offset, v, v + delta));//-- -- -- -- -- -- -- -- -- -- -- -- -- 1 -- -- -- -- -- -- -- -- -- -- -- -- --
Return v.
}

To see a lot of post still don't understand,,,
Most don't understand is, compare the two parameters, oldValue with the current value is?
Can understand for, atomic classes AtomicInteger itself contains a copy of oldValue, then compareAndSwapInt (), according to the offset to find main memory corresponding to the current value of oldValue, if the same change, different went back into the cycle to read main memory oldValue current value, to compare? Until both, plus one?
In addition, want to ask next, where the atomic reflect? Is said to run the whole getAndIncrement () method is atomic? A thread running, this method will not be interrupted by another thread, the atomic or what?
Strives for the people,

CodePudding user response:

Comparison and replace this step is atomic operations, is packaged a execution, you ever think of, if not compare and atomicity, held at the thread oldValue oldValue consistent and main memory, you are about to replace, and then thread blocks, such as thread turn to replace operation, the value is more thin, the data was wrong

CodePudding user response:

CAS you will think of it as in the case of unlocked, multithreading, to modify a variable to ensure that only one thread can modify success, the reason for comparing values, is to make sure to change the value of the other threads
  • Related