CompletableFuture::supplyAsync(() -> IO bound queries)
How do I chose an Executor for CompletableFuture::supplyAsync to avoid polluting the ForkJoinPool.commonPool()
.
There are many options in Executors
(newCachedThreadPool
, newWorkStealingPool
, newFixedThreadPool
etc)
And I read about new ForkJoinPool here
How do I chose the right one for my use case ?
supplyAsync(Supplier<U> supplier) Returns a new CompletableFuture that is asynchronously completed by a task running in the ForkJoinPool. commonPool() with the value obtained by calling the given Supplier. static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier, Executor executor)
The difference between runAsync() and supplyAsync() is that the former returns a Void while supplyAsync() returns a value obtained by the Supplier. Both methods also support a second input argument — a custom Executor to submit tasks to.
Yes! CompletableFuture executes these tasks in a thread obtained from the global ForkJoinPool. commonPool(). But hey, you can also create a Thread Pool and pass it to runAsync() and supplyAsync() methods to let them execute their tasks in a thread obtained from your thread pool.
What is CompletableFuture? A CompltableFuture is used for asynchronous programming. Asynchronous programming means writing non-blocking code. It runs a task on a separate thread than the main application thread and notifies the main thread about its progress, completion or failure.
You should use public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier, Executor executor)
method.
As executor you can use any from the Executors.new.. - it depends on your needs.
It's better to use newFixedThreadPool() rather than newCachedThreadPool(), since newCachedThreadPool() can lead to performance issues creating to many threads or even throw OutOfMemoryError.
Here's a very nice article with good examples.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With