【问题标题】:Completable Future inside completable futureCompletablefuture 里面的 Completablefuture
【发布时间】:2019-09-18 18:39:54
【问题描述】:

我的代码中有几个完整的未来。在一个可完成的未来内,我想要另一个可完成的未来(可完成的未来在可完成的未来内),例如

public CompletableFuture<List<Employee>> buildEmployee (List<EmployeeResponse> employeeInfo) {
    return supplyAsync(() -> {

        Map<String, List<EmployeeReward>> rewards = rewards(employeeInfo);
        Map<String, List<EmployeePoints>> points = points(employeeInfo);
    }, executor);
}

在上述方法中,奖励和积分是两个独立的顺序调用,我希望它为我尝试过的它们并行调用 -

public CompletableFuture<List<Employee>> buildEmployee (List<EmployeeResponse> employeeInfo) {
    return supplyAsync(() -> {

        CompletableFuture<Map<String, List<EmployeeReward>>> rewards = reward(employeeInfo);
        CompletableFuture<Map<String, List<EmployeePoints>>> points = points(employeeInfo);

        CompletableFuture<Void> futures = allOf(rewards, points);
    }, executor);
}
  1. 这是正确的方法吗?如果方法不正确,我该如何改进?

我正在构建&lt;List&lt;Employee&gt;&gt;,如下所示

employeeInfo.stream.map(employee -> Employee.builder().
  .<someEmplyInfo>
  .points(points.getOrDefault(employee.getEmpId, newArrayList()))
);

【问题讨论】:

  • 定义“不工作”
  • 我更新了问题。我的意思是仍然需要很长时间才能返回,所以我的问题是如何改进它或者它是正确的方法。
  • 方法reward(...)和points(...)的签名是什么?你打电话给他们不一致。你如何从这两种方法的输出中构造List&lt;Employee&gt;?换句话说,请包含此方法的顺序版本,该版本可以正确编译和工作。
  • reward(...) 和points(...) 方法分别调用API获取详细信息。一旦获得详细信息,它就会收集到 List 并将其放入 map 中与 empId。

标签: java-8 completable-future


【解决方案1】:

处理个别期货的异常阻塞中的任何异常非常重要。

理想情况下,控制流不应该依赖于异常处理逻辑,它应该被包装在一个状态对象中,该对象可以用来评估是否应该进行进一步的处理。 添加一个 thenApply 发布 allOf 方法,然后在 thenApply 块中获取结果应该可以解决问题

public CompletableFuture<List<Employee>> buildEmployee(List<EmployeeResponse> employeeInfo) {
    //Build the future instance for reward
    CompletableFuture<Map<String, List<EmployeeReward>>> rewardsFuture = reward(employeeInfo)
        .exceptionally(throwable -> {
            //Handle the error
            return null;
        });

    //Build the future instance for points
    CompletableFuture<Map<String, List<EmployeePoints>>> pointsFuture = points(employeeInfo)
        .exceptionally(throwable -> {
            //Handle the error for rewards
            return null;
        });

    return CompletableFuture.allOf(rewardsFuture, pointsFuture).thenApply(v -> {
        try {
            Map<String, List<EmployeeReward>> rewardsResult = rewardsFuture.get();
            Map<String, List<EmployeePoints>> pointsResult = pointsFuture.get();

            //Convert the above map to the desired list of string
            List<Employee> buildEmployeeResult = null;
            return buildEmployeeResult;
        }
        catch (Exception e) {
            //Handle exception
            return null;
        }
    }, executor);
}

private CompletableFuture<Map<String, List<EmployeePoints>>> points(List<EmployeeResponse> employeeInfo) {
    return supplyAsync(() -> {
        //Logic for points synchronous
    });
}

private CompletableFuture<Map<String, List<EmployeeReward>>> reward(List<EmployeeResponse> employeeInfo) {
    return supplyAsync(() -> {
        //Logic for rewards synchronous
    });
}

【讨论】:

  • 应使用异常块,除非您有信心或有理由不这样做。 @Deepak。使用 .thenApplyAsync 不会有任何区别,因为在方法块 buildEmployee(.....) 中没有任何其他操作正在执行或预期与 .thenApplyAsync(...) 并行执行。两个 .get(...) 操作已经是未来的并且将在 .thenApplyAsync(...) 内完成。使用 .thenApply(...) 代替 .thenApplyAsync(...) 不会获得应有的好处,并且可能会使开发人员混淆该行为。
  • 同意@Nimeshmakwana
【解决方案2】:

在上述方法中,您使用Async 线程执行buildEmployee 方法,这意味着Async 线程负责进行两次API 调用rewards 和points,然后将结果合并。所以在上面的方法中,这个方法是异步执行的,而不是 API 调用。

但是您可以通过异步调用 API 来实现另一种方式,使用 supplyAsync 异步调用 reward,然后使用主线程调用 points。最后阻塞主线程,直到异步调用完成,然后合并结果

public CompletableFuture<List<Employee>> buildEmployee (List<EmployeeResponse> employeeInfo) {

       // First call is Async call        

    CompletableFuture<Map<String, List<EmployeeReward>>> rewards = CompletableFuture.supplyAsync(()->reward(employeeInfo), executor);

      //Second call by main thread

    Map<String, List<EmployeePoints>>> points = points(employeeInfo);

    // main thread is Blocked and get the result of the future.
      rewards.get(); //throws InterruptedException,ExecutionException

   // Now combine the result and return list

      return CompletableFuture.completedFuture(result);

}

【讨论】:

  • 但List&lt;Employee&gt; buildEmployee 是另一个可以完成的未来 - CompletableFuture&lt;List&lt;Employee&gt;&gt; employee = employeeInfo.isPresent() ? employeeService.buildEmployee(employeeInfo.get()) : completedFuture(null);
猜你喜欢
  • 1970-01-01
  • 2016-03-17
  • 1970-01-01
  • 2020-08-07
  • 2019-07-18
  • 2016-12-09
  • 2019-02-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多