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.
Asked
Active
Viewed 89 times
1 Answers
0
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:
- Fetch the current value (it's 5)
- Tell the CPU: Hey, CPU, IF the value is still 5, can you make it 7? Otherwise, please don't do anything. And tell me if you managed.
- If you managed, great. return 5.
- If you did not, go back to 1. And keep doing that, until the CAS operation works.

rzwitserloot
- 85,357
- 5
- 51
- 72