【问题标题】:What is a usecase for Java AtomicReference#getAndSet?Java AtomicReference#getAndSet 的用例是什么?
【发布时间】:2020-09-03 18:39:19
【问题描述】:

Java AtomicReference#getAndSet 的用例是什么?换句话说,如果我在代码中使用的来自AtomicReference 的唯一方法是AtomicReference#getAndSet,那么这是正确的假设,那么我根本不需要AtomicReference,只需要一个volatile 变量就足够了吗?

例如,如果我有下一个代码:

private final AtomicReference<String> string = new AtomicReference<>("old");

public String getAndSet() {
    return string.getAndSet("new");
}

,是不是一直都和

一样
private volatile String string = "old";

public String getAndSet() {
    String old = string;
    string = "new";
    return old;
}

从调用者的角度来看?

【问题讨论】:

    标签: java concurrency volatile atomicreference


    【解决方案1】:

    不,这些不相等。不同之处在于getAndSet 以原子方式执行两种操作,而不仅仅是原子获取和原子集合。

    getAndSet 始终保证返回准确存储在引用中就在设置新值之前的值。 volatile 版本可能会“跳过”其他线程插入的值。

    【讨论】:

      猜你喜欢
      • 2010-09-21
      • 1970-01-01
      • 1970-01-01
      • 2013-04-14
      • 1970-01-01
      • 1970-01-01
      • 2011-01-26
      • 2016-07-25
      • 2011-04-27
      相关资源
      最近更新 更多