什么是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;
}从来电者的角度来看?
发布于 2020-09-03 18:50:05
不,这些不是等价物。不同之处在于,getAndSet两种操作都是原子化的,而不仅仅是原子get,然后是原子集。
在设置新值之前,始终保证getAndSet准确地返回存储在引用中的值。易失性版本可能“跳过”其他线程插入的值。
https://stackoverflow.com/questions/63729807
复制相似问题