问题
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 ?
回答1:
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.
回答2:
Adding to Anton's Answer, it is wise to use newFixedThreadPool rather than newCachedThreadPool unless you know the operation will not cause OutOfMemoryError. Since, your request is an i/o process the usage of Async nio request such as AsynchronousFileChannel or Async Rest Client...etc could greatly supplement your performance.
来源:https://stackoverflow.com/questions/33377177/how-to-chose-an-executor-for-completablefuturesupplyasync