什么是Java的AtomicReference.getAndSet用例?换句话说,如果我在我的代码中仅使用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;
}
从呼叫者的角度来看?