I have a method with nested for loops as follows:
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;
}
This works fine, but the application is performance critical so I modified the method to use parallelStream()
as follows:
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;
}
This worked fine until I wanted to introduce an InterruptedException
in the 'getLeaves()' method. Now the parallelStream
version will not compile as it says I have an unreported InterruptedException
which must be caught or declared to be thrown. I think this is because the parallelStream
runs on multiple threads. No combination of try/catch blocks suggested by my IDE resolves the issue.
The second solution posted in Interrupt parallel Stream execution
suggests that I may be able to resolve the issue using ForkJoinPool
but I have been unable to figure out how to modify my method to use this approach.