【问题标题】:Call method in parallel with CompletablFuture and ExecutorService与 CompletablFuture 和 ExecutorService 并行调用方法
【发布时间】:2016-08-06 17:46:24
【问题描述】:

我正在尝试为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());

【问题讨论】:

    标签: java-8 executorservice completable-future


    【解决方案1】:

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

    为什么不使用:

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

    【讨论】:

      猜你喜欢
      • 2015-07-06
      • 2022-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-22
      • 2016-12-23
      • 1970-01-01
      相关资源
      最近更新 更多