与 CompletablFuture 和 ExecutorService 并行调用方法

Call method in parallel with CompletablFuture and ExecutorService

我正在尝试为 products 中的每个 product 并行调用 getPrice 方法。我有这段代码并验证了 getPrice 在不同的线程中是 运行,但它们是 运行 顺序的,而不是并行的。谁能指出我在这里缺少什么?

非常感谢您的帮助。

   ExecutorService service = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
   Set<Product> decoratedProductSet = products.stream()
   .map(product -> CompletableFuture
                             .supplyAsync(() -> getPrice(product.getId(), date, context), service))
   .map(t -> t.exceptionally(throwable -> null))
   .map(t -> t.join())
   .collect(Collectors.<Product>toSet());

您正在流式传输您的产品,将每个产品发送到 CompletableFuture,然后在流处理下一个之前等待加入。

为什么不使用:

products.parallelStream()
 .map(p -> getPrice(p.getId(), date, context))
 .collect(Collectors.<Product>toSet());