何时在Java中使用AtomicReference? [英] When to use AtomicReference in Java?

查看:184
本文介绍了何时在Java中使用AtomicReference?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们何时使用AtomicReference?



是否需要在所有多线程程序中创建对象?



提供一个应该使用AtomicReference的简单示例。

解决方案

原子参考应该在你需要做的简单的设置中使用<对引用执行的em> atomic (即线程安全,非平凡)操作,基于监视器的同步不适用。假设您要检查特定字段是否仅在上次检查时对象的状态仍然存在:

  AtomicReference<对象> cache = new AtomicReference< Object>(); 

Object cachedValue = new Object();
cache.set(cachedValue);

// ...时间通过...
对象cachedValueToUpdate = cache.get();
// ...做一些工作将cachedValueToUpdate转换为新版本
Object newValue = someFunctionOfOld(cachedValueToUpdate);
boolean success = cache.compareAndSet(cachedValue,cachedValueToUpdate);

由于原子引用语义,即使缓存也可以这样做对象在线程之间共享,而不使用 synchronized 。一般情况下,最好使用同步器或 java.util.concurrent 框架而不是裸 Atomic * 除非你知道你在做什么。



两个优秀的死树引用,它们将向您介绍这个主题:





<请注意(我不知道这是否一直都是真的) reference 赋值(即 = )本身就是原子的(更新原始 64位类型,如 long double 可能不是原子的;但更新 reference 总是原子的,即使它是64位的)没有显式使用 Atomic *

参见 Java语言规范3ed,第17.7节


When do we use AtomicReference?

Is it needed to create objects in all multithreaded programs?

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);

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:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆