简体   繁体   English

如何在异常处理中使用CompletableFuture和CompletionStage

[英]How to use CompletableFuture and CompletionStage with exception handling

I am dealing with some code involving multiple blocking I/O operations to be performed in sequence. 我正在处理一些涉及按顺序执行的多个阻塞I / O操作的代码。 The context is a JVM based web application running on Java 8 and Tomcat. 上下文是在Java 8和Tomcat上运行的基于JVM的Web应用程序。 I have code that performs three operations in sequence. 我有按顺序执行三个操作的代码。 All are of the blocking nature, and the output of each operation may be utilized in a subsequent operation. 所有这些都具有阻塞性,并且每个操作的输出都可以在后续操作中使用。 Each operation can throw exceptions, either checked or unchecked. 每个操作都可以引发已检查或未检查的异常。 I have illustrated with some sample exceptions that can be thrown: 我已经说明了一些可能引发的异常示例:

String output1 = callToRestAPI(); // throws MalformedUrlException, ConcurrentModificationException

callToDatabase(output1); // throws SQLException, ConcurrentModificationException

boolean output2 = callToSendEmail(output1); // throws MessagingException

How would I write this using Java 8's promising (no pun intended) CompletionStage and CompletableFuture? 我将如何使用Java 8的有前途的(无双关语)CompletionStage和CompletableFuture来编写此代码?

Hope this helps. 希望这可以帮助。

import java.util.concurrent.CompletableFuture;

public class HandleException {

  public static void main(String[] args) {
    CompletableFuture.completedFuture(null)
        .thenApply(__ -> callToRestAPI())
        .thenApply(
            output1 -> {
              callToDatabase(output1);
              return output1;
            })
        .thenAccept(output1 -> callToSendEmail(output1))
        .exceptionally(
            t -> {
              System.out.println("Exception occurred: " + t.getMessage());
              return null;
            });
  }
}

thenApply and thenAccept is used when the code is blocking. 代码阻塞时,将使用thenApply和thenAccept。 thenApply is used when we want to return something to next thenXXX method. 当我们想返回下一个thenXXX方法时使用thenApply。 thenAccept does not return anything. thenAccept不返回任何内容。 You can also make callToRestAPI,callToDatabase as Async(non blocking code) using a runAsync or supplyAsync 您还可以使用runAsync或supplyAsync将callToRestAPI,callToDatabase设置为Async(非阻塞代码)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM