我有一个嵌套了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解决这个问题,但是我一直不知道如何修改我的方法来使用这种方法。
发布于 2018-02-15 18:12:17
如果你想坚持你当前的设计,你只需要捕捉异常:
.flatMap(spec -> {
try {
return getMinimalConstSpecTreeRootedAt(spec).getLeaves().parallelStream();
} catch (InterruptedException e) {
// return something else to indicate interruption
// maybe an empty stream?
}
}).map(...)请注意,并行流的并行流可能是不必要的,并且仅对顶级流进行并行化可能在性能方面就足够了。
https://stackoverflow.com/questions/48804493
复制相似问题