import java.util.concurrent.ForkJoinPool; //导入方法依赖的package包/类
/**
* Applies the given function to every element of the given collection and returns a Collection of the results.
*
* @param function the function which is applied to every element of collection
* @param collection the elements
* @param Input (argument) type
* @param Result type
* @return a collection of results of the function
* @throws PSRSSException if the parallel execution failed
*/
private Collection map(final Function function, Iterable collection) throws PSRSSException {
ForkJoinPool pool = new ForkJoinPool(Runtime.getRuntime().availableProcessors());
Collection> tasks = new LinkedList<>();
for (final E item : collection) {
tasks.add(new Callable() {
@Override
public R call() throws Exception {
return function.execute(item);
}
});
}
List> futures = pool.invokeAll(tasks);
Collection results = new ArrayList<>(futures.size());
for (Future future : futures) {
if (!future.isCancelled()) {
try {
results.add(future.get());
} catch (InterruptedException | ExecutionException e) {
throw new PSRSSException(e);
}
} else {
throw new PSRSSException("Parallel execution failed");
}
}
pool.shutdown();
return results;
}