什么时候在 Java 中使用 AtomicReference? [英] When to use AtomicReference in Java?
问题描述
我们什么时候使用 AtomicReference
?
When do we use AtomicReference
?
所有的多线程程序都需要创建对象吗?
Is it needed to create objects in all multithreaded programs?
提供一个应该使用 AtomicReference 的简单示例.
Provide a simple example where AtomicReference should be used.
推荐答案
原子引用应该用在你需要做简单的原子(即线程安全,非平凡)对引用的操作,基于监视器的同步不适合这种操作.假设您要检查特定字段是否仅当对象的状态保持为您上次检查时:
Atomic reference should be used in a setting where you need to do simple atomic (i.e. thread-safe, non-trivial) operations on a reference, for which monitor-based synchronization is not appropriate. Suppose you want to check to see if a specific field only if the state of the object remains as you last checked:
AtomicReference<Object> cache = new AtomicReference<Object>();
Object cachedValue = new Object();
cache.set(cachedValue);
//... time passes ...
Object cachedValueToUpdate = cache.get();
//... do some work to transform cachedValueToUpdate into a new version
Object newValue = someFunctionOfOld(cachedValueToUpdate);
boolean success = cache.compareAndSet(cachedValue,cachedValueToUpdate);
由于原子引用语义,即使 cache
对象在线程之间共享,您也可以这样做,而无需使用 synchronized
.一般来说,除非您知道自己在做什么,否则最好使用同步器或 java.util.concurrent
框架而不是纯粹的 Atomic*
.
Because of the atomic reference semantics, you can do this even if the cache
object is shared amongst threads, without using synchronized
. In general, you're better off using synchronizers or the java.util.concurrent
framework rather than bare Atomic*
unless you know what you're doing.
两个优秀的死树参考文献将向您介绍这个主题:
Two excellent dead-tree references which will introduce you to this topic:
注意(我不知道这是否一直都是真的)reference 赋值(即 =
)本身是原子的(更新 primitive 64 位类型如 long
或 double
可能不是原子的;但更新 reference 总是原子的,即使它是 64 位的)没有显式使用 Atomic*
.
请参阅 Java 语言规范 3ed,第 17.7 节.
Note that (I don't know if this has always been true) reference assignment (i.e. =
) is itself atomic (updating primitive 64-bit types like long
or double
may not be atomic; but updating a reference is always atomic, even if it's 64 bit) without explicitly using an Atomic*
.
See the Java Language Specification 3ed, Section 17.7.
这篇关于什么时候在 Java 中使用 AtomicReference?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!