使用parallelStream时抛出InterruptedException - Java

时间:2018-02-15 10:06:07

标签: java parallel-processing java-stream interrupted-exception forkjoinpool

我有一个嵌套for循环的方法如下:

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(),如下所示:

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来解决问题,但我无法弄清楚如何修改我的方法来使用这种方法。

1 个答案:

答案 0 :(得分:1)

如果你想坚持当前的设计,你只需要抓住例外:

.flatMap(spec -> {
     try {
       return getMinimalConstSpecTreeRootedAt(spec).getLeaves().parallelStream();
     } catch (InterruptedException e) {
       // return something else to indicate interruption
       // maybe an empty stream?
     }
 }).map(...)

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