什么时候需要AtomicReference?

问:既然在java中引用的赋值操作本身就是是原子的,那为什么还需要AtomicReference(原子引用)?

答:如果仅需要通过赋值操作改变一个引用,确实不需要AtomicReference。

 
// 注意volatile关键字
volatile Person person = new person("Jim");
 
 
public void processA() {
    // 赋值操作是原子的
    persion = new persion("Tom");
}
实际上相当于仅使用了AtomicReference的set()方法,看一下set()的实现:

 /**
     * Sets to the given value.
     *
     * @param newValue the new value
     */
    public final void set(V newValue) {
        value = newValue;
    }
AtomicReference的set()方法,其实就是直接赋值。

真正需要使用AtomicReference的场景是你需要CAS类操作时,由于涉及到比较、设置等多于一个的操作,需要借用Unsafe类的原子操作,比如:

/**
     * Atomically sets the value to the given updated value
     * if the current value {@code ==} the expected value.
     * @param expect the expected value
     * @param update the new value
     * @return {@code true} if successful. False return indicates that
     * the actual value was not equal to the expected value.
     */
    public final boolean compareAndSet(V expect, V update) {
        return unsafe.compareAndSwapObject(this, valueOffset, expect, update);
    }
 

原文:https://blog.csdn.net/kosmosas/article/details/89510675

java并发库提供了很多原子类来支持并发访问的数据安全性,除了常用的

AtomicInteger、AtomicBoolean、AtomicLong 外还有
AtomicReference 用以支持对象的原子操作:AtomicReference<V> 可以封装引用一个V实例,
通过
public final boolean compareAndSet(V expect, V update) 
可以支持并发访问,set的时候进行对比判断,如果当前值和操作之前一样则返回false,否则表示数据没有变化。

参考:https://blog.csdn.net/conquer0715/article/details/12365553

发布了740 篇原创文章 · 获赞 65 · 访问量 10万+

猜你喜欢

转载自blog.csdn.net/qq_41723615/article/details/104342834
今日推荐