【发布时间】:2018-07-26 01:08:42
【问题描述】:
我有一个嵌套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 解决问题,但我一直无法弄清楚如何修改我的方法以使用这种方法。
【问题讨论】:
-
An
InterruptedException是一个检查异常,因此是编译问题。并行运行它实际上并不重要,您需要一种方法将此异常从流内部传递到流外部。
标签: java parallel-processing java-stream interrupted-exception forkjoinpool