Home » Java » java – CompletableFuture.runAsync vs array of CompletableFuture-Exceptionshub

java – CompletableFuture.runAsync vs array of CompletableFuture-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I found this code in a project:

int threadCount = 10;
CompletableFuture<?>[] futures = new CompletableFuture<?>[threadCount];
for (int i = 0; i < threadCount; i++) {
    futures[i] = CompletableFuture.runAsync(() -> { process.run(queue); });
}
// Wait all futures
CompletableFuture.allOf(futures).join();

What’s the difference with doing this?

ExecutorService threadPool = Executors.newFixedThreadPool(threadCount);
CompletableFuture.runAsync(() -> { process.run(queue); }, threadPool );

Thanks for your explanation.

How to&Answers:
int threadCount = 10;
CompletableFuture<?>[] futures = new CompletableFuture<?>[threadCount];
for (int i = 0; i < threadCount; i++) {
    futures[i] = CompletableFuture.runAsync(() -> { process.run(queue); });
}
// Wait all futures
CompletableFuture.allOf(futures).join();

In this case, you creates set of completable futures which are result of executing asynchronous code in common ForkJoin pool. Then process waits until all futures are completed.

ExecutorService threadPool = Executors.newFixedThreadPool(threadCount);
CompletableFuture.runAsync(() -> { process.run(queue); }, threadPool );

In this case, you are executing code in specified thread pool.

The differences between these code blocks

  • They are executed in different thread pools (first in common ForkJoin which is default for completable futures, second in specified thread pool)
  • In first case you are waiting for set of tasks to be completed, in second – you just running task asynchronously