gpt4 book ai didi

java - 我是否需要同步 invokeAll 调用的结果?

转载 作者:搜寻专家 更新时间:2023-11-01 03:14:51 27 4
gpt4 key购买 nike

我正在增强现有算法,该算法由多个独立步骤组成以使用并发任务。每个任务都将创建多个对象来保存其结果。最后,我想要一个从控制方法返回的所有结果的列表。目前,我的代码看起来像这样

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/

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