我正在改进一个由多个独立步骤组成的算法,以使用并发任务。每个任务将创建多个对象来保存其结果。最终,我希望从控制方法返回所有结果的列表。目前,我的代码大致如下:
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
来强制执行与修改操作之间的happens-before关系?或者我可以依赖于所有写操作已经发生在invokeAll
返回之后,并且对控制线程可见吗?并且是否有任何理由,不应该从其自己的synchronized
块中返回结果集合?