简体   繁体   中英

What is the meaning of the spin in the getAndIncrement method in the AtomicInteger class?

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:

  1. Fetch the current value (it's 5)
  2. 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.
  3. If you managed, great. return 5.
  4. If you did not, go back to 1. And keep doing that, until the CAS operation works.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM