I know CompareAndSwap is used under hood of methods like AtomicInteger.incrementAndGet() in java concurrent,it works like endless cycle until it successful and blocked it's thread
It compares the contents of a memory location with a given value and, only if they are the same, modifies the contents of that memory location to a new given value. This is done as a single atomic operation. The atomicity guarantees that the new value is calculated based on up-to-date information; if the value had been updated by another thread in the meantime, the write would fail. The result of the operation must indicate whether it performed the substitution; this can be done either with a simple boolean response (this variant is often called compare-and-set), or by returning the value read from the memory location (not the value written to it).
So what it the given value and contents of a memory location in incrementAndGet()?
When one thread sees the current value, for example, 1
, then it increments it to 2
as given value
, and compare 2
to the real value in memory at current moment.
If it successes, 2
will be returned.
Otherwise, it will retrieve the newest value, let's say it x
, and increment to x + 1
as given value.
...
This procedure will continue until a successful comparison.