Java--什么时候需要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);
    }

 

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值