Future模式之CompletableFuture

CompletableFuture 是Java 8 新增加的Api,該類實現(xiàn),F(xiàn)uture和CompletionStage兩個接口,提供了非常強大的Future的擴展功能,可以幫助我們簡化異步編程的復(fù)雜性,提供了函數(shù)式編程的能力,可以通過回調(diào)的方式處理計算結(jié)果,并且提供了轉(zhuǎn)換和組合CompletableFuture的方法。

一、主動完成計算

  • public T get()

    該方法為阻塞方法,會等待計算結(jié)果完成

  • public T get(long timeout,TimeUnit unit)

    有時間限制的阻塞方法

  • public T getNow(T valueIfAbsent)

    立即獲取方法結(jié)果,如果沒有計算結(jié)束則返回傳的值

  • public T join()

    和 get() 方法類似也是主動阻塞線程,等待計算結(jié)果。和get() 方法有細(xì)微的差別

public class ThreadUtil {
    public static void sleep(long ms) {
        try {
            Thread.sleep(ms);
        } catch (InterruptedException e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }
}

public static void main(String[] args) {

     CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
            ThreadUtil.sleep(200);
            return 10 / 0;
    });
//       System.out.println(future.join());
//       System.out.println(future.get());
    System.out.println(future.getNow(10));
}
  • public boolean complete(T value)

    立即完成計算,并把結(jié)果設(shè)置為傳的值,返回是否設(shè)置成功

    如果 CompletableFuture 沒有關(guān)聯(lián)任何的Callback、異步任務(wù)等,如果調(diào)用get方法,那會一直阻塞下去,可以使用complete方法主動完成計算

public static void main(String[] args) throws Exception {
    CompletableFuture<Integer> future = new CompletableFuture<>();
//        future.get();
    future.complete(10);
}
  • public boolean completeExceptionally(Throwable ex)
    立即完成計算,并拋出異常

二、執(zhí)行異步任務(wù)

創(chuàng)建一個異步任務(wù)

  • public static <U> CompletableFuture<U> completedFuture(U value)

    創(chuàng)建一個有初始值的CompletableFuture

  • public static CompletableFuture<Void> runAsync(Runnable runnable)

  • public static CompletableFuture<Void> runAsync(Runnable runnable, Executor executor)

  • public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier)

  • public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier, Executor executor)

    以上四個方法中,以 Async 結(jié)尾并且沒有 Executor 參數(shù)的,會默認(rèn)使用 ForkJoinPool.commonPool() 作為它的線程池執(zhí)行異步代碼。
    以run開頭的,因為以 Runable 類型為參數(shù)所以沒有返回值。示例:

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CompletableFuture<Void> future1 = CompletableFuture.runAsync(() -> System.out.println("runAsync"));
        CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> "supplyAsync");
        
        System.out.println(future1.get());
        System.out.println(future2.get());
    }

結(jié)果:

runAsync
null
supplyAsync

三、計算完成時對結(jié)果的處理 whenComplete/exceptionally/handle

當(dāng)CompletableFuture的計算結(jié)果完成,或者拋出異常的時候,我們可以執(zhí)行特定的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)

參數(shù)類型為 BiConsumer<? super T, ? super Throwable> 會獲取上一步計算的計算結(jié)果和異常信息。以Async結(jié)尾的方法可能會使用其它的線程去執(zhí)行,如果使用相同的線程池,也可能會被同一個線程選中執(zhí)行,以下皆相同。

   public static void main(String[] args) throws Exception {
    CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
        ThreadUtil.sleep(100);
        return 20;
    }).whenCompleteAsync((v, e) -> {
        System.out.println(v);
        System.out.println(e);
    });
    System.out.println(future.get());
}
  • public CompletableFuture<T> exceptionally(Function<Throwable,? extends T> fn)

    該方法是對異常情況的處理,當(dāng)函數(shù)異常時應(yīng)該的返回值

    public static void main(String[] args) throws Exception {
        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
            ThreadUtil.sleep(100);
            return 10 / 0;
        }).whenCompleteAsync((v, e) -> {
            System.out.println(v);
            System.out.println(e);
        }).exceptionally((e) -> {
            System.out.println(e.getMessage());
            return 30;
        });
        System.out.println(future.get());
    }

  • public <U> CompletableFuture<U> handle(BiFunction<? super T,Throwable,? extends U> fn)
  • public <U> CompletableFuture<U> handleAsync(BiFunction<? super T,Throwable,? extends U> fn)
  • public <U> CompletableFuture<U> handleAsync(BiFunction<? super T,Throwable,? extends U> fn, Executor executor)

handle 方法和whenComplete方法類似,只不過接收的是一個 BiFunction<? super T,Throwable,? extends U> fn 類型的參數(shù),因此有 whenComplete 方法和 轉(zhuǎn)換的功能 (thenApply)

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CompletableFuture<Integer> future = CompletableFuture
                .supplyAsync(() -> 10 / 0)
                .handle((t, e) -> {
                    System.out.println(e.getMessage());
                    return 10;
                });

        System.out.println(future.get());
    }

四、結(jié)果處理轉(zhuǎn)換 thenApply

CompletableFuture 由于有回調(diào),可以不必等待一個計算完成而阻塞著調(diào)用縣城,可以在一個結(jié)果計算完成之后緊接著執(zhí)行某個Action。我們可以將這些操作串聯(lián)起來。

  • public <U> CompletableFuture<U> thenApply(Function<? super T,? extends U> fn)
  • public <U> CompletableFuture<U> thenApplyAsync(Function<? super T,? extends U> fn)
  • public <U> CompletableFuture<U> thenApplyAsync(Function<? super T,? extends U> fn, Executor executor)
 public static void main(String[] args) throws ExecutionException, InterruptedException {
        CompletableFuture<Integer> future = CompletableFuture
                .supplyAsync(() -> 1)
                .thenApply((a) -> {
                    System.out.println(a);//1
                    return a * 10;
                }).thenApply((a) -> {
                    System.out.println(a);//10
                    return a + 10;
                }).thenApply((a) -> {
                    System.out.println(a);//20
                    return a - 5;
                });
        System.out.println(future.get());//15
    }

這些方法不是馬上執(zhí)行的,也不會阻塞,而是前一個執(zhí)行完成后繼續(xù)執(zhí)行下一個。

和 handle 方法的區(qū)別是,handle 會處理正常計算值和異常,不會拋出異常。而 thenApply 只會處理正常計算值,有異常則拋出。

五、純消費 thenAccept/thenAcceptBoth/thenRun

單純的去消費結(jié)果而不會返回新的值,因些計算結(jié)果為 Void;

  • public CompletableFuture<Void> thenAccept(Consumer<? super T> action)
  • public CompletableFuture<Void> thenAcceptAsync(Consumer<? super T> action)
  • public CompletableFuture<Void> thenAcceptAsync(Consumer<? super T> action, Executor executor)
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        
        CompletableFuture<Void> future = CompletableFuture
                .supplyAsync(() -> 1)
                .thenAccept(System.out::println) //消費 上一級返回值 1
                .thenAcceptAsync(System.out::println); //上一級沒有返回值 輸出null
                
        System.out.println(future.get()); //消費函數(shù)沒有返回值 輸出null
    }

  • public <U> CompletableFuture<Void> thenAcceptBoth(CompletionStage<? extends U> other, BiConsumer<? super T,? super U> action)
  • public <U> CompletableFuture<Void> thenAcceptBothAsync(CompletionStage<? extends U> other, BiConsumer<? super T,? super U> action)
  • public <U> CompletableFuture<Void> thenAcceptBothAsync(CompletionStage<? extends U> other, BiConsumer<? super T,? super U> action, Executor executor)

和 thenAccept 相比,參數(shù)類型多了一個 CompletionStage<? extends U> other,以上方法會接收上一個CompletionStage返回值,和當(dāng)前的一個。

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CompletableFuture
                .supplyAsync(() -> 1)
                .thenAcceptBoth(CompletableFuture.supplyAsync(() -> 2), (a, b) -> {
                    System.out.println(a);
                    System.out.println(b);
                }).get();
    }
  • public CompletableFuture<Void> runAfterBoth(CompletionStage<?> other, Runnable action)

    runAfterBoth 和以上方法不同,傳一個 Runnable 類型的參數(shù),不接收上一級的返回值


更徹底的:

  • public CompletableFuture<Void> thenRun(Runnable action)
  • public CompletableFuture<Void> thenRunAsync(Runnable action)
  • public CompletableFuture<Void> thenRunAsync(Runnable action, Executor executor)

以上是徹底的純消費,完全忽略計算結(jié)果

六、組合 thenCompose/thenCombine

  • public <U> CompletableFuture<U> thenCompose(Function<? super T,? extends CompletionStage<U>> fn)
  • public <U> CompletableFuture<U> thenComposeAsync(Function<? super T,? extends CompletionStage<U>> fn)
  • public <U> CompletableFuture<U> thenComposeAsync(Function<? super T,? extends CompletionStage<U>> fn, Executor executor)

以上接收類型為 Function<? super T,? extends CompletionStage<U>> fn ,fn 接收上一級返回的結(jié)果,并返回一個新的 CompletableFuture

   public static void main(String[] args) throws ExecutionException, InterruptedException {

        CompletableFuture<Integer> future = CompletableFuture
                .supplyAsync(() -> 1)
                .thenApply((a) -> {
                    ThreadUtil.sleep(1000);
                    return a + 10;
                })
                .thenCompose((s) -> {
                    System.out.println(s); //11
                    return CompletableFuture.supplyAsync(() -> s * 5);
                });

        System.out.println(future.get());//55
    }

  • public <U,V> CompletableFuture<V> thenCombine(CompletionStage<? extends U> other, BiFunction<? super T,? super U,? extends V> fn)
  • public <U,V> CompletableFuture<V> thenCombineAsync(CompletionStage<? extends U> other, BiFunction<? super T,? super U,? extends V> fn)
  • public <U,V> CompletableFuture<V> thenCombineAsync(CompletionStage<? extends U> other, BiFunction<? super T,? super U,? extends V> fn, Executor executor)

兩個CompletionStage是并行執(zhí)行的,它們之間并沒有先后依賴順序,other并不會等待先前的CompletableFuture執(zhí)行完畢后再執(zhí)行。

public static void main(String[] args) throws ExecutionException, InterruptedException {

        Random random = new Random();
        CompletableFuture<Integer> future = CompletableFuture
                .supplyAsync(() -> {
                    ThreadUtil.sleep(random.nextInt(1000));
                    System.out.println("supplyAsync");
                    return 2;
                }).thenApply((a) -> {
                    ThreadUtil.sleep(random.nextInt(1000));
                    System.out.println("thenApply");
                    return a * 3;
                })
                .thenCombine(CompletableFuture.supplyAsync(() -> {
                    ThreadUtil.sleep(random.nextInt(1000));
                    System.out.println("thenCombineAsync");
                    return 10;
                }), (a, b) -> {
                    System.out.println(a);
                    System.out.println(b);
                    return a + b;
                });

        System.out.println(future.get());
    }

thenCombine 和 supplyAsync 不一定哪個先哪個后,是并行執(zhí)行的。

七、acceptEither / applyToEither

  • public CompletableFuture<Void> acceptEither(CompletionStage<? extends T> other, Consumer<? super T> action)
  • public CompletableFuture<Void> acceptEitherAsync(CompletionStage<? extends T> other, Consumer<? super T> action)
  • public CompletableFuture<Void> acceptEitherAsync(CompletionStage<? extends T> other, Consumer<? super T> action, Executor executor)

先看示例:

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        Random random = new Random();
        CompletableFuture
                .supplyAsync(() -> {
                    ThreadUtil.sleep(random.nextInt(1000));
                    return "A";
                })
                .acceptEither(CompletableFuture.supplyAsync(() -> {
                    ThreadUtil.sleep(random.nextInt(1000));
                    return "B";
                }), System.out::println)
                .get();
    }

以上代碼有時輸出A,有時輸出B,哪個Future先執(zhí)行完就會根據(jù)它的結(jié)果計算。

acceptEither方法是當(dāng)任意一個 CompletionStage 完成的時候,action 這個消費者就會被執(zhí)行。這個方法返回 CompletableFuture<Void>


  • public <U> CompletableFuture<U> applyToEither(CompletionStage<? extends T> other, Function<? super T,U> fn)
  • public <U> CompletableFuture<U> applyToEitherAsync(CompletionStage<? extends T> other, Function<? super T,U> fn)
  • public <U> CompletableFuture<U> applyToEitherAsync(CompletionStage<? extends T> other, Function<? super T,U> fn, Executor executor)

applyToEither 方法是當(dāng)任意一個 CompletionStage 完成的時候,fn會被執(zhí)行,它的返回值會當(dāng)作新的CompletableFuture<U>的計算結(jié)果。

acceptEither 沒有返回值,applyToEither 有返回值

八、allOf / anyOf

  • public static CompletableFuture<Void> allOf(CompletableFuture<?>... cfs)

這個方法的意思是把有方法都執(zhí)行完才往下執(zhí)行,沒有返回值

   public static void main(String[] args) throws ExecutionException, InterruptedException {

        Random random = new Random();
        CompletableFuture.allOf(
                CompletableFuture.runAsync(() -> {
                    ThreadUtil.sleep(random.nextInt(1000));
                    System.out.println(1);
                }),
                CompletableFuture.runAsync(() -> {
                    ThreadUtil.sleep(random.nextInt(1000));
                    System.out.println(2);
                }))
                .get();

    }

有時輸出1 2 有時輸出 2 1


  • public static CompletableFuture<Object> anyOf(CompletableFuture<?>... cfs)

任務(wù)一個方法執(zhí)行完都往下執(zhí)行,返回一個Object類型的值

  public static void main(String[] args) throws ExecutionException, InterruptedException {
        Random random = new Random();

        Object obj = CompletableFuture.anyOf(
                CompletableFuture.supplyAsync(() -> {
                    ThreadUtil.sleep(random.nextInt(1000));
                    return 1;
                }),
                CompletableFuture.supplyAsync(() -> {
                    ThreadUtil.sleep(random.nextInt(1000));
                    return 2;
                })).get();

        System.out.println(obj);
    }

輸出結(jié)果有時為1 有時間為 2

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • 更多 Java 并發(fā)編程方面的文章,請參見文集《Java 并發(fā)編程》 所謂異步調(diào)用其實就是實現(xiàn)一個可無需等待被調(diào)用...
    專職跑龍?zhí)?/span>閱讀 21,448評論 0 26
  • 本筆記來自 計算機程序的思維邏輯 系列文章 Lambda表達(dá)式 Lambda表達(dá)式 語法 匿名函數(shù),由 -> 分隔...
    碼匠閱讀 491評論 0 6
  • Java 8 有大量的新特性和增強如 Lambda 表達(dá)式,Streams,CompletableFuture等。...
    YDDMAX_Y閱讀 4,794評論 0 15
  • 在現(xiàn)代軟件開發(fā)中,系統(tǒng)功能越來越復(fù)雜,管理復(fù)雜度的方法就是分而治之,系統(tǒng)的很多功能可能會被切分為小的服務(wù),對外提供...
    天堂鳥6閱讀 7,191評論 0 23
  • 201組別 301期 利他一組 【日精進(jìn)打卡第210天 【知~學(xué)習(xí)】 誦讀《六項精進(jìn)大綱》3遍,累計272遍;誦...
    J0hn先生閱讀 155評論 0 0