2010-09-29 136 views

回答

6

看起來像是在功能上等同於AtomicReference[],儘管佔用的內存較少。

因此,當您需要超過一百萬個原子引用時,它非常有用 - 無法想象任何用例。

+0

不完全正確 - 請參閱法赫德的描述答案。 – aperkins 2010-09-29 17:21:39

+1

比接受的答案好得多。它比AtomicReference []節省了空間 - 不安全類的一個副本,它可以處理大量的對象引用。 – themightyjon 2012-10-05 16:15:11

1

如果您有大量同時更新的對象,例如在大型多人遊戲中,它可能會很有用。

的參考i的更新將遵循的模式

boolean success = false; 
while (!success) 
{ 
    E previous = atomicReferenceArray.get(i); 
    E next = ... // compute updated object 
    success = atomicReferenceArray.compareAndSet(i, previous, next); 
} 

根據不同的情況下,這可能會更快和/或更容易比鎖定(​​)使用。

8

如果您有一個共享的對象引用數組,那麼您將使用AtomicReferenceArray來確保該數組不能同時被不同的線程更新,即一次只能更新一個元素。

但是,在AtomicReference[]AtomicReference的數組)中,多個線程仍然可以模擬地更新不同的元素,因爲原子性位於元素上,而不是整個陣列上。

更多信息here

+1

多個線程可以同時更新AtomicReferenceArray元素。 – irreputable 2010-09-29 17:36:23

+0

他們不能。閱讀我發佈的鏈接。 – dogbane 2010-09-29 17:56:30

+0

那麼'AtomicReferenceArray'和'AtomicReference []'有什麼區別? Sun的實施是由Doug Lea完成的。 – dogbane 2010-09-30 07:08:51

1

一個可能的用例應該是內部廣泛使用數組的ConcurrentHashMap。數組可以是不穩定的,但是在每個元素級別,語義不能是易失性的。這是自動陣列誕生的原因之一。

0
import java.util.concurrent.atomic.AtomicReferenceArray; 

public class AtomicReferenceArrayExample { 
    AtomicReferenceArray<String> arr = new AtomicReferenceArray<String>(10); 

    public static void main(String... args) { 
     new Thread(new AtomicReferenceArrayExample().new AddThread()).start(); 
     new Thread(new AtomicReferenceArrayExample().new AddThread()).start(); 
    } 

    class AddThread implements Runnable { 
     @Override 
     public void run() { 
      // Sets value at the index 1 
      arr.set(0, "A"); 
      // At index 0, if current reference is "A" then it changes as "B". 
      arr.compareAndSet(0, "A", "B"); 
      // At index 0, if current value is "B", then it is sets as "C". 
      arr.weakCompareAndSet(0, "B", "C"); 
      System.out.println(arr.get(0)); 
     } 
    } 

} 

// Result: 
//  C 
//  C 
+1

你能解釋一下這段代碼嗎? – Twisty 2016-03-13 16:23:55