首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用parallelStream - Java时抛出InterruptedException

使用parallelStream - Java时抛出InterruptedException
EN

Stack Overflow用户
提问于 2018-02-15 18:06:07
回答 1查看 950关注 0票数 1

我有一个嵌套了for循环的方法,如下所示:

代码语言:javascript
复制
public MinSpecSetFamily getMinDomSpecSets() throws InterruptedException {
    MinSpecSetFamily result = new MinSpecSetFamily();
    ResourceType minRT = this.getFirstEssentialResourceType();
    if (minRT == null || minRT.noSpecies()) {
        System.out.println("There is something wrong with the "
                + "minimal rticator, such as adjacent to no species. ");
    }
    for (Species spec : minRT.specList) {
        ArrayList<SpecTreeNode> leafList = this.getMinimalConstSpecTreeRootedAt(spec).getLeaves();
        for (SpecTreeNode leaf : leafList) {
            result.addSpecSet(new SpecSet(leaf.getAncestors()));
        }
    }
    return result;
}

这可以很好地工作,但应用程序的性能非常关键,因此我修改了该方法以使用parallelStream(),如下所示:

代码语言:javascript
复制
public MinSpecSetFamily getMinDomSpecSets() throws InterruptedException {
    ResourceType minRT = this.getFirstEssentialResourceType();
    if (minRT == null || minRT.noSpecies()) {
        System.out.println("There is something wrong with the "
                + "minimal rticator, such as adjacent to no species. ");
    }

    MinSpecSetFamily result = minRT.specList.parallelStream()
            .flatMap(spec -> getMinimalConstSpecTreeRootedAt(spec).getLeaves().parallelStream())
            .map(leaf -> new SpecSet(leaf.getAncestors()))
            .collect(MinSpecSetFamily::new, MinSpecSetFamily::addSpecSet, MinSpecSetFamily::addMSSF);
    return result;
}

在我想在'getLeaves()‘方法中引入一个InterruptedException之前,这个方法运行得很好。现在parallelStream版本将不会编译,因为它说我有一个未报告的InterruptedException,必须捕获或声明抛出。我认为这是因为parallelStream运行在多个线程上。我的IDE建议的try/catch块的组合不能解决这个问题。

发布在Interrupt parallel Stream execution上的第二个解决方案表明,我也许能够使用ForkJoinPool解决这个问题,但是我一直不知道如何修改我的方法来使用这种方法。

EN

回答 1

Stack Overflow用户

发布于 2018-02-15 18:12:17

如果你想坚持你当前的设计,你只需要捕捉异常:

代码语言:javascript
复制
.flatMap(spec -> {
     try {
       return getMinimalConstSpecTreeRootedAt(spec).getLeaves().parallelStream();
     } catch (InterruptedException e) {
       // return something else to indicate interruption
       // maybe an empty stream?
     }
 }).map(...)

请注意,并行流的并行流可能是不必要的,并且仅对顶级流进行并行化可能在性能方面就足够了。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48804493

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档