- 資訊首頁(yè) > 開(kāi)發(fā)技術(shù) >
- Java中CompletableFuture的作用是什么
這篇文章給大家介紹Java中CompletableFuture的作用是什么,內容非常詳細,感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。
創(chuàng )建CompletableFuture對象。
以下四個(gè)靜態(tài)方法用來(lái)為一段異步執行的代碼創(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)
runAsync方法也好理解,它以Runnable函數式接口類(lèi)型為參數,所以CompletableFuture的計算結果為空。以Async結尾會(huì )使用其它的線(xiàn)程去執行,沒(méi)有指定Executor的方法會(huì )使用ForkJoinPool.commonPool()作為它的線(xiàn)程池執行異步代碼。
supplyAsync方法以Supplier<U>函數式接口類(lèi)型為參數,CompletableFuture的計算結果類(lèi)型為U。
因為方法的參數類(lèi)型都是函數式接口,所以可以使用lambda表達式實(shí)現異步任務(wù),比如:
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> { //長(cháng)時(shí)間的計算任務(wù) return "hello world"; });
計算結果完成時(shí)的處理
當CompletableFuture的計算結果完成,或者拋出異常的時(shí)候,我們可以執行特定的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的類(lèi)型是BiConsumer<? super T,? super Throwable>,它可以處理正常的計算結果,或者異常情況。
注意這幾個(gè)方法都會(huì )返回CompletableFuture,當Action執行完畢后它的結果返回原始的CompletableFuture的計算結果或者返回異常。
public class Main { private static Random rand = new Random(); private static long t = System.currentTimeMillis(); static int getMoreData() { System.out.println("begin to start compute"); try { Thread.sleep(10000); } catch (InterruptedException e) { throw new RuntimeException(e); } System.out.println("end to start compute. passed " + (System.currentTimeMillis() - t)/1000 + " seconds"); return rand.nextInt(1000); } public static void main(String[] args) throws Exception { CompletableFuture<Integer> future = CompletableFuture.supplyAsync(Main::getMoreData); Future<Integer> f = future.whenComplete((v, e) -> { System.out.println(v); System.out.println(e); }); System.out.println(f.get()); System.in.read(); } }
exceptionally方法返回一個(gè)新的CompletableFuture,當原始的CompletableFuture拋出異常的時(shí)候,就會(huì )觸發(fā)這個(gè)CompletableFuture的計算,調用function計算值,否則如果原始的CompletableFuture正常計算完后,這個(gè)新的CompletableFuture也計算完成,它的值和原始的CompletableFuture的計算的值相同。也就是這個(gè)exceptionally方法用來(lái)處理異常的情況。
結果轉換
由于回調風(fēng)格的實(shí)現,我們不必因為等待一個(gè)計算完成而阻塞著(zhù)調用線(xiàn)程,而是告訴CompletableFuture當計算完成的時(shí)候請執行某個(gè)function。而且我們還可以將這些操作串聯(lián)起來(lái),或者將CompletableFuture組合起來(lái)。
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)
這一組函數的功能是當原來(lái)的CompletableFuture計算完后,將結果傳遞給函數fn,將fn的結果作為新的CompletableFuture計算結果。因此它的功能相當于將CompletableFuture<T>轉換成CompletableFuture<U>。
使用例子如下:
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> { return 100; }); CompletableFuture<String> f = future.thenApplyAsync(i -> i * 10).thenApply(i -> i.toString()); System.out.println(f.get()); //"1000"
需要注意的是,這些轉換并不是馬上執行的,也不會(huì )阻塞,而是在前一個(gè)stage完成后繼續執行。
下面一組方法雖然也返回CompletableFuture對象,但是對象的值和原來(lái)的CompletableFuture計算的值不同。當原先的CompletableFuture的值計算完成或者拋出異常的時(shí)候,會(huì )觸發(fā)這個(gè)CompletableFuture對象的計算,結果由BiFunction參數計算而得。因此這組方法兼有whenComplete和轉換的兩個(gè)功能。
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)
它們與thenApply* 方法的區別在于handle*方法會(huì )處理正常計算值和異常,因此它可以屏蔽異常,避免異常繼續拋出。而thenApply*方法只是用來(lái)處理正常值,因此一旦有異常就會(huì )拋出。
純消費結果
上面的方法是當計算完成的時(shí)候,會(huì )生成新的計算結果(thenApply, handle),或者返回同樣的計算結果(whenComplete,CompletableFuture)。CompletableFuture提供了一種處理結果的方法,只對結果執行Action,而不返回新的計算值,因此計算值為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)
看它的參數類(lèi)型也就明白了,它們是消費型函數式接口Consumer,這個(gè)接口只有輸入,沒(méi)有返回值。
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> { return 100; }); CompletableFuture<Void> f = future.thenAccept(System.out::println); System.out.println(f.get()); 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) public CompletableFuture<Void> runAfterBoth(CompletionStage<?> other, Runnable action)
thenAcceptBoth以及相關(guān)方法提供了類(lèi)似的功能,當兩個(gè)CompletionStage都正常完成計算的時(shí)候,就會(huì )執行提供的action,它用來(lái)組合另外一個(gè)異步的結果。
runAfterBoth是當兩個(gè)CompletionStage都正常完成計算的時(shí)候,執行一個(gè)Runnable,這個(gè)Runnable并不使用計算的結果。
例子如下:
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> { return 100; }); CompletableFuture<Void> f = future.thenAcceptBoth(CompletableFuture.completedFuture(10), (x, y) -> System.out.println(x * y)); System.out.println(f.get());
更徹底地,下面一組方法當計算完成的時(shí)候會(huì )執行一個(gè)Runnable,與thenAccept不同,Runnable并不使用CompletableFuture計算的結果。
public CompletableFuture<Void> thenRun(Runnable action) public CompletableFuture<Void> thenRunAsync(Runnable action) public CompletableFuture<Void> thenRunAsync(Runnable action, Executor executor)
因此先前的CompletableFuture計算的結果被忽略了,這個(gè)方法返回CompletableFuture<Void>類(lèi)型的對象。
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> { return 100; }); CompletableFuture<Void> f = future.thenRun(() -> System.out.println("finished")); System.out.println(f.get());
因此,你可以根據方法的參數的類(lèi)型來(lái)加速你的記憶。Runnable類(lèi)型的參數會(huì )忽略計算的結果,Consumer是純消費計算結果,BiConsumer會(huì )組合另外一個(gè)CompletionStage純消費,Function會(huì )對計算結果做轉換,BiFunction會(huì )組合另外一個(gè)CompletionStage的計算結果做轉換。
組合
有時(shí),你需要在一個(gè)future結構運行某個(gè)函數,但是這個(gè)函數也是返回某種future,也就是說(shuō)是兩個(gè)future彼此依賴(lài)串聯(lián)在一起,它類(lèi)似于flatMap。
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)
這一組方法接受一個(gè)Function作為參數,這個(gè)Function的輸入是當前的CompletableFuture的計算值,返回結果將是一個(gè)新的CompletableFuture,這個(gè)新的CompletableFuture會(huì )組合原來(lái)的CompletableFuture和函數返回的CompletableFuture。因此它的功能類(lèi)似:
A +--> B +---> C
記住,thenCompose返回的對象并不一是函數fn返回的對象,如果原來(lái)的CompletableFuture還沒(méi)有計算出來(lái),它就會(huì )生成一個(gè)新的組合后的CompletableFuture。
例子:
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> { return 100; }); CompletableFuture<String> f = future.thenCompose( i -> { return CompletableFuture.supplyAsync(() -> { return (i * 10) + ""; }); }); System.out.println(f.get()); //1000
而下面的一組方法thenCombine用來(lái)復合另外一個(gè)CompletionStage的結果。它的功能類(lèi)似:
A +
|
+------> C
+------^
B +
兩個(gè)CompletionStage是并行執行的,它們之間并沒(méi)有先后依賴(lài)順序,other并不會(huì )等待先前的CompletableFuture執行完畢后再執行。
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)
其實(shí)從功能上來(lái)講,它們的功能更類(lèi)似thenAcceptBoth,只不過(guò)thenAcceptBoth是純消費,它的函數參數沒(méi)有返回值,而thenCombine的函數參數fn有返回值。
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> { return 100; }); CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> { return "abc"; }); CompletableFuture<String> f = future.thenCombine(future2, (x,y) -> y + "-" + x); System.out.println(f.get()); //abc-100
Either
thenAcceptBoth和runAfterBoth是當兩個(gè)CompletableFuture都計算完成,而我們下面要了解的方法是當任意一個(gè)CompletableFuture計算完成的時(shí)候就會(huì )執行。
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 <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)
acceptEither方法是當任意一個(gè)CompletionStage完成的時(shí)候,action這個(gè)消費者就會(huì )被執行。這個(gè)方法返回CompletableFuture<Void>
applyToEither方法是當任意一個(gè)CompletionStage完成的時(shí)候,fn會(huì )被執行,它的返回值會(huì )當作新的CompletableFuture<U>的計算結果。
下面這個(gè)例子有時(shí)會(huì )輸出100,有時(shí)候會(huì )輸出200,哪個(gè)Future先完成就會(huì )根據它的結果計算。
Random rand = new Random(); CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> { try { Thread.sleep(10000 + rand.nextInt(1000)); } catch (InterruptedException e) { e.printStackTrace(); } return 100; }); CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> { try { Thread.sleep(10000 + rand.nextInt(1000)); } catch (InterruptedException e) { e.printStackTrace(); } return 200; }); CompletableFuture<String> f = future.applyToEither(future2,i -> i.toString());
輔助方法 allOf 和 anyOf
前面我們已經(jīng)介紹了幾個(gè)靜態(tài)方法:completedFuture、runAsync、supplyAsync,下面介紹的這兩個(gè)方法用來(lái)組合多個(gè)CompletableFuture。
public static CompletableFuture<Void> allOf(CompletableFuture<?>... cfs) public static CompletableFuture<Object> anyOf(CompletableFuture<?>... cfs)
allOf方法是當所有的CompletableFuture都執行完后執行計算。
anyOf方法是當任意一個(gè)CompletableFuture執行完后就會(huì )執行計算,計算的結果相同。
下面的代碼運行結果有時(shí)是100,有時(shí)是"abc"。但是anyOf和applyToEither不同。anyOf接受任意多的CompletableFuture,但是applyToEither只是判斷兩個(gè)CompletableFuture。anyOf返回值的計算結果是參數中其中一個(gè)CompletableFuture的計算結果,applyToEither返回值的計算結果卻是要經(jīng)過(guò)fn處理的。當然還有靜態(tài)方法的區別,線(xiàn)程池的選擇等。
Random rand = new Random(); CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> { try { Thread.sleep(10000 + rand.nextInt(1000)); } catch (InterruptedException e) { e.printStackTrace(); } return 100; }); CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> { try { Thread.sleep(10000 + rand.nextInt(1000)); } catch (InterruptedException e) { e.printStackTrace(); } return "abc"; }); //CompletableFuture<Void> f = CompletableFuture.allOf(future1,future2); CompletableFuture<Object> f = CompletableFuture.anyOf(future1,future2); System.out.println(f.get());
更進(jìn)一步
Guava的Future類(lèi),它的Futures輔助類(lèi)提供了很多便利方法,用來(lái)處理多個(gè)Future,而不像Java的CompletableFuture,只提供了allOf、anyOf兩個(gè)方法。 比如有這樣一個(gè)需求,將多個(gè)CompletableFuture組合成一個(gè)CompletableFuture,這個(gè)組合后的CompletableFuture的計算結果是個(gè)List,它包含前面所有的CompletableFuture的計算結果,guava的Futures.allAsList可以實(shí)現這樣的功能,但是對于java CompletableFuture,我們需要一些輔助方法:
public static <T> CompletableFuture<List<T>> sequence(List<CompletableFuture<T>> futures) { CompletableFuture<Void> allDoneFuture = CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()])); return allDoneFuture.thenApply(v -> futures.stream().map(CompletableFuture::join).collect(Collectors.<T>toList())); } public static <T> CompletableFuture<Stream<T>> sequence(Stream<CompletableFuture<T>> futures) { List<CompletableFuture<T>> futureList = futures.filter(f -> f != null).collect(Collectors.toList()); return sequence(futureList); }
或者Java Future轉CompletableFuture:
public static <T> CompletableFuture<T> toCompletable(Future<T> future, Executor executor) { return CompletableFuture.supplyAsync(() -> { try { return future.get(); } catch (InterruptedException | ExecutionException e) { throw new RuntimeException(e); } }, executor); }
免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng )、來(lái)自互聯(lián)網(wǎng)轉載和分享為主,文章觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權請聯(lián)系QQ:712375056 進(jìn)行舉報,并提供相關(guān)證據,一經(jīng)查實(shí),將立刻刪除涉嫌侵權內容。
Copyright ? 2009-2021 56dr.com. All Rights Reserved. 特網(wǎng)科技 特網(wǎng)云 版權所有 珠海市特網(wǎng)科技有限公司 粵ICP備16109289號
域名注冊服務(wù)機構:阿里云計算有限公司(萬(wàn)網(wǎng)) 域名服務(wù)機構:煙臺帝思普網(wǎng)絡(luò )科技有限公司(DNSPod) CDN服務(wù):阿里云計算有限公司 中國互聯(lián)網(wǎng)舉報中心 增值電信業(yè)務(wù)經(jīng)營(yíng)許可證B2
建議您使用Chrome、Firefox、Edge、IE10及以上版本和360等主流瀏覽器瀏覽本網(wǎng)站