CompletableFuture与parallelStream()性能差异
private static int getJob() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
return 50;
}private static long testParallelStream(int jobCount) {
List<Supplier<Integer>> tasks = new ArrayList<>();
IntStream.rangeClosed(1, jobCount).forEach(value -> tasks.add(Main::getJob));
long start = System.currentTimeMillis();
int sum = tasks.parallelStream().map(Supplier::get).mapToInt(Integer::intValue).sum();
return System.currentTimeMillis() - start;
}
private static long testCompletableFutureDefaultExecutor(int jobCount) {
List<CompletableFuture<Integer>> tasks = new ArrayList<>();
IntStream.rangeClosed(1, jobCount).forEach(value -> tasks.add(CompletableFuture.supplyAsync(Main::getJob)));
long start = System.currentTimeMillis();
int sum = tasks.stream().map(CompletableFuture::join).mapToInt(Integer::intValue).sum();
return System.currentTimeMillis() - start;
}

Last updated