【发布时间】:2010-05-28 21:03:09
【问题描述】:
我用过很多次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;
}
或者
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 被标记为 volatile。
我不确定它到底是哪一个,因为如果使用 .equals,javadoc 和该类的代码不清楚。
看到上面的方法不是那么难写,有没有人使用过 AtomicReference?
【问题讨论】:
-
They曾经用过。
标签: java concurrency atomic