In the getAndIncrement method of the AtomicInteger class,the getAndAddInt method of the unsafe class is called,which contains the compareAndSwapInt method and the spin(do...while). The compareAndSwapInt method is thread-safe,so Why not just change the value in the compareAndSwapInt method, but also need the spin to be safe? Thank you for your answer.
What source are you looking at? At least since JDK11, and still in the current JDK16, the implementation of Unsafe
's getAndAddInt
is:
int v;
do {
v = getIntVolatile(o, offset);
} while (!weakCompareAndSetInt(o, offset, v, v + delta));
return v;
I have no idea where you got compareAndSwapInt
from.
The above code has a spin because that's how CAS always works. (Compare-And-Set): That code says, with for example an AtomicInteger that is currently '5' and you are trying to add 2 to it:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.