簡體   English   中英

何時使用AtomicReference(Java)? 真的有必要嗎?

[英]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?

這是一個參考 ,所以這是比較。 該文檔清楚地表明它是一種身份比較,即使在其描述中使用==操作也是如此

我經常使用AtomicReference和其他原子類。 分析表明它們的性能優於使用同步的等效方法。 例如,對AtomicReferenceget()操作只需要從主內存中獲取,而使用synchronized的類似操作必須首先將線程緩存的任何值刷新到主內存,然后執行其獲取。

AtomicXXX類提供對比較和交換(CAS)操作的本機支持的訪問。 如果底層系統支持它,CAS將比純Java中使用synchronized塊生成的任何方案更快。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM