yas*_*dev 3 java concurrency volatile atomicreference
什么是 Java 用例AtomicReference#getAndSet?换句话说,是否正确的假设是,如果AtomicReference我在代码中使用的唯一方法是AtomicReference#getAndSet,那么我根本不需要AtomicReference,只需要一个volatile变量就足够了?
例如,如果我有下一个代码:
private final AtomicReference<String> string = new AtomicReference<>("old");
public String getAndSet() {
return string.getAndSet("new");
}
Run Code Online (Sandbox Code Playgroud)
, 是不是总是和
private volatile String string = "old";
public String getAndSet() {
String old = string;
string = "new";
return old;
}
Run Code Online (Sandbox Code Playgroud)
从调用者的角度来看?
不,这些不是等价的。不同之处在于getAndSet这两个操作都是原子的,而不仅仅是一个原子获取然后一个原子集合。
getAndSet总是保证准确返回在设置新值之前存储在引用中的值。易失版本可能会“跳过”其他线程插入的值。
| 归档时间: |
|
| 查看次数: |
100 次 |
| 最近记录: |