什么是Java AtomicReference#getAndSet的用例?

huangapple go评论64阅读模式
英文:

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&lt;String&gt; string = new AtomicReference&lt;&gt;(&quot;old&quot;);

public String getAndSet() {
    return string.getAndSet(&quot;new&quot;);
}

, isn't it always doing exactly the same as

private volatile String string = &quot;old&quot;;

public String getAndSet() {
    String old = string;
    string = &quot;new&quot;;
    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.

huangapple
  • 本文由 发表于 2020年9月4日 02:39:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/63729807.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定