如何在Java中声明数组元素volatile ?

时间:2021-04-30 07:09:39

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

是否有方法在Java中声明数组元素volatile ?即。

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

declares the array reference volatile, but the array elements (e.g. a[1]) are still not volatile. So I'm looking for something like

声明数组引用volatile,但是数组元素(例如[1])仍然不是volatile。我要找的是

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

but it doesn't work that way. Is it possible at all?

但事实并非如此。有可能吗?

2 个解决方案

#1


27  

Use AtomicIntegerArray or AtomicLongArray or AtomicReferenceArray

使用AtomicIntegerArray或AtomicLongArray或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).

AtomicIntegerArray类实现了一个int数组,它的各个字段可以通过类的get()和set()方法使用volatile语义访问。加勒比海盗。从一个线程中设置(x, y),然后保证调用arr.get(x)的另一个线程将读取值y(直到另一个值被读取到位置x)。

See:

看到的:

#2


6  

No, you can't make array elements volatile. See also http://jeremymanson.blogspot.com/2009/06/volatile-arrays-in-java.html .

不,你不能让数组元素不稳定。参见http://jeremymanson.blogspot.com/2009/06/volatile-arrays-in-java.html。

#1


27  

Use AtomicIntegerArray or AtomicLongArray or AtomicReferenceArray

使用AtomicIntegerArray或AtomicLongArray或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).

AtomicIntegerArray类实现了一个int数组,它的各个字段可以通过类的get()和set()方法使用volatile语义访问。加勒比海盗。从一个线程中设置(x, y),然后保证调用arr.get(x)的另一个线程将读取值y(直到另一个值被读取到位置x)。

See:

看到的:

#2


6  

No, you can't make array elements volatile. See also http://jeremymanson.blogspot.com/2009/06/volatile-arrays-in-java.html .

不,你不能让数组元素不稳定。参见http://jeremymanson.blogspot.com/2009/06/volatile-arrays-in-java.html。