gpt4 book ai didi

java - Varargs、不可变数组和线程安全

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:55:05 25 4
gpt4 key购买 nike

大家好,我有一个不可变数组实现,如下所示:

public static final class FixedArray<T> {
private final T[] array;
public final int Length;

@SafeVarargs
public FixedArray(T... args) {
array = args;
Length = args.length;
}

public T Get(int index) {
return array[index];
}
}

public static final class FixedIntArray {
private final int[] array;
public final int Length;

public FixedIntArray(int... args) {
array = args;
Length = args.length;
}

public int Get(int index) {
return array[index];
}
}

public static final class FixedLongArray {
private final long[] array;
public final int Length;

public FixedLongArray(long... args) {
array = args;
Length = args.length;
}

public long Get(int index) {
return array[index];
}
}

最初我以为它保证是线程安全的。但是看完the discussion关于不可变数组和 Java 内存模型,我一个人相信,我不能确定。

我没有使用防御性副本,调用代码“做正确的事”的契约(和往常一样,如果它不遵守契约,行为是未定义的)。

调用方法如下所示:

public static void main(String args[]) {
int[] ints = new int[10000];
FixedIntArray fixed_ints = new FixedIntArray(ints);
SendToThreadA(fixed_ints);
SendToThreadB(fixed_ints);
SendToThreadC(fixed_ints);
SendToThreadD(fixed_ints);
//caller (which is this method) does the right thing, ints goes out of scope without anyone trying to modify it.
}

我想知道上面的代码是否保证是线程安全的?

最佳答案

因为我们不知道您存储引用的数组(及其值)发生了什么,我认为如果构造函数创建参数数组的副本并设置内部最终引用,您的类会更安全到复制的数组。

关于java - Varargs、不可变数组和线程安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8196431/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com