本部分介紹Java 8 中提供的具備異步回調能力的工具類——CompletableFuture,該類實現了Future接口,還具備函數式編程能力。
CompletableFuture詳解
CompletableFuture類實現了Future和CompletionStage兩個接口,該類的實例作為一個異步任務。
CompletionStage接口
CompletionStage代表某個同步或者異步計算的一個階段,或者一些列異步任務中的一個子任務。
每個CompletionStage子任務所包裝的可以是一個Function、Consumer或者Runnable函數式接口實例。這三個函數式接口特點如下:
- Function接口的特點是有輸入、有輸出。
- Runnable接口的特點是無輸入、無輸出。
- Consumer接口的特點是有輸入、無輸出。
多個CompletionStage構成了一條任務流水線,多個子任務之間可以使用鏈式調用,下面是個簡單的例子:
oneStage.thenApply(x -> square(x))
.thenAccept(y -> System.out.println(y))
.thenRun(() -> System.out.println())
上例子說明如下:
- oneStage是一個CompletionStage子任務。
-
x -> square(x)
是一個Function類型的Lambda表達式,被thenApply方法包裝成了CompletionStage子任務,它又包含輸入和輸出。 -
y -> System.out.println(y)
是一個Consumer類型的Lambda表達式,被thenAccept包裝成了一個CompletionStage子任務,它只有輸入(即上個任務的輸出)。 -
() -> System.out.println()
是一個Runnable類型的Lambda表達式,被thenRun方法包裝成了一個CompletionStage子任務,它沒有輸入輸出。
使用runAsync和supplyAsync創建子任務
CompletableFuture定義了一組用于創建CompletionStage子任務的方法。
// 子任務包裝一個Runnable實例,并調用ForkJoinPool。commonPool線程池來執行
public static CompletableFuture<Void> runAsync(Runnable runnable)
// 子任務包裝一個Runnable實例,并調用指定的executor線程池來執行
public static CompletableFuture<Void> runAsync(Runnable runnable, Executor executor)
// 子任務包裝一個Supplier實例,并調用ForkJoinPool。commonPool線程池來執行
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier)
// 子任務包裝一個Supplier實例,并調用指定的executor線程池來執行
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier, Executor executor)
執行子任務時,如果沒有執行Executor線程池,默認情況下會使用公共的ForkJoinPool線程池。
設置子任務回調鉤子
可以為CompletionStage子任務設置特定的回調鉤子,當計算結果完成或者拋出異常的時候,執行這些特定的鉤子。
設置子任務回調鉤子的主要函數如下:
// 設置子任務完成時的回調鉤子
public CompletableFuture<T> whenComplete(BiConsumer<? super T, ? super Throeable> action)
// 設置子任務完成時的回調鉤子,可能不在同一線程執行
public CompletableFuture<T> whenCompleteAsync(BiConsumer<? super T, ? super Throwable> action)
// 設置子任務完成時的回調鉤子,提交給線程池executor執行
public CompletableFuture<T> whenCompleteAsync(BiConsumer<? super T, ? super Throwable> action, Executor executor)
// 設置異常處理的回調鉤子
public CompletableFuture<T> exceptionally(Fuction<Throwable, ? extends T> fn)
下面看個簡單例子:
public class CompletableFutureDemo {
public static void main(String[] args) throws Exception {
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("拋出異常");
throw new RuntimeException("發生異常");
});
// 設置異步任務執行完成后的回調鉤子
future.whenComplete(new BiConsumer<Void, Throwable>() {
@Override
public void accept(Void aVoid, Throwable throwable) {
System.out.println("執行完成");
}
});
future.exceptionally(new Function<Throwable, Void>() {
@Override
public Void apply(Throwable t) {
System.out.println("執行失敗:" + t.getMessage());
return null;
}
});
future.get();
}
}
運行結果:
拋出異常
執行完成
執行失敗:java.lang.RuntimeException: 發生異常
調用cancel方法取消CompletableFuture時,任務被視為異常完成,completeExceptionally方法所設置的異常回調鉤子也會被執行。
如果沒有設置異常回調鉤子,發生內部異常時會有兩種情況發生:
- 在調用get方法啟動任務時,如果遇到內部異常,get方法就會拋出ExecutionException。
- 在調用join和getNow啟動任務時(大多數情況下都是如此),如果遇到內部異常,會拋出CompletionException。
調用handle方法統一處理異常和結果
除了分別通過whenComplete、exceptionally設置完成鉤子、異常鉤子之外,還可以調用handle方法統一處理結果和異常。
handle方法有3個重載版本:
// 在執行任務的同一個線程中處理異常和結果
public<U> CompletionStage<U> handle (BiFunction<? super T, Throwable, ? extends U> fn);
// 可能不再執行任務的同一個線程中處理異常和結果
public <U> CompletionStage<U> handleAsync(BiFunction<? super T, Throwable, ? extends U> fn);
// 在指定線程池executor中處理異常和結果
public <U> CompletionStage<U> handleAsync(BiFunction<? super T, Throwable, ? extends U> fn, Executor executor);
將前面的例子改成handle版本。
public class CompletableFutureDemo {
public static void main(String[] args) throws Exception {
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("拋出異常");
throw new RuntimeException("發生異常");
});
future.handle(new BiFunction<Void, Throwable, Void>() {
@Override
public Void apply(Void input, Throwable throwable) {
if(throwable == null) {
System.out.println("沒有發生異常");
} else {
System.out.println("發生了異常");
}
return null;
}
});
future.get();
}
}
線程池的使用
默認情況下,通過靜態方法runAsync和supplyAsync創建的CompletableFuture任務會使用公共的ForkJoinPool線程池。默認的線程數是CPU的核數。
如果所有CompletableFuture任務共享一個線程池,那么一旦有任務執行一些很慢的IO操作,會導致所有線程阻塞,造成線程饑餓。所以建議大家根據不同的業務類型創建不同的線程池。
異步任務的串行執行
如果兩個異步任務需要串行,可以通過CompletionStage接口的thenApply、thenAccept、thenRun和thenCompose方法實現。
theApply方法
theApply方法有三個重載版本,聲明如下:
// 后一個任務與前一個任務在同一個線程中執行
public <U> CompletableFuture<U> thenApply(Function<? super T, ? extends U> fn)
// 后一個任務與前一個任務不在同一個線程中執行
public <U> CompletableFuture<U> thenApplyAsync(Function<? super T, ? extends U> fn)
// 后一個任務在指定的executor線程池中執行
public <U> CompletableFuture<U> thenApplyAsync(Function<? super T, ? extends U> fn, Executor executor)
參數fn表示要串行執行的第二個異步任務,泛型參數T是上一個任務所返回結果的類型,泛型參數U是當前任務的返回值類型。
看個簡單例子。
public class ThenApplyDemo {
public static void main(String[] args) throws Exception {
CompletableFuture<Long> future = CompletableFuture.supplyAsync(new Supplier<Long>() {
@Override
public Long get() {
long firstStep = 10L + 10L;
System.out.println("first step outcome is " + firstStep);
return firstStep;
}
}).thenApplyAsync(new Function<Long, Long>() {
@Override
public Long apply(Long aLong) { // 參數是第一步的結果
long secondStep = aLong * 2;
System.out.println("Second outcome is " + secondStep);
return secondStep;
}
});
long result = future.get();
System.out.println("outcome is " + result);
}
}
thenRun方法
thenRun方法不關心任務的處理結果,只需要前一個任務執行完成,就開始執行后一個串行任務。
thenApply方法也有三個重載版本,聲明如下:
// 后一個任務與前一個任務在同一個線程中執行
public CompletionStage<Void> thenRun(Runnable action);
// 后一個任務與前一個任務不再同一個線程中執行
public CompletionStage<Void> thenRunAsync(Runnable action);
// 后一個任務在executor線程池中執行
public CompletionStage<Void> thenRunAsync(Runnable action, Executor executor);
thenAccept方法
thenAccept方法接收前一個任務的處理結果,但是沒有輸出。
thenAccept方法有三個重載版本,聲明如下:
// 后一個任務與前一個任務在同一個線程中執行
public CompletionStage<Void> thenAccept(Consumer<? super T> action);
// 后一個任務與前一個任務不再同一個線程中執行
public CompletionStage<Void> thenRunAsync(Consumer<? super T> action);
// 后一個任務在executor線程池中執行
public CompletionStage<Void> thenRunAsync(Consumer<? super T> action, Executor executor);
thenCompose方法
thenCompose方法在第一個任務操作完成時,將它的結果作為參數傳遞給第二個任務。
thenCompose方法有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);
thenCompose方法要求第二個任務的返回值是一個CompletionStage異步實例。
將前面的例子改成theCompose版本:
public class ThenComposeDemo {
public static void main(String[] args) throws Exception {
CompletableFuture<Long> future = CompletableFuture.supplyAsync(new Supplier<Long>() {
@Override
public Long get() {
long firstStep = 10L + 10L;
System.out.println("first step outcome is " + firstStep);
return firstStep;
}
}).thenCompose(new Function<Long, CompletionStage<Long>>() {
@Override
public CompletionStage<Long> apply(Long firstStepOutcome) {
return CompletableFuture.supplyAsync(new Supplier<Long>() {
@Override
public Long get() {
long secondStep = firstStepOutcome * 2;
System.out.println("Second outcome is " + secondStep);
return secondStep;
}
});
}
});
long result = future.get();
System.out.println("outcome is " + result);
}
}
異步任務的合并執行
對兩個異步任務合并可以通過CompletionStage接口的thenCombine、runAfterBoth和thenAcceptBoth三個方法來實現。
thenCombine方法
thenCombine會在兩個任務都執行完成后,把兩個任務的結果一起交給thenCombine來處理。
public <U, V> CompletionStage<V> thenCombine(
CompletionStage<? extends U> other, // 待合并實例
BiFunction<? super T, ? super U, ? extends V> fn);
public <U, V> CompletionStage<V> thenCombineAsync(
CompletionStage<? extends U> other,
BiFunction<? super T, ? super U, ? extends V> fn
);
public <U, V> CompletionStage<V> thenCombineAsync(
CompletionStage<? extends U> other,
BiFunction<? super T, ? super U, ? extends V> fn,
Executor executor
);
下面看一個使用thenCombine分三步計算(10+10)*(10+10)
的例子:
public class ThenCombineDemo {
public static void main(String[] args) throws Exception {
CompletableFuture<Integer> future1 =
CompletableFuture.supplyAsync(new Supplier<Integer>() {
@Override
public Integer get() {
Integer firstStep = 10 + 10;
System.out.println("firstStep outcome is " + firstStep);
return firstStep;
}
});
CompletableFuture<Integer> future2 =
CompletableFuture.supplyAsync(new Supplier<Integer>() {
@Override
public Integer get() {
Integer secondStep = 10 + 10;
System.out.println("secondStep outcome is " + secondStep);
return secondStep;
}
});
CompletableFuture<Integer> future3 = future1.thenCombine(future2,
new BiFunction<Integer, Integer, Integer>() {
@Override
public Integer apply(Integer integer, Integer integer2) {
return integer * integer2;
}
});
Integer result = future3.get();
System.out.println(" outcome is " + result);
}
}
runAfterBoth方法
runAfterBoth方法不關心沒異步任務的輸入參數和處理結果。
public CompletionStage<Void> runAfterBoth(
CompletionStage<?> other, Runnable action
);
public CompletionStage<Void> runAfterBothAsync(
CompletionStage<?> other, Runnable action
);
public CompletionStage<Void> runAfterBothAsync(
CompletionStage<?> other, Runnable action, Executor executor
);
thenAcceptBoth方法
thenAcceptBoth方法可以接收前兩個任務的處理結果,但是第三個任務卻不返回結果。
public <U> CompletionStage<Void> thenAcceptBoth(
CompletionStage<? extends U> other,
BiConusmer<? super T, ? super U> action
);
public <U> CompletionStage<Void> thenAcceptBothAsync(
CompletionStage<? extends U> other,
BiConusmer<? super T, ? super U> action
);
public <U> CompletionStage<Void> thenAcceptBothAsync(
CompletionStage<? extends U> other,
BiConusmer<? super T, ? super U> action,
Executor executor
);
allOf等待所有的任務結束
allOf會等待所有任務結束,以合并所有任務。
異步任務的選擇執行
對有兩個異步任務的選擇可以通過CompletionStage接口的applyToEither、runAfterEither和acceptEither三個方法來實現。
applyToEither方法
兩個CompletionStage誰返回結果的速度快,applyToEither方法就用這個結果進行下一步操作。
// 和other任務返回較快的結果用于執行fn回調函數
public <U> CompletionStage<U> applyToEither(
CompletionStage<? extends T> other, Function<? super T, U> fn
);
// 功能與上一個相同,但是不一定在同一個線程執行fn
public <U> CompletionStage<U> applyToEitherAsync(
CompletionStage<? extends T> other, Function<? super T, U> fn
);
// 功能與上一個相同,在指定線程執行fn
public <U> CompletionStage<U> applyToEitherAsync(
CompletionStage<? extends T> other, Function<? super T, U> fn, Executor executor
);
看個例子。
public class ApplyToEitherDemo {
public static void main(String[] args) throws Exception{
CompletableFuture<Integer> future1 =
CompletableFuture.supplyAsync(new Supplier<Integer>() {
@Override
public Integer get() {
Integer firstStep = 10 + 10;
System.out.println("firstStep outcome is " + firstStep);
return firstStep;
}
});
CompletableFuture<Integer> future2 =
CompletableFuture.supplyAsync(new Supplier<Integer>() {
@Override
public Integer get() {
Integer secondStep = 100 + 100;
System.out.println("secondStep outcome is " + secondStep);
return secondStep;
}
});
CompletableFuture<Integer> future3 =
future1.applyToEither(future2,
new Function<Integer, Integer>() {
@Override
public Integer apply(Integer integer) {
return integer;
}
});
Integer result = future3.get();
System.out.println("outcome is " + result);
}
}
runAfterEither方法
runAfterEither方法的功能為前面兩個CompletionStage實例,任何一個執行完成都會執行第三部回調。
// 和other任務返回較快的結果用于執行fn回調函數
public CompletionStage<Void> runAfterEither(
CompletionStage<?> other, Runnable fn
);
// 功能與上一個相同,但是不一定在同一個線程執行fn
public CompletionStage<Void> runAfterEitherAsync(
CompletionStage<?> other, Runnable fn
);
// 功能與上一個相同,在指定線程執行fn
public CompletionStage<Void> runAfterEitherAsync(
CompletionStage<?> other, Runnable fn, Executor executor
);
acceptEither方法
acceptEither用哪個最快的CompletionStage的結果作為下一步的輸入,但是第三步沒有輸出。
// 和other任務返回較快的結果用于執行fn回調函數
public CompletionStage<Void> acceptEither(
CompletionStage<?> other, Consumer<? super T> fn
);
public CompletionStage<Void> acceptEitherAsync(
CompletionStage<?> other, Consumer<? super T> fn
);
public CompletionStage<Void> acceptEitherAsync(
CompletionStage<?> other, Consumer<? super T> fn, Executor executor
);
CompletableFuture的綜合案例
使用CompletableFuture實現喝茶案例。
public class CompletableFutureDemo2 {
private static final int SLEEP_GAP = 3;
public static void main(String[] args) {
// 洗水壺->燒開水
CompletableFuture<Boolean> hotJob =
CompletableFuture.supplyAsync(() -> {
System.out.println("洗好水壺");
System.out.println("燒開水");
try {
Thread.sleep(SLEEP_GAP);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("水開了");
return true;
});
// 洗茶杯->那茶葉
CompletableFuture<Boolean> washJob =
CompletableFuture.supplyAsync(() -> {
System.out.println("洗茶杯");
try {
Thread.sleep(SLEEP_GAP);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("洗完了");
return true;
});
CompletableFuture<String> drinkJob =
hotJob.thenCombine(washJob, (hotOK, washOk) -> {
if(hotOK && washOk) {
System.out.println("泡茶喝,茶喝完");
return "茶喝完了";
}
return "沒有喝到差";
});
System.out.println(drinkJob.join());
}
}