伊谢尔伦2017-04-18 10:42:51
It is the address, to be precise, it is the value of the memory valueOffset position of this object compared with expect.
Detailed explanation of Unsafe
阿神2017-04-18 10:42:51
As the questioner said, AtomicInteger
源码是比较并替换Integer
来实现线程安全性。而AtomicReference
is a comparison and replacement compared to object references. These are atomic class CAS implementations.
As for comparing addresses, let’s start with what the questioner said AtomicReference
and know the following methods:
public final boolean compareAndSet(V expect, V update) {
return unsafe.compareAndSwapObject(this, valueOffset, expect, update);
}
The underlying implementation is in Unsafe
类中,是一个native
本地方法。Unsafe
的CAS包括了三个操作数--需要读写的内存位置valueOffset
,进行比较的值expected
,拟定写入的新值update
. CAS atomically updates the old value of the memory address with the new value if and only if the value stored in memory location V is equal to the compared value A. Otherwise, no operation is performed.
The key lies in the role of the passed in valueOffset
, continue to view valueOffset
的作用,继续查看AtomicReference
Source code:
static {
try {
valueOffset = unsafe.objectFieldOffset
(AtomicReference.class.getDeclaredField("value"));
} catch (Exception ex) { throw new Error(ex); }
}
private volatile V value;
Here, the unsafe
的objectFieldOffset
method is to get the memory offset of the object, that is, through comparison here, you can determine whether it is the same object address.
So, conclusion:
Atomic atomic CAS operation compares memory offsets, that is, memory addresses.