我需要同步invokeAll调用的结果吗? [英] Do I need to synchronize on the result of an invokeAll call?

查看:352
本文介绍了我需要同步invokeAll调用的结果吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am enhancing an existing algorithm that consists of multiple independent steps to use concurrent tasks. Each of the tasks will create multiple objects to hold its results. In the end, I would like to have a list of all the results to return from the controlling method. At the moment, my code looks something like that

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;
    }
}

我真的需要 synchronized 在## A ##,以强制与工作任务中的修改操作的发生先前的关系?或者我可以依赖所有的写操作发生在 invokeAll 返回后,并且对控制线程可见?是否有任何原因,为什么我不应该从自己的同步块中返回结果集合?

Do I actually need the synchronized at "## A ##" to enforce a happens-before relationship with the modifying operations in the worker tasks? Or can I rely on all write operations to have happened after invokeAll returns and be visible to the controlling thread? And is there any reason, why I should not return the results collection from within its own synchronized block?

推荐答案

不,你不需要。 invokeAll 说明所有作业在返回时都应该完成。因此,当您到达return语句时,不应再有其他访问权限。

No, you don't need that. The documentation of invokeAll states that all jobs should be done when it returns. So there should be no further access to collect when you reach the return statement.

这篇关于我需要同步invokeAll调用的结果吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆