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;
}
从调用者的角度来看?