如何用Java声明数组元素volatile?

Joo*_*kka 35 java arrays concurrency volatile

有没有办法volatile在Java中声明数组元素?即

volatile int[] a = new int[10];
Run Code Online (Sandbox Code Playgroud)

声明数组引用 volatile,但数组元素(例如a[1])仍然不是volatile.所以我正在寻找类似的东西

volatile int[] a = new volatile int[10];
Run Code Online (Sandbox Code Playgroud)

但它不会那样工作.有可能吗?

uth*_*ark 30

使用AtomicIntegerArrayAtomicLongArrayAtomicReferenceArray

AtomicIntegerArray类实现通过类的一个int数组,其单独的字段可与易失性的语义来访问,get()set()方法.arr.set(x, y)从一个线程调用将保证另一个线程调用arr.get(x)将读取值y(直到另一个值被读取到位置x).

看到:

  • @JoonasPulakka其他原始类型,你也可以将它们转换为int或长期使用如`Float.floatToIntBits(浮动)`.这避免了在使用`AtomicReferenceArray`时需要装箱. (4认同)

SWd*_*WdV 6

另一种方法是使用 JDK 9+VarHandle类。正如您在AtomicxxxArray类的源代码中看到的AtomicIntegerArray,这些类也VarHandle从 JDK 9 开始使用:

//[...]

private static final VarHandle AA
    = MethodHandles.arrayElementVarHandle(int[].class);
private final int[] array;

//[...]

/**
 * Returns the current value of the element at index {@code i},
 * with memory effects as specified by {@link VarHandle#getVolatile}.
 *
 * @param i the index
 * @return the current value
 */
public final int get(int i) {
    return (int)AA.getVolatile(array, i);
}

/**
 * Sets the element at index {@code i} to {@code newValue},
 * with memory effects as specified by {@link VarHandle#setVolatile}.
 *
 * @param i the index
 * @param newValue the new value
 */
public final void set(int i, int newValue) {
    AA.setVolatile(array, i, newValue);
}

//[...]
Run Code Online (Sandbox Code Playgroud)

你首先创建一个VarHandle这样的:

MethodHandles.arrayElementVarHandle(yourArrayClass)
Run Code Online (Sandbox Code Playgroud)

比如你可以byte[].class在这里输入实现缺失的AtomicByteArray自己。

然后您可以使用setxxx(array, index, value)getxxx(array, index)方法访问它,其中array是 type yourArrayClassindexis of type intvalue是数组中元素的类型(yourArrayClass.getComponentType() )。

请注意,例如,如果yourArrayClass == byte[].class您输入42as value,则会出现错误,因为42is anint而不是 abyte并且访问方法的Object...参数是 vararg参数:

java.lang.invoke.WrongMethodTypeException: cannot convert MethodHandle(VarHandle,byte[],int,byte)void to (VarHandle,byte[],int,int)void
Run Code Online (Sandbox Code Playgroud)

(第二个签名是您使用的签名,第一个是您应该使用的签名。)


请注意,在 JDK 8 及以下版本sun.misc.Unsafe中用于实现原子类,例如AtomicIntegerArray

//[...]

private static final Unsafe unsafe = Unsafe.getUnsafe();
private static final int base = unsafe.arrayBaseOffset(int[].class);
private static final int shift;
private final int[] array;

static {
    int scale = unsafe.arrayIndexScale(int[].class);
    if ((scale & (scale - 1)) != 0)
        throw new Error("data type scale not a power of two");
    shift = 31 - Integer.numberOfLeadingZeros(scale);
}

private long checkedByteOffset(int i) {
    if (i < 0 || i >= array.length)
        throw new IndexOutOfBoundsException("index " + i);

    return byteOffset(i);
}

private static long byteOffset(int i) {
    return ((long) i << shift) + base;
}

//[...]

/**
 * Gets the current value at position {@code i}.
 *
 * @param i the index
 * @return the current value
 */
public final int get(int i) {
    return getRaw(checkedByteOffset(i));
}

private int getRaw(long offset) {
    return unsafe.getIntVolatile(array, offset);
}

/**
 * Sets the element at position {@code i} to the given value.
 *
 * @param i the index
 * @param newValue the new value
 */
public final void set(int i, int newValue) {
    unsafe.putIntVolatile(array, checkedByteOffset(i), newValue);
}

//[...]
Run Code Online (Sandbox Code Playgroud)

使用Unsafe仍然是一种选择(虽然我认为获取实例有点棘手),但不鼓励这样做,因为您必须自己检查数组边界,并且如果您犯了错误,它可能会导致 Java 进程出现段错误,而VarHandle边界会为您检查如果给定的索引超出范围,则抛出 Java 异常(但这可能会带来性能成本)。除此之外,Unsafe不受官方支持,可能随时被删除。

但是从 JDK 10 开始UnsafeAtomicInteger由于“未解决的循环启动依赖项”,仍然在使用。


如果您想了解有关可用的不同 get 和 set 方法的更多信息,请查看使用 JDK 9 内存顺序模式(我不得不说我根本不是这方面的专家(还?))。


请注意,截至今天,您无法VarHandle在 Kotlin 中使用,因为它将Object...get 和 set 方法的 vararg参数包装在中Object[],请参阅错误 KT-26165

java.lang.invoke.WrongMethodTypeException: cannot convert MethodHandle(VarHandle,byte[],int,byte)void to (VarHandle,Object[])void
Run Code Online (Sandbox Code Playgroud)

(现在应该修复)