本文介绍了何时使用AtomicReference(Java)?是真的有必要吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用AtomicLong多次,但我从来没有需要使用AtomicReference

I have used AtomicLong many times but I have never needed to use AtomicReference

看起来AtomicReference做了(我复制这个代码从另一个stackoverflow
问题):

It seems that AtomicReference does either (I copied this code from another stackoverflowquestion):

public synchronized boolean compareAndSet(List<Object> oldValue, List<Object> newValue) {
    if (this.someList == oldValue) {
        // someList could be changed by another thread after that compare,
        // and before this set
        this.someList = newValue;
        return true;
    }
    return false;
}

public synchronized boolean compareAndSet(List<Object> oldValue, List<Object> newValue) {
    if (this.someList == oldValue || this.someList.equals(oldValue)) {
        // someList could be changed by another thread after that compare,
        // and before this set
        this.someList = newValue;
        return true;
    }
    return false;
}

假设this.someList标记为volatile。

Assume this.someList is marked volatile.

我不知道它是真正的那个是因为javadoc和该类的代码不清楚如果使用.equals。

I'm not sure really which one it is because the javadoc and the code for that class are not clear if .equals is used.

看到如何上面的方法不是那么难写,有谁曾经使用AtomicReference?

Seeing how the above methods are not exactly that hard to write has anyone ever used AtomicReference?

推荐答案

这是一个参考文档非常清楚,它是一个身份比较,甚至使用

It's a reference, so that's what is compared. The documentation makes it very clear that it's an identity comparison, even using the == operation in its description.

我经常使用 AtomicReference 和其他原子类。分析表明,它们的性能比使用同步的等效方法更好。例如,对 AtomicReference get()操作只需要从主存储器提取,而类似的操作使用 synchronized 必须首先将线程缓存的任何值刷新到主存储器,然后执行其提取操作。

I use AtomicReference and other atomic classes very frequently. Profiling shows that they perform better than the equivalent methods using synchronization. For example, a get() operation on an AtomicReference requires only a fetch from main memory, while an a similar operation using synchronized must first flush any values cached by threads to main memory and then perform its fetch.

c $ c> AtomicXXX 类提供对比较和交换(CAS)操作的本机支持的访问。如果底层系统支持它,CAS将比在纯Java中使用 synchronized 块的任何方案更快。

The AtomicXXX classes provide access to native support for compare-and-swap (CAS) operations. If the underlying system supports it, CAS will be faster than any scheme cooked up with synchronized blocks in pure Java.

这篇关于何时使用AtomicReference(Java)?是真的有必要吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 08:12