我正在增强现有算法,该算法由多个独立步骤组成以使用并发任务。每个任务都将创建多个对象来保存其结果。最后,我想要一个从控制方法返回的所有结果的列表。目前,我的代码看起来像这样
private final ExecutorService pool = ...;
// A single task to be performed concurrently with other tasks.
private class WorkHorse implements Callable<Void> {
private final Collection<X> collect;
public WorkHorse(Collection<X> collect, ...) {
this.collect = collect;
}
public Void call() {
for (...) {
// do work
synchronized (this.collect) {
this.collect.add(result);
}
}
return null;
}
}
// Uses multiple concurrent tasks to compute its result list.
public Collection<X> getResults() {
// this list is supposed to hold the results
final Collection<X> collect = new LinkedList<X>();
final List<WorkHorse> tasks = Arrays.asList(
new WorkHorse(collect, ...), new WorkHorse(collect, ...), ...);
this.pool.invokeAll(tasks);
// ## A ##
synchronized (collect) {
return collect;
}
}
我真的需要“## A ##”处的 synchronized
来强制与工作任务中的修改操作发生先行关系吗?或者我可以依赖所有写操作在 invokeAll
返回后发生并且对控制线程可见吗?有什么理由,为什么我不应该从它自己的 synchronized
block 中返回结果集合?
最佳答案
不,你不需要那个。 invokeAll 的文档声明所有工作都应该在它返回时完成。因此,当您到达返回语句时,应该没有进一步的访问权限。
关于java - 我是否需要同步 invokeAll 调用的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1360936/