异步编程五:CompletableFuture异步编程Handle最终处理

177 阅读1分钟

handle和whenComplete方法类似,但是whenComplete能感知异常但是不能返回结果。只能通过exceptionally进行处理。

而handle即可以获取执行结果,也可以感知异常信息,并能处理执行结果并返回。

public class CompletableFutureHandle {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService executor = Executors.newFixedThreadPool(5);

        System.out.println("main start ...");
        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
            System.out.println("开启异步任务...");
            int i = 10 / 0;
            return i;
        }, executor).handleAsync((res, thr) -> {
            System.out.println("进入handleAsync方法");
            if (res != null) {
                return res * 2;
            }
            if (thr != null) {
                System.out.println("捕获到异常" + thr);
                return 0;
            }
            return 0;
        }, executor);
        System.out.println("获取异步任务返回值:" + future.get());
        System.out.println("main end ...");

        executor.shutdown();
    }
}

有异常情况执行结果:

main start ...
开启异步任务...
进入handleAsync方法
捕获到异常java.util.concurrent.CompletionException: java.lang.ArithmeticException: / by zero
获取异步任务返回值:0
main end ...

无异常情况执行结果:

main start ...
开启异步任务...
进入handleAsync方法
获取异步任务返回值:10
main end ...