search

Home  >  Q&A  >  body text

java - AtomicReference<V> compareAndSwap是比较对象的地址吗

PHPzPHPz2900 days ago511

reply all(2)I'll reply

  • 伊谢尔伦

    伊谢尔伦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

    reply
    0
  • 阿神

    阿神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的作用,继续查看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.

    reply
    0
  • Cancelreply