【发布时间】: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