如何为CompletableFuture :: supplyAsync选择Executor

pre*_*ash 14 java executorservice java-8 threadpoolexecutor completable-future

CompletableFuture::supplyAsync(() -> IO bound queries)

如何为CompletableFuture :: supplyAsync选择Executor以避免污染ForkJoinPool.commonPool().

有许多选项Executors(newCachedThreadPool,newWorkStealingPool,newFixedThreadPool等)

在这里阅读了关于新ForkJoinPool的内容

如何为我的用例选择合适的?

小智 6

你应该使用public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier, Executor executor)方法。作为执行人,您可以使用 Executors.new 中的任何一个.. - 这取决于您的需要。最好使用 newFixedThreadPool() 而不是 newCachedThreadPool(),因为 newCachedThreadPool() 会导致性能问题,创建多个线程甚至抛出 OutOfMemoryError。这是一篇很好的文章,里面有很好的例子。