英文:
What is a usecase for Java AtomicReference#getAndSet?
问题
什么是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;
}
英文:
What is a usecase for Java AtomicReference#getAndSet
? In other words, is it correct assumption, that if the only method from AtomicReference
that I use in my code is AtomicReference#getAndSet
, then I do not need AtomicReference
at all, just a volatile
variable would be enough?
For example, if I have the next code:
private final AtomicReference<String> string = new AtomicReference<>("old");
public String getAndSet() {
return string.getAndSet("new");
}
, isn't it always doing exactly the same as
private volatile String string = "old";
public String getAndSet() {
String old = string;
string = "new";
return old;
}
from the caller's point of view?
答案1
得分: 9
不,这些不是等价的。区别在于 getAndSet
会原子地执行 两个操作,而不仅仅是原子地获取然后原子地设置。
getAndSet
保证始终返回在设置新值 之前 存储在引用中的确切值。而 volatile 版本可能会“跳过”其他线程插入的值。
英文:
No, these are not equivalent. The difference is that getAndSet
does both operations atomically, not just an atomic get and then an atomic set.
getAndSet
is always guaranteed to return exactly the value that was stored in the reference right before the new value was set. The volatile version might "skip" values inserted by other threads.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论