本部分介紹Java 8 中提供的具備異步回調(diào)能力的工具類——CompletableFuture,該類實(shí)現(xiàn)了Future接口,還具備函數(shù)式編程能力。
CompletableFuture詳解
CompletableFuture類實(shí)現(xiàn)了Future和CompletionStage兩個(gè)接口,該類的實(shí)例作為一個(gè)異步任務(wù)。
CompletionStage接口
CompletionStage代表某個(gè)同步或者異步計(jì)算的一個(gè)階段,或者一些列異步任務(wù)中的一個(gè)子任務(wù)。
每個(gè)CompletionStage子任務(wù)所包裝的可以是一個(gè)Function、Consumer或者Runnable函數(shù)式接口實(shí)例。這三個(gè)函數(shù)式接口特點(diǎn)如下:
- Function接口的特點(diǎn)是有輸入、有輸出。
- Runnable接口的特點(diǎn)是無輸入、無輸出。
- Consumer接口的特點(diǎn)是有輸入、無輸出。
多個(gè)CompletionStage構(gòu)成了一條任務(wù)流水線,多個(gè)子任務(wù)之間可以使用鏈?zhǔn)秸{(diào)用,下面是個(gè)簡單的例子:
oneStage.thenApply(x -> square(x))
.thenAccept(y -> System.out.println(y))
.thenRun(() -> System.out.println())
上例子說明如下:
- oneStage是一個(gè)CompletionStage子任務(wù)。
-
x -> square(x)
是一個(gè)Function類型的Lambda表達(dá)式,被thenApply方法包裝成了CompletionStage子任務(wù),它又包含輸入和輸出。 -
y -> System.out.println(y)
是一個(gè)Consumer類型的Lambda表達(dá)式,被thenAccept包裝成了一個(gè)CompletionStage子任務(wù),它只有輸入(即上個(gè)任務(wù)的輸出)。 -
() -> System.out.println()
是一個(gè)Runnable類型的Lambda表達(dá)式,被thenRun方法包裝成了一個(gè)CompletionStage子任務(wù),它沒有輸入輸出。
使用runAsync和supplyAsync創(chuàng)建子任務(wù)
CompletableFuture定義了一組用于創(chuàng)建CompletionStage子任務(wù)的方法。
// 子任務(wù)包裝一個(gè)Runnable實(shí)例,并調(diào)用ForkJoinPool。commonPool線程池來執(zhí)行
public static CompletableFuture<Void> runAsync(Runnable runnable)
// 子任務(wù)包裝一個(gè)Runnable實(shí)例,并調(diào)用指定的executor線程池來執(zhí)行
public static CompletableFuture<Void> runAsync(Runnable runnable, Executor executor)
// 子任務(wù)包裝一個(gè)Supplier實(shí)例,并調(diào)用ForkJoinPool。commonPool線程池來執(zhí)行
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier)
// 子任務(wù)包裝一個(gè)Supplier實(shí)例,并調(diào)用指定的executor線程池來執(zhí)行
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier, Executor executor)
執(zhí)行子任務(wù)時(shí),如果沒有執(zhí)行Executor線程池,默認(rèn)情況下會(huì)使用公共的ForkJoinPool線程池。
設(shè)置子任務(wù)回調(diào)鉤子
可以為CompletionStage子任務(wù)設(shè)置特定的回調(diào)鉤子,當(dāng)計(jì)算結(jié)果完成或者拋出異常的時(shí)候,執(zhí)行這些特定的鉤子。
設(shè)置子任務(wù)回調(diào)鉤子的主要函數(shù)如下:
// 設(shè)置子任務(wù)完成時(shí)的回調(diào)鉤子
public CompletableFuture<T> whenComplete(BiConsumer<? super T, ? super Throeable> action)
// 設(shè)置子任務(wù)完成時(shí)的回調(diào)鉤子,可能不在同一線程執(zhí)行
public CompletableFuture<T> whenCompleteAsync(BiConsumer<? super T, ? super Throwable> action)
// 設(shè)置子任務(wù)完成時(shí)的回調(diào)鉤子,提交給線程池executor執(zhí)行
public CompletableFuture<T> whenCompleteAsync(BiConsumer<? super T, ? super Throwable> action, Executor executor)
// 設(shè)置異常處理的回調(diào)鉤子
public CompletableFuture<T> exceptionally(Fuction<Throwable, ? extends T> fn)
下面看個(gè)簡單例子:
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("發(fā)生異常");
});
// 設(shè)置異步任務(wù)執(zhí)行完成后的回調(diào)鉤子
future.whenComplete(new BiConsumer<Void, Throwable>() {
@Override
public void accept(Void aVoid, Throwable throwable) {
System.out.println("執(zhí)行完成");
}
});
future.exceptionally(new Function<Throwable, Void>() {
@Override
public Void apply(Throwable t) {
System.out.println("執(zhí)行失敗:" + t.getMessage());
return null;
}
});
future.get();
}
}
運(yùn)行結(jié)果:
拋出異常
執(zhí)行完成
執(zhí)行失敗:java.lang.RuntimeException: 發(fā)生異常
調(diào)用cancel方法取消CompletableFuture時(shí),任務(wù)被視為異常完成,completeExceptionally方法所設(shè)置的異常回調(diào)鉤子也會(huì)被執(zhí)行。
如果沒有設(shè)置異常回調(diào)鉤子,發(fā)生內(nèi)部異常時(shí)會(huì)有兩種情況發(fā)生:
- 在調(diào)用get方法啟動(dòng)任務(wù)時(shí),如果遇到內(nèi)部異常,get方法就會(huì)拋出ExecutionException。
- 在調(diào)用join和getNow啟動(dòng)任務(wù)時(shí)(大多數(shù)情況下都是如此),如果遇到內(nèi)部異常,會(huì)拋出CompletionException。
調(diào)用handle方法統(tǒng)一處理異常和結(jié)果
除了分別通過whenComplete、exceptionally設(shè)置完成鉤子、異常鉤子之外,還可以調(diào)用handle方法統(tǒng)一處理結(jié)果和異常。
handle方法有3個(gè)重載版本:
// 在執(zhí)行任務(wù)的同一個(gè)線程中處理異常和結(jié)果
public<U> CompletionStage<U> handle (BiFunction<? super T, Throwable, ? extends U> fn);
// 可能不再執(zhí)行任務(wù)的同一個(gè)線程中處理異常和結(jié)果
public <U> CompletionStage<U> handleAsync(BiFunction<? super T, Throwable, ? extends U> fn);
// 在指定線程池executor中處理異常和結(jié)果
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("發(fā)生異常");
});
future.handle(new BiFunction<Void, Throwable, Void>() {
@Override
public Void apply(Void input, Throwable throwable) {
if(throwable == null) {
System.out.println("沒有發(fā)生異常");
} else {
System.out.println("發(fā)生了異常");
}
return null;
}
});
future.get();
}
}
線程池的使用
默認(rèn)情況下,通過靜態(tài)方法runAsync和supplyAsync創(chuàng)建的CompletableFuture任務(wù)會(huì)使用公共的ForkJoinPool線程池。默認(rèn)的線程數(shù)是CPU的核數(shù)。
如果所有CompletableFuture任務(wù)共享一個(gè)線程池,那么一旦有任務(wù)執(zhí)行一些很慢的IO操作,會(huì)導(dǎo)致所有線程阻塞,造成線程饑餓。所以建議大家根據(jù)不同的業(yè)務(wù)類型創(chuàng)建不同的線程池。
異步任務(wù)的串行執(zhí)行
如果兩個(gè)異步任務(wù)需要串行,可以通過CompletionStage接口的thenApply、thenAccept、thenRun和thenCompose方法實(shí)現(xiàn)。
theApply方法
theApply方法有三個(gè)重載版本,聲明如下:
// 后一個(gè)任務(wù)與前一個(gè)任務(wù)在同一個(gè)線程中執(zhí)行
public <U> CompletableFuture<U> thenApply(Function<? super T, ? extends U> fn)
// 后一個(gè)任務(wù)與前一個(gè)任務(wù)不在同一個(gè)線程中執(zhí)行
public <U> CompletableFuture<U> thenApplyAsync(Function<? super T, ? extends U> fn)
// 后一個(gè)任務(wù)在指定的executor線程池中執(zhí)行
public <U> CompletableFuture<U> thenApplyAsync(Function<? super T, ? extends U> fn, Executor executor)
參數(shù)fn表示要串行執(zhí)行的第二個(gè)異步任務(wù),泛型參數(shù)T是上一個(gè)任務(wù)所返回結(jié)果的類型,泛型參數(shù)U是當(dāng)前任務(wù)的返回值類型。
看個(gè)簡單例子。
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) { // 參數(shù)是第一步的結(jié)果
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方法不關(guān)心任務(wù)的處理結(jié)果,只需要前一個(gè)任務(wù)執(zhí)行完成,就開始執(zhí)行后一個(gè)串行任務(wù)。
thenApply方法也有三個(gè)重載版本,聲明如下:
// 后一個(gè)任務(wù)與前一個(gè)任務(wù)在同一個(gè)線程中執(zhí)行
public CompletionStage<Void> thenRun(Runnable action);
// 后一個(gè)任務(wù)與前一個(gè)任務(wù)不再同一個(gè)線程中執(zhí)行
public CompletionStage<Void> thenRunAsync(Runnable action);
// 后一個(gè)任務(wù)在executor線程池中執(zhí)行
public CompletionStage<Void> thenRunAsync(Runnable action, Executor executor);
thenAccept方法
thenAccept方法接收前一個(gè)任務(wù)的處理結(jié)果,但是沒有輸出。
thenAccept方法有三個(gè)重載版本,聲明如下:
// 后一個(gè)任務(wù)與前一個(gè)任務(wù)在同一個(gè)線程中執(zhí)行
public CompletionStage<Void> thenAccept(Consumer<? super T> action);
// 后一個(gè)任務(wù)與前一個(gè)任務(wù)不再同一個(gè)線程中執(zhí)行
public CompletionStage<Void> thenRunAsync(Consumer<? super T> action);
// 后一個(gè)任務(wù)在executor線程池中執(zhí)行
public CompletionStage<Void> thenRunAsync(Consumer<? super T> action, Executor executor);
thenCompose方法
thenCompose方法在第一個(gè)任務(wù)操作完成時(shí),將它的結(jié)果作為參數(shù)傳遞給第二個(gè)任務(wù)。
thenCompose方法有3個(gè)重載版本,聲明如下:
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方法要求第二個(gè)任務(wù)的返回值是一個(gè)CompletionStage異步實(shí)例。
將前面的例子改成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);
}
}
異步任務(wù)的合并執(zhí)行
對兩個(gè)異步任務(wù)合并可以通過CompletionStage接口的thenCombine、runAfterBoth和thenAcceptBoth三個(gè)方法來實(shí)現(xiàn)。
thenCombine方法
thenCombine會(huì)在兩個(gè)任務(wù)都執(zhí)行完成后,把兩個(gè)任務(wù)的結(jié)果一起交給thenCombine來處理。
public <U, V> CompletionStage<V> thenCombine(
CompletionStage<? extends U> other, // 待合并實(shí)例
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
);
下面看一個(gè)使用thenCombine分三步計(jì)算(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方法不關(guān)心沒異步任務(wù)的輸入?yún)?shù)和處理結(jié)果。
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方法可以接收前兩個(gè)任務(wù)的處理結(jié)果,但是第三個(gè)任務(wù)卻不返回結(jié)果。
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等待所有的任務(wù)結(jié)束
allOf會(huì)等待所有任務(wù)結(jié)束,以合并所有任務(wù)。
異步任務(wù)的選擇執(zhí)行
對有兩個(gè)異步任務(wù)的選擇可以通過CompletionStage接口的applyToEither、runAfterEither和acceptEither三個(gè)方法來實(shí)現(xiàn)。
applyToEither方法
兩個(gè)CompletionStage誰返回結(jié)果的速度快,applyToEither方法就用這個(gè)結(jié)果進(jìn)行下一步操作。
// 和other任務(wù)返回較快的結(jié)果用于執(zhí)行fn回調(diào)函數(shù)
public <U> CompletionStage<U> applyToEither(
CompletionStage<? extends T> other, Function<? super T, U> fn
);
// 功能與上一個(gè)相同,但是不一定在同一個(gè)線程執(zhí)行fn
public <U> CompletionStage<U> applyToEitherAsync(
CompletionStage<? extends T> other, Function<? super T, U> fn
);
// 功能與上一個(gè)相同,在指定線程執(zhí)行fn
public <U> CompletionStage<U> applyToEitherAsync(
CompletionStage<? extends T> other, Function<? super T, U> fn, Executor executor
);
看個(gè)例子。
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方法的功能為前面兩個(gè)CompletionStage實(shí)例,任何一個(gè)執(zhí)行完成都會(huì)執(zhí)行第三部回調(diào)。
// 和other任務(wù)返回較快的結(jié)果用于執(zhí)行fn回調(diào)函數(shù)
public CompletionStage<Void> runAfterEither(
CompletionStage<?> other, Runnable fn
);
// 功能與上一個(gè)相同,但是不一定在同一個(gè)線程執(zhí)行fn
public CompletionStage<Void> runAfterEitherAsync(
CompletionStage<?> other, Runnable fn
);
// 功能與上一個(gè)相同,在指定線程執(zhí)行fn
public CompletionStage<Void> runAfterEitherAsync(
CompletionStage<?> other, Runnable fn, Executor executor
);
acceptEither方法
acceptEither用哪個(gè)最快的CompletionStage的結(jié)果作為下一步的輸入,但是第三步?jīng)]有輸出。
// 和other任務(wù)返回較快的結(jié)果用于執(zhí)行fn回調(diào)函數(shù)
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實(shí)現(xiàn)喝茶案例。
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());
}
}