How to declare array elements volatile in Java?

前端 未结 4 989
别那么骄傲
别那么骄傲 2020-12-02 23:02

Is there a way to declare array elements volatile in Java? I.e.

volatile int[] a = new int[10];

declares the array referen

4条回答
  •  旧时难觅i
    2020-12-02 23:15

    Use AtomicIntegerArray or AtomicLongArray or AtomicReferenceArray

    The AtomicIntegerArray class implements an int array whose individual fields can be accessed with volatile semantics, via the class's get() and set() methods. Calling arr.set(x, y) from one thread will then guarantee that another thread calling arr.get(x) will read the value y (until another value is read to position x).

    See:

    • AtomicIntegerArray
    • AtomicLongArray
    • AtomicReferenceArray
    • java.util.concurrent.atomic Package Summary

提交回复
热议问题