如何为CompletableFuture :: supplyAsync选择Executor
CompletableFuture::supplyAsync(() -> IO bound queries)
如何为CompletableFuture :: supplyAsync选择Executor以避免污染ForkJoinPool.commonPool()
。
Executors
有很多选项( newCachedThreadPool
, newWorkStealingPool
, newFixedThreadPool
等)
我在这里阅读了有关新ForkJoinPool的内容
如何为我的用例选择合适的一个?
您应该使用public static CompletableFuture supplyAsync(Supplier supplier, Executor executor)
方法。 作为执行者,您可以使用Executors.new中的任何一个.. – 这取决于您的需求。 最好使用newFixedThreadPool()而不是newCachedThreadPool(),因为newCachedThreadPool()可能导致创建到许multithreading的性能问题,甚至抛出OutOfMemoryError。 这是一篇非常好的文章,有很好的例子。
添加到Anton的答案中,使用newFixedThreadPool而不是newCachedThreadPool是明智的,除非您知道该操作不会导致OutOfMemoryError。 因为,您的请求是一个I / O进程,Async nio请求的使用,如AsynchronousFileChannel或Async Rest Client …等可以极大地补充您的性能。