The cycle can be endless (since it can generate hunger for your flow), but the likelihood of this happening is very small. In order for you to get hunger, you will need another thread that will change the value you want to update between your reading and your store, and repeat for that.
One could write code to cause hunger, but for real programs this is unlikely to happen.
Comparison and swap are usually used when you do not think that you will have write conflicts very often. Let's say that there is a 50% chance of a “miss” during the upgrade, that is, a 25% chance that you will miss two loops and a less than 0.1% chance that the upgrade will fail in 10 cycles. For examples in the real world, 50% of missed rates are very high (basically they do nothing but update), and since the miss speed decreases, say, 1%, the risk of not succeeding in two attempts is only 0.01%, and in 3 tries 0.0001%.
Usage is similar to the following problem
Set the variable a to 0 and add two threads, updating them with a = a + 1 million times each at a time. At the end, a can have any response between 1,000,000 (every other update was lost due to overwriting) and 2,000,000 (the update was not overwritten).
The closer you get to 2,000,000, the more likely you are to use CAS, as this means that CAS often sees the expected value and can set a new value.
source share