Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to chose an Executor for CompletableFuture::supplyAsync

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 ?

like image 976
premprakash Avatar asked Oct 27 '15 19:10

premprakash


People also ask

What is supplyAsync in CompletableFuture?

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)

What is the difference between runAsync and supplyAsync?

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.

Does CompletableFuture use ForkJoinPool?

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.

When should I use CompletableFuture?

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.


1 Answers

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.

like image 107
Anton Antonenko Avatar answered Sep 21 '22 16:09

Anton Antonenko