Java CompletableFuture 詳解
來源:http://colobu.com/2016/02/29/Java-CompletableFuture/#
Java 8 強大的函數式異步編程輔助類
目錄 [−]
Future是Java 5添加的類,用來描述一個異步計算的結果。你可以使用isDone
方法檢查計算是否完成,或者使用get
阻塞住調用線程,直到計算完成返回結果,你也可以使用cancel
方法停止任務的執行。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
public class BasicFuture {
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService es = Executors.newFixedThreadPool(
10);
Future<Integer> f = es.submit(() ->{
// 長時間的異步計算
// ……
// 然后返回結果
return 100;
});
// while(!f.isDone())
// ;
f.get();
}
}
|
雖然Future
以及相關使用方法提供了異步執行任務的能力,但是對於結果的獲取卻是很不方便,只能通過阻塞或者輪詢的方式得到任務的結果。阻塞的方式顯然和我們的異步編程的初衷相違背,輪詢的方式又會耗費無謂的CPU資源,而且也不能及時地得到計算結果,為什么不能用觀察者設計模式當計算結果完成及時通知監聽者呢?
很多語言,比如Node.js,采用回調的方式實現異步編程。Java的一些框架,比如Netty,自己擴展了Java的 Future
接口,提供了addListener
等多個擴展方法:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
ChannelFuture future = bootstrap.connect(
new InetSocketAddress(host, port));
future.addListener(
new ChannelFutureListener()
{
@Override
public void operationComplete(ChannelFuture future) throws Exception
{
if (future.isSuccess()) {
// SUCCESS
}
else {
// FAILURE
}
}
});
|
Google guava也提供了通用的擴展Future:ListenableFuture、SettableFuture 以及輔助類Futures等,方便異步編程。
1
2
3
4
5
6
7
8
9
10
11
|
final String name = ...;
inFlight.add(name);
ListenableFuture<Result> future = service.query(name);
future.addListener(
new Runnable() {
public void run() {
processedCount.incrementAndGet();
inFlight.remove(name);
lastProcessed.set(name);
logger.info(
"Done with {0}", name);
}
}, executor);
|
Scala也提供了簡單易用且功能強大的Future/Promise異步編程模式。
作為正統的Java類庫,是不是應該做點什么,加強一下自身庫的功能呢?
在Java 8中, 新增加了一個包含50個方法左右的類: CompletableFuture,提供了非常強大的Future的擴展功能,可以幫助我們簡化異步編程的復雜性,提供了函數式編程的能力,可以通過回調的方式處理計算結果,並且提供了轉換和組合CompletableFuture的方法。
主動完成計算
CompletableFuture類實現了CompletionStage和Future接口,所以你還是可以像以前一樣通過阻塞或者輪詢的方式獲得結果,盡管這種方式不推薦使用。
1
2
3
4
|
public T get()
public T get(long timeout, TimeUnit unit)
public T getNow(T valueIfAbsent)
public T join()
|
getNow
有點特殊,如果結果已經計算完則返回結果或者拋出異常,否則返回給定的valueIfAbsent
值。join
返回計算的結果或者拋出一個unchecked異常(CompletionException),它和get
對拋出的異常的處理有些細微的區別,你可以運行下面的代碼進行比較:
1
2
3
4
5
6
|
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
int i = 1/0;
return 100;
});
//future.join();
future.get();
|
盡管Future可以代表在另外的線程中執行的一段異步代碼,但是你還是可以在本身線程中執行:
1
2
3
4
5
|
public static CompletableFuture<Integer> compute() {
final CompletableFuture<Integer> future = new CompletableFuture<>();
return future;
}
|
上面的代碼中future
沒有關聯任何的Callback
、線程池、異步任務等,如果客戶端調用future.get
就會一致傻等下去。你可以通過下面的代碼完成一個計算,觸發客戶端的等待:
1
|
f.complete(
100);
|
當然你也可以拋出一個異常,而不是一個成功的計算結果:
1
|
f.completeExceptionally(
new Exception());
|
完整的代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
public class BasicMain {
public static CompletableFuture<Integer> compute() {
final CompletableFuture<Integer> future = new CompletableFuture<>();
return future;
}
public static void main(String[] args) throws Exception {
final CompletableFuture<Integer> f = compute();
class Client extends Thread {
CompletableFuture<Integer> f;
Client(String threadName, CompletableFuture<Integer> f) {
super(threadName);
this.f = f;
}
@Override
public void run() {
try {
System.out.println(
this.getName() + ": " + f.get());
}
catch (InterruptedException e) {
e.printStackTrace();
}
catch (ExecutionException e) {
e.printStackTrace();
}
}
}
new Client("Client1", f).start();
new Client("Client2", f).start();
System.out.println(
"waiting");
f.complete(
100);
//f.completeExceptionally(new Exception());
System.in.read();
}
}
|
可以看到我們並沒有把f.complete(100);
放在另外的線程中去執行,但是在大部分情況下我們可能會用一個線程池去執行這些異步任務。CompletableFuture.complete()
、CompletableFuture.completeExceptionally
只能被調用一次。但是我們有兩個后門方法可以重設這個值:obtrudeValue
、obtrudeException
,但是使用的時候要小心,因為complete
已經觸發了客戶端,有可能導致客戶端會得到不期望的結果。
創建CompletableFuture對象。
CompletableFuture.completedFuture
是一個靜態輔助方法,用來返回一個已經計算好的CompletableFuture
。
1
|
public static <U> CompletableFuture<U> completedFuture(U value)
|
而以下四個靜態方法用來為一段異步執行的代碼創建CompletableFuture
對象:
1
2
3
4
|
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
結尾並且沒有指定Executor
的方法會使用ForkJoinPool.commonPool()
作為它的線程池執行異步代碼。
runAsync
方法也好理解,它以Runnable
函數式接口類型為參數,所以CompletableFuture
的計算結果為空。supplyAsync
方法以Supplier<U>
函數式接口類型為參數,CompletableFuture
的計算結果類型為U
。
因為方法的參數類型都是函數式接口,所以可以使用lambda表達式實現異步任務,比如:
1
2
3
4
|
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
//長時間的計算任務
return "·00";
});
|
計算結果完成時的處理
當CompletableFuture
的計算結果完成,或者拋出異常的時候,我們可以執行特定的Action
。主要是下面的方法:
1
2
3
4
|
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>
,它可以處理正常的計算結果,或者異常情況。
方法不以Async
結尾,意味着Action
使用相同的線程執行,而Async
可能會使用其它的線程去執行(如果使用相同的線程池,也可能會被同一個線程選中執行)。
注意這幾個方法都會返回CompletableFuture
,當Action
執行完畢后它的結果返回原始的CompletableFuture
的計算結果或者返回異常。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
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
方法返回一個新的CompletableFuture,當原始的CompletableFuture拋出異常的時候,就會觸發這個CompletableFuture的計算,調用function計算值,否則如果原始的CompletableFuture正常計算完后,這個新的CompletableFuture也計算完成,它的值和原始的CompletableFuture的計算的值相同。也就是這個exceptionally
方法用來處理異常的情況。
下面一組方法雖然也返回CompletableFuture對象,但是對象的值和原來的CompletableFuture計算的值不同。當原先的CompletableFuture的值計算完成或者拋出異常的時候,會觸發這個CompletableFuture對象的計算,結果由BiFunction
參數計算而得。因此這組方法兼有whenComplete
和轉換的兩個功能。
1
2
3
|
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)
|
同樣,不以Async
結尾的方法由原來的線程計算,以Async
結尾的方法由默認的線程池ForkJoinPool.commonPool()
或者指定的線程池executor
運行。
轉換
CompletableFuture
可以作為monad(單子)和functor。由於回調風格的實現,我們不必因為等待一個計算完成而阻塞着調用線程,而是告訴CompletableFuture
當計算完成的時候請執行某個function
。而且我們還可以將這些操作串聯起來,或者將CompletableFuture
組合起來。
1
2
3
|
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)
|
這一組函數的功能是當原來的CompletableFuture計算完后,將結果傳遞給函數fn
,將fn
的結果作為新的CompletableFuture
計算結果。因此它的功能相當於將CompletableFuture<T>
轉換成CompletableFuture<U>
。
這三個函數的區別和上面介紹的一樣,不以Async
結尾的方法由原來的線程計算,以Async
結尾的方法由默認的線程池ForkJoinPool.commonPool()
或者指定的線程池executor
運行。Java的CompletableFuture類總是遵循這樣的原則,下面就不一一贅述了。
使用例子如下:
1
2
3
4
5
|
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"
|
需要注意的是,這些轉換並不是馬上執行的,也不會阻塞,而是在前一個stage完成后繼續執行。
它們與handle
方法的區別在於handle
方法會處理正常計算值和異常,因此它可以屏蔽異常,避免異常繼續拋出。而thenApply
方法只是用來處理正常值,因此一旦有異常就會拋出。
純消費(執行Action)
上面的方法是當計算完成的時候,會生成新的計算結果(thenApply
, handle
),或者返回同樣的計算結果whenComplete
,CompletableFuture
還提供了一種處理結果的方法,只對結果執行Action
,而不返回新的計算值,因此計算值為Void
:
1
2
3
|
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)
|
看它的參數類型也就明白了,它們是函數式接口Consumer
,這個接口只有輸入,沒有返回值。
1
2
3
4
5
|
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
return 100;
});
CompletableFuture<Void> f = future.thenAccept(System.out::println);
System.out.println(f.get());
|
thenAcceptBoth
以及相關方法提供了類似的功能,當兩個CompletionStage都正常完成計算的時候,就會執行提供的action
,它用來組合另外一個異步的結果。runAfterBoth
是當兩個CompletionStage都正常完成計算的時候,執行一個Runnable,這個Runnable並不使用計算的結果。
1
2
3
4
|
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)
|
例子如下:
1
2
3
4
5
|
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());
|
更徹底地,下面一組方法當計算完成的時候會執行一個Runnable,與thenAccept
不同,Runnable並不使用CompletableFuture計算的結果。
1
2
3
|
public CompletableFuture<Void> thenRun(Runnable action)
public CompletableFuture<Void> thenRunAsync(Runnable action)
public CompletableFuture<Void> thenRunAsync(Runnable action, Executor executor)
|
因此先前的CompletableFuture計算的結果被忽略了,這個方法返回CompletableFuture<Void>
類型的對象。
1
2
3
4
5
|
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
return 100;
});
CompletableFuture<Void> f = future.thenRun(() -> System.out.println(
"finished"));
System.out.println(f.get());
|
因此,你可以根據方法的參數的類型來加速你的記憶。
Runnable
類型的參數會忽略計算的結果,Consumer
是純消費計算結果,BiConsumer
會組合另外一個CompletionStage
純消費,Function
會對計算結果做轉換,BiFunction
會組合另外一個CompletionStage
的計算結果做轉換。
組合
1
2
3
|
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作為參數,這個Function的輸入是當前的CompletableFuture的計算值,返回結果將是一個新的CompletableFuture,這個新的CompletableFuture會組合原來的CompletableFuture和函數返回的CompletableFuture。因此它的功能類似:
A +--> B +---> C
記住,thenCompose
返回的對象並不一是函數fn
返回的對象,如果原來的CompletableFuture
還沒有計算出來,它就會生成一個新的組合后的CompletableFuture。
例子:
1
2
3
4
5
6
7
8
9
|
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
用來復合另外一個CompletionStage的結果。它的功能類似:
A +
|
+------> C
+------^
B +
兩個CompletionStage是並行執行的,它們之間並沒有先后依賴順序,
other
並不會等待先前的
CompletableFuture
執行完畢后再執行。
1
2
3
|
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)
|
其實從功能上來講,它們的功能更類似thenAcceptBoth
,只不過thenAcceptBoth
是純消費,它的函數參數沒有返回值,而thenCombine
的函數參數fn
有返回值。
1
2
3
4
5
6
7
8
|
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
是當兩個CompletableFuture都計算完成,而我們下面要了解的方法是當任意一個CompletableFuture計算完成的時候就會執行。
1
2
3
4
5
6
7
|
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
方法是當任意一個CompletionStage完成的時候,action
這個消費者就會被執行。這個方法返回CompletableFuture<Void>
applyToEither
方法是當任意一個CompletionStage完成的時候,fn
會被執行,它的返回值會當作新的CompletableFuture<U>
的計算結果。
下面這個例子有時會輸出100
,有時候會輸出200
,哪個Future先完成就會根據它的結果計算。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
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
前面我們已經介紹了幾個靜態方法:completedFuture
、runAsync
、supplyAsync
,下面介紹的這兩個方法用來組合多個CompletableFuture。
1
2
|
public static CompletableFuture<Void> allOf(CompletableFuture<?>... cfs)
public static CompletableFuture<Object> anyOf(CompletableFuture<?>... cfs)
|
allOf
方法是當所有的CompletableFuture
都執行完后執行計算。anyOf
方法是當任意一個CompletableFuture
執行完后就會執行計算,計算的結果相同。
下面的代碼運行結果有時是100,有時是"abc"。但是anyOf
和applyToEither
不同。anyOf
接受任意多的CompletableFuture但是applyToEither
只是判斷兩個CompletableFuture,anyOf
返回值的計算結果是參數中其中一個CompletableFuture的計算結果,applyToEither
返回值的計算結果卻是要經過fn
處理的。當然還有靜態方法的區別,線程池的選擇等。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
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());
|
我想通過上面的介紹,應該把CompletableFuture的方法和功能介紹完了(cancel
、isCompletedExceptionally()
、isDone()
以及繼承於Object的方法無需介紹了, toCompletableFuture()
返回CompletableFuture本身),希望你能全面了解CompletableFuture強大的功能,並將它應用到Java的異步編程中。如果你有使用它的開源項目,可以留言分享一下。
更進一步
如果你用過Guava的Future類,你就會知道它的Futures
輔助類提供了很多便利方法,用來處理多個Future,而不像Java的CompletableFuture,只提供了allOf
、anyOf
兩個方法。 比如有這樣一個需求,將多個CompletableFuture組合成一個CompletableFuture,這個組合后的CompletableFuture的計算結果是個List,它包含前面所有的CompletableFuture的計算結果,guava的Futures.allAsList
可以實現這樣的功能,但是對於java CompletableFuture,我們需要一些輔助方法:
1
2
3
4
5
6
7
8
|
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:
1
2
3
4
5
6
7
8
9
|
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);
}
|
github有多個項目可以實現Java CompletableFuture與其它Future (如Guava ListenableFuture)之間的轉換,如spotify/futures-extra、future-converter、scala/scala-java8-compat 等。