[英]When to use AtomicReference (Java)? Is it really necessary?
我已多次使用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?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.