我需要使ArrayLists的ArrayList线程安全.我也无法让客户对集合进行更改.不可修改的包装器是否会使其线程安全,或者我需要在集合上使用两个包装器?
我想了解是否volatile需要发布不可变对象.
例如,假设我们有一个不可变对象A:
// class A is immutable
class A {
final int field1;
final int field2;
public A(int f1, int f2) {
field1 = f1;
field2 = f2;
}
}
Run Code Online (Sandbox Code Playgroud)
然后我们有一个B从不同线程访问的类.它包含对类对象的引用A:
// class B publishes object of class A through a public filed
class B {
private /* volatile? */ A toShare;
// this getter might be called from different threads
public A getA(){
return toShare;
}
// this might be called …Run Code Online (Sandbox Code Playgroud) 我有一个字符串(tagList)列表需要在多个线程之间共享进行读取,所以我创建了一个不可修改的版本并将其传递给线程,我不确定它是否是线程安全的,因为线程只读取该列表所以我猜应该没问题?
当我将该不可修改的列表传递给线程时,它是否传递单个副本并由线程共享,还是创建多个副本并将一个副本传递给每个线程?
这是我的代码:
final List<String> tList = Collections.unmodifiableList(tagList);
List<Future<Void>> calls = new ArrayList<Future<Void>>();
FileStatus[] fsta = _fileSystem.listStatus(p);
for (FileStatus sta : fsta) {
final Path path = new Path(sta.getPath(), "data.txt");
if (!_fileSystem.exists(path)) {
continue;
}
else {
calls.add(_exec.submit(new Callable<Void>() {
@Override
public Void call() throws Exception {
filterData(path, tList);
return null;
}
}));
}
}
Run Code Online (Sandbox Code Playgroud)