How to chose an Executor for CompletableFuture::supplyAsync

狂风中的少年 提交于 2019-12-20 12:04:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!