代码之家  ›  专栏  ›  技术社区  ›  Margus

原子参考阵列有什么用?

  •  10
  • Margus  · 技术社区  · 15 年前

    什么时候使用是个好主意 AtomicReferenceArray ? 请举例说明。

    5 回复  |  直到 10 年前
        1
  •  9
  •   irreputable    15 年前

    AtomicReference[] ,占用的内存少了一点。

    因此,当你需要超过一百万个原子引用时,它是很有用的——无法想出任何用例。

        2
  •  11
  •   dogbane    15 年前

    AtomicReferenceArray 以确保不同线程不能同时更新数组,即一次只能更新一个元素。

    然而,在 AtomicReference[] AtomicReference )多个线程仍然可以同时更新不同的元素,因为原子性是在元素上,而不是在整个数组上。

    here .

        3
  •  1
  •   starblue    15 年前

    参考文献的更新 i 会遵循模式

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

    根据具体情况,这可能比锁定更快和/或更容易使用( synchronized

        4
  •  1
  •   Chetan K    11 年前

    一个可能的用例是ConcurrentHashMap,它在内部广泛使用数组。数组可以是可变的,但在每个元素级别上语义不能是可变的。这是自动阵列产生的原因之一。

        5
  •  0
  •   Vy Do    11 年前
    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