我使用过很多次AtomicLong,但我从来不需要使用AtomicReference
看起来AtomicReference不是这样做的(我从另一个堆栈溢出问题中复制了这段代码):
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;
}或
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?
发布于 2010-05-29 05:05:50
这是一个参考,所以这就是比较的内容。文档清楚地表明,这是一种身份比较,即使在its description.中使用==操作也是如此
我非常频繁地使用AtomicReference和其他原子类。分析表明,它们比使用同步的等效方法执行得更好。例如,AtomicReference上的get()操作只需要从主内存中获取,而使用synchronized的类似操作必须首先将线程缓存的任何值刷新到主存中,然后执行其获取。
AtomicXXX类提供对比较和交换(CAS)操作的本机支持的访问。如果底层系统支持它,那么CAS将比任何用纯Java语言编写的synchronized块的方案都要快。
https://stackoverflow.com/questions/2932505
复制相似问题