Atomic objects use the Compare and Swap mechanism to make them atomic - that is, you can guarantee that the value was , as indicated, and now with the new value.
The code you posted is constantly trying to set the current value to another than before. Remember, another thread could also get and try to install it. If two threads diverge from each other to change the value, it is possible that one of the increments will fail.
Consider the following scenario:
- Topic 1 calls
get and gets the value 1 . - In thread 1,
next calculated as 2 . - Thread 2 calls
get and gets the value 1 . - In thread 2,
next calculated as 2 . - Both threads try to write the value.
Now, due to atomic science - only one thread will succeed , the other will get false from compareAndSet and go down again.
If this mechanism was not used, it would be quite possible for both threads to increase the value, resulting in only one increment.
The confusing infinite loop for(;;) will really loop only if many threads write to the variable at the same time. With a very large load, it can rotate several times, but it should end rather quickly.
Oldcurmudgeon
source share