Why is CompletableFuture join/get faster in separate streams than using one stream

前端 未结 3 1707
眼角桃花
眼角桃花 2021-01-02 21:51

For the following program I am trying to figure out why using 2 different streams parallelizes the task and using the same stream and calling join/get on the Completable fut

3条回答
  •  长发绾君心
    2021-01-02 22:26

    The stream framework does not define the order in which map operations are executed on stream elements, because it is not intended for use cases in which that might be a relevant issue. As a result, the particular way your second version is executing is equivalent, essentially, to

    List results = new ArrayList<>();
    for (Integer sleepTime : sleepTimes) {
      results.add(CompletableFuture
         .supplyAsync(() -> sleepTask(sleepTime), executorService2)
         .exceptionally(ex -> { ex.printStackTrace(); return -1; }))
         .join());
    }
    

    ...which is itself essentially equivalent to

    List results = new ArrayList<>()
    for (Integer sleepTime : sleepTimes) {
      results.add(sleepTask(sleepTime));
    }
    

提交回复
热议问题