Glide
Glide

Reputation: 21275

CompletableFuture supplyAsync(supplier) vs supplyAsync(supplier, executor)

Java Docs says CompletableFuture:supplyAsync(Supplier<U> supplier) runs the task in the ForkJoinPool#commonPool() whereas the CompletableFuture:suppleAsync(supplier, executor) runs it in the given executor.

I'm trying to figure out which one to use. So my questions are:

  1. What is the ForkJoinPool#commonPool()?
  2. When should I use supplyAsync(supplier) vs supplyAsync(supplier, executor)?

Upvotes: 4

Views: 2299

Answers (1)

Jai
Jai

Reputation: 8363

ForkJoinPool#commonPool() is the common pool of threads that Java API provides. If you ever used stream API, then the parallel operations are also done in this thread pool.

The advantage of using the common thread pool is that Java API would manage that for you - from creation to destruction. The disadvantage is that you would expect a lot of classes to share the usage of this pool.

If you used an executor, then it is like owning a private pool, so nothing is going to fight with you over the usage. You make to create the executor yourself, and pass it into CompletableFuture. However, do note that, eventually the actual performance would still depend on what is being done in the threads, and by your hardware.

Generally, I find it fine to use the common thread pool for doing more computationally intensive stuff, while executor would be better for doing things that would have to wait for things (like IO). When you "sleep" in common thread pool thread, it is like using a cubicle in a public washroom to play games on your mobile phone - someone else could be waiting for the cubicle.

Upvotes: 5

Related Questions