Compare 在 AtomicInteger.incrementAndGet() 的 CompareAndSwap 比较什么?
what does Compare compare at CompareAndSwap at AtomicInteger.incrementAndGet()?
我知道 CompareAndSwap 在 java 并发的 AtomicInteger.incrementAndGet() 等方法的幕后使用,它像无限循环一样工作,直到它成功并阻塞它的线程
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).
那么 incrementAndGet() 中的给定值和内存位置的内容是什么?
当一个线程看到当前值时,例如 1
,然后它将其递增到 2
作为 given value
,并将 2
与实际值进行比较当前在内存中。
如果成功,将返回2
。
否则,它将检索最新值,假设为 x
,并递增至 x + 1
作为给定值。
...
此过程将一直持续到比较成功。
我知道 CompareAndSwap 在 java 并发的 AtomicInteger.incrementAndGet() 等方法的幕后使用,它像无限循环一样工作,直到它成功并阻塞它的线程
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).
那么 incrementAndGet() 中的给定值和内存位置的内容是什么?
当一个线程看到当前值时,例如 1
,然后它将其递增到 2
作为 given value
,并将 2
与实际值进行比较当前在内存中。
如果成功,将返回2
。
否则,它将检索最新值,假设为 x
,并递增至 x + 1
作为给定值。
...
此过程将一直持续到比较成功。