何时使用AtomicReference(Java)? 真的有必要吗?
我已多次使用AtomicLong,但我从未需要使用AtomicReference
似乎AtomicReference做了(我从另一个stackoverflow问题复制了这个代码):
public synchronized boolean compareAndSet(List oldValue, List newValue) { if (this.someList == oldValue) { // someList could be changed by another thread after that compare, // and before this set this.someList = newValue; return true; } return false; }
要么
public synchronized boolean compareAndSet(List oldValue, List newValue) { if (this.someList == oldValue || this.someList.equals(oldValue)) { // someList could be changed by another thread after that compare, // and before this set this.someList = newValue; return true; } return false; }
假设this.someList标记为volatile。
我不确定它是哪一个因为如果使用了.equals,javadoc和该类的代码都不清楚。
看到上面的方法并不是那么难写,有没有人用过AtomicReference?
这是一个参考 ,所以这是比较。 该文档清楚地表明它是一种身份比较,即使在其描述中使用==
操作也是如此。
我经常使用AtomicReference
和其他primefaces类。 分析表明它们的性能优于使用同步的等效方法。 例如, AtomicReference
上的get()
操作只需要从主内存中获取,而使用synchronized
的类似操作必须首先将线程缓存的任何值刷新到主内存,然后执行其获取。
AtomicXXX
类提供对比较和交换(CAS)操作的本机支持的访问。 如果底层系统支持它,CAS将比纯Java中使用synchronized
块生成的任何方案更快。