我已经多次使用 AtomicLong 但我从未需要使用 AtomicReference
看来 AtomicReference 可以做到其中之一(我从另一个 stackoverflow 复制了这段代码
问题):
public synchronized boolean compareAndSet(List<Object> oldValue, List<Object> 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;
}
Or
public synchronized boolean compareAndSet(List<Object> oldValue, List<Object> 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 被标记为易失性。
我不确定它到底是哪一个,因为 javadoc 和该类的代码不清楚是否使用 .equals 。
看到上面的方法并不那么难写,有人用过 AtomicReference 吗?
It's a 参考,这就是比较的结果。该文档非常清楚地表明这是一个身份比较,即使使用==
操作于它的描述。
I use AtomicReference
和其他原子类非常频繁。分析表明,它们的性能优于使用同步的等效方法。例如,一个get()
操作于AtomicReference
仅需要从主存中获取,而使用类似的操作synchronized
必须首先将线程缓存的所有值刷新到主内存,然后执行其获取。
The AtomicXXX
类提供对比较和交换 (CAS) 操作的本机支持的访问。如果底层系统支持,CAS 将比任何用它编写的方案都要快synchronized
纯 Java 中的块。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)