Ada*_*ent 6 java concurrency atomic
我已多次使用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;
}
Run Code Online (Sandbox Code Playgroud)
要么
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;
}
Run Code Online (Sandbox Code Playgroud)
假设this.someList标记为volatile.
我不确定它是哪一个因为如果使用了.equals,javadoc和该类的代码都不清楚.
看到上面的方法并不是那么难写,有没有人用过AtomicReference?