作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
大家好,我有一个不可变数组实现,如下所示:
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/
我是一名优秀的程序员,十分优秀!