CompletableFuture详解~异常处理
生活随笔
收集整理的這篇文章主要介紹了
CompletableFuture详解~异常处理
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
計算結果完成時的回調方法
當 CompletableFuture 的計算結果完成,或者拋出異常的時候,可以執行特定的 Action。主要是下面的方法:
public CompletableFuture<T> whenComplete(BiConsumer<? super T,? super Throwable> action) public CompletableFuture<T> whenCompleteAsync(BiConsumer<? super T,? super Throwable> action) public CompletableFuture<T> whenCompleteAsync(BiConsumer<? super T,? super Throwable> action, Executor executor) public CompletableFuture<T> exceptionally(Function<Throwable,? extends T> fn)可以看到 Action 的類型是 BiConsumer<? super T,? super Throwable>它可以處理正常的計算結果,或者異常情況。
whenComplete 和 whenCompleteAsync 的區別:
-
whenComplete:是執行當前任務的線程執行繼續執行 whenComplete 的任務。
-
whenCompleteAsync:是執行把 whenCompleteAsync 這個任務繼續提交給線程池來進行執行。
示例代碼
public static void whenComplete() throws Exception {CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {try {TimeUnit.SECONDS.sleep(1);} catch (InterruptedException e) {}if(new Random().nextInt()%2>=0) {int i = 12/0;}System.out.println("run end ...");});future.whenComplete(new BiConsumer<Void, Throwable>() {@Overridepublic void accept(Void t, Throwable action) {System.out.println("執行完成!");}});future.exceptionally(new Function<Throwable, Void>() {@Overridepublic Void apply(Throwable t) {System.out.println("執行失敗!"+t.getMessage());return null;}});TimeUnit.SECONDS.sleep(2); }handle 方法
handle 是執行任務完成時對結果的處理。handle 方法和 thenApply 方法處理方式基本一樣。不同的是 handle 是在任務完成后再執行,還可以處理異常的任務。thenApply 只可以執行正常的任務,任務出現異常則不執行 thenApply 方法。
public <U> CompletionStage<U> handle(BiFunction<? super T, Throwable, ? extends U> fn); public <U> CompletionStage<U> handleAsync(BiFunction<? super T, Throwable, ? extends U> fn); public <U> CompletionStage<U> handleAsync(BiFunction<? super T, Throwable, ? extends U> fn,Executor executor);示例代碼
public static void handle() throws Exception{CompletableFuture<Integer> future = CompletableFuture.supplyAsync(new Supplier<Integer>() {@Overridepublic Integer get() {int i= 10/0;return new Random().nextInt(10);}}).handle(new BiFunction<Integer, Throwable, Integer>() {@Overridepublic Integer apply(Integer param, Throwable throwable) {int result = -1;if(throwable==null){result = param * 2;}else{System.out.println(throwable.getMessage());}return result;}});System.out.println(future.get()); }從示例中可以看出,在 handle 中可以根據任務是否有異常來進行做相應的后續處理操作。而 thenApply 方法,如果上個任務出現錯誤,則不會執行 thenApply 方法。
總結
以上是生活随笔為你收集整理的CompletableFuture详解~异常处理的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python 的 requests 库的
- 下一篇: Node.js 教程