java - AtomicReference<V> compareAndSwap是比较对象的地址吗
PHPz
PHPz 2017-04-18 10:40:51
0
2
448
PHPz
PHPz

学习是最好的投资!

reply all(2)
伊谢尔伦

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

阿神

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的作用,继续查看AtomicReferenceSource code:

static {
  try {
    valueOffset = unsafe.objectFieldOffset
        (AtomicReference.class.getDeclaredField("value"));
  } catch (Exception ex) { throw new Error(ex); }
}

private volatile V value;

Here, the unsafeobjectFieldOffset 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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!