我已经使用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吗?