简体   繁体   中英

CompletableFuture.runAsync vs array of CompletableFuture

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM