如何为CompletableFuture :: supplyAsync选择Executor [英] How to chose an Executor for CompletableFuture::supplyAsync
问题描述
CompletableFuture :: supplyAsync(() - > IO约束查询)
如何选择CompletableFuture :: supplyAsync的执行程序,以避免污染 ForkJoinPool.commonPool()
。
How do I chose an Executor for CompletableFuture::supplyAsync to avoid polluting the ForkJoinPool.commonPool()
.
执行者
中有很多选项( newCachedThreadPool
, newWorkStealingPool
, newFixedThreadPool
etc)
There are many options in Executors
(newCachedThreadPool
, newWorkStealingPool
, newFixedThreadPool
etc)
我读了一下新的ForkJoinPool 这里
And I read about new ForkJoinPool here
如何选择合适的用例?
How do I chose the right one for my use case ?
推荐答案
您应该使用 public static< U> CompletableFuture< U> supplyAsync(供应商< U>供应商,Executor执行者)
方法。
作为执行人,您可以使用Executors.new中的任何一个.. - 这取决于您的需求。
最好使用newFixedThreadPool()而不是newCachedThreadPool(),因为newCachedThreadPool()会导致创建到许多线程的性能问题,甚至抛出OutOfMemoryError。
这是一个非常好的文章有很好的例子。
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.
这篇关于如何为CompletableFuture :: supplyAsync选择Executor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!