java1.8新特性 CompletableFuture 使用案例詳解
CompletableFuture方法詳解
1、runAsync 和 supplyAsync方法
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);
沒有指定Executor的方法會使用ForkJoinPool.commonPool() 作為它的執行緒池執行非同步程式碼。如果指定執行緒池,則使用指定的執行緒池執行。以下所有的方法都類同。
- runAsync方法不支援返回值。
- supplyAsync可以支援返回值。
示例
public static void main(String[] args) throws Exception { CompletableFuture<Void> future = CompletableFuture.runAsync(() -> { try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("執行結束"); }); future.get(); }
public static void main(String[] args) throws Exception { CompletableFuture<Long> future = CompletableFuture.supplyAsync(() -> { long start = System.currentTimeMillis(); try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("執行結束"); return System.currentTimeMillis() - start; }); System.out.println("執行時間 => " + future.get()); }
2、計算結果完成時的回撥方法
當CompletableFuture的計算結果完成,或者丟擲異常的時候,可以執行特定的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的型別是BiConsumer<? super T,? super Throwable>它可以處理正常的計算結果,或者異常情況。
whenComplete 和 whenCompleteAsync 的區別:
whenComplete:是執行當前任務的執行緒執行繼續執行 whenComplete 的任務。
whenCompleteAsync:是執行把 whenCompleteAsync 這個任務繼續提交給執行緒池來進行執行。
示例
public static void main(String[] args) throws Exception {
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (new Random().nextInt() % 2 >= 0) {
int i = 12 / 0;
}
System.out.println("執行結束");
});
future.whenComplete((t, action) -> System.out.println("執行完成!"));
future.exceptionally(t -> {
System.out.println("執行失敗!" + t.getMessage());
return null;
});
TimeUnit.SECONDS.sleep(2);
}
執行成功結果
異常結果
3、 thenApply 方法
當一個執行緒依賴另一個執行緒時,可以使用 thenApply 方法來把這兩個執行緒序列化。
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);
Function<? super T,? extends U>
T:上一個任務返回結果的型別
U:當前任務的返回值型別
示例
public static void main(String[] args) throws Exception {
CompletableFuture<Long> future = CompletableFuture.supplyAsync(() -> {
long result = new Random().nextInt(100);
System.out.println("結果1 => " + result);
return result;
}).thenApply(t -> {
long result = t * 5;
System.out.println("結果2 => " + result);
return result;
});
long result = future.get();
System.out.println(result);
}
第二個任務依賴第一個任務的結果。
4、 handle 方法
handle 是執行任務完成時對結果的處理。
handle 方法和 thenApply 方法處理方式基本一樣。不同的是 handle 是在任務完成後再執行,還可以處理異常的任務。thenApply 只可以執行正常的任務,任務出現異常則不執行 thenApply 方法。
public <U> CompletionStage<U> handle(BiFunction<? super T, Throwable, ? extends U> fn);
public <U> CompletionStage<U> handleAsync(BiFunction<? super T, Throwable, ? extends U> fn);
public <U> CompletionStage<U> handleAsync(BiFunction<? super T, Throwable, ? extends U> fn,Executor executor);
示例
public static void main(String[] args) throws Exception {
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
int i = 10 / 0;
return new Random().nextInt(10);
}).handle((param, throwable) -> {
int result = -1;
if (throwable == null) {
result = param * 2;
} else {
System.out.println(throwable.getMessage());
}
return result;
});
System.out.println(future.get());
}
從示例中可以看出,在 handle 中可以根據任務是否有異常來進行做相應的後續處理操作。而 thenApply 方法,如果上個任務出現錯誤,則不會執行 thenApply 方法。
5、 thenAccept 消費處理結果
接收任務的處理結果,並消費處理,無返回結果。
public CompletionStage<Void> thenAccept(Consumer<? super T> action);
public CompletionStage<Void> thenAcceptAsync(Consumer<? super T> action);
public CompletionStage<Void> thenAcceptAsync(Consumer<? super T> action,Executor executor);
示例
public static void main(String[] args) throws Exception {
CompletableFuture<Void> future = CompletableFuture.supplyAsync(() ->
new Random().nextInt(10))
.thenAccept(t -> System.out.println("結果為 => " + t));
future.get();
}
從示例程式碼中可以看出,該方法只是消費執行完成的任務,並可以根據上面的任務返回的結果進行處理。並沒有後續的輸錯操作。
6、thenRun 方法
跟 thenAccept 方法不一樣的是,不關心任務的處理結果。只要上面的任務執行完成,就開始執行 thenAccept 。
public CompletionStage<Void> thenRun(Runnable action);
public CompletionStage<Void> thenRunAsync(Runnable action);
public CompletionStage<Void> thenRunAsync(Runnable action,Executor executor);
示例
public static void main(String[] args) throws Exception {
CompletableFuture<Void> future = CompletableFuture.supplyAsync(() ->
new Random().nextInt(10))
.thenRun(() -> System.out.println("thenRun ..."));
future.get();
}
該方法同 thenAccept 方法類似。不同的是上個任務處理完成後,並不會把計算的結果傳給 thenRun 方法。只是處理玩任務後,執行 thenAccept 的後續操作。
7、thenCombine 合併任務
thenCombine 會把 兩個 CompletionStage 的任務都執行完成後,把兩個任務的結果一塊交給 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);
示例
public static void main(String[] args) throws Exception {
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> "hello");
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> "world");
CompletableFuture<String> result = future1.thenCombine(future2, (t, u) -> t + " " + u);
System.out.println(result.get());
}
8、thenAcceptBoth
當兩個CompletionStage都執行完成後,把結果一塊交給thenAcceptBoth來進行消耗
public <U> CompletionStage<Void> thenAcceptBoth(CompletionStage<? extends U> other,BiConsumer<? super T, ? super U> action);
public <U> CompletionStage<Void> thenAcceptBothAsync(CompletionStage<? extends U> other,BiConsumer<? super T, ? super U> action);
public <U> CompletionStage<Void> thenAcceptBothAsync(CompletionStage<? extends U> other,BiConsumer<? super T, ? super U> action, Executor executor);
示例
public static void main(String[] args) throws Exception {
CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> {
int t = new Random().nextInt(3);
try {
TimeUnit.SECONDS.sleep(t);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("future1 => " + t);
return t;
});
CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> {
int t = new Random().nextInt(3);
try {
TimeUnit.SECONDS.sleep(t);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("future2 => " + t);
return t;
});
TimeUnit.SECONDS.sleep(3);
future1.thenAcceptBoth(future2, (t, u) -> System.out.println("future1 => " + t + "; future2 => " + u + ";"));
}
9、applyToEither 方法
兩個CompletionStage,誰執行返回的結果快,我就用那個CompletionStage的結果進行下一步的轉化操作。
public <U> CompletionStage<U> applyToEither(CompletionStage<? extends T> other,Function<? super T, U> fn);
public <U> CompletionStage<U> applyToEitherAsync(CompletionStage<? extends T> other,Function<? super T, U> fn);
public <U> CompletionStage<U> applyToEitherAsync(CompletionStage<? extends T> other,Function<? super T, U> fn,Executor executor);
示例
public static void main(String[] args) throws Exception {
CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> {
int t = new Random().nextInt(3);
try {
TimeUnit.SECONDS.sleep(t);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("future1 => " + t);
return t;
});
CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> {
int t = new Random().nextInt(3);
try {
TimeUnit.SECONDS.sleep(t);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("future2 => " + t);
return t;
});
CompletableFuture<Integer> result = future1.applyToEither(future2, t -> {
System.out.println(t);
return t * 2;
});
System.out.println(result.get());
}
10、acceptEither 方法
兩個CompletionStage,誰執行返回的結果快,我就用那個CompletionStage的結果進行下一步的消耗操作。
public CompletionStage<Void> acceptEither(CompletionStage<? extends T> other,Consumer<? super T> action);
public CompletionStage<Void> acceptEitherAsync(CompletionStage<? extends T> other,Consumer<? super T> action);
public CompletionStage<Void> acceptEitherAsync(CompletionStage<? extends T> other,Consumer<? super T> action,Executor executor);
示例
public static void main(String[] args) throws Exception {
CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> {
int t = new Random().nextInt(3);
try {
TimeUnit.SECONDS.sleep(t);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("future1 => " + t);
return t;
});
CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> {
int t = new Random().nextInt(3);
try {
TimeUnit.SECONDS.sleep(t);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("future2 => " + t);
return t;
});
future1.acceptEither(future2, System.out::println);
}
11、runAfterEither 方法
兩個CompletionStage,任何一個完成了都會執行下一步的操作(Runnable)
public CompletionStage<Void> runAfterEither(CompletionStage<?> other,Runnable action);
public CompletionStage<Void> runAfterEitherAsync(CompletionStage<?> other,Runnable action);
public CompletionStage<Void> runAfterEitherAsync(CompletionStage<?> other,Runnable action,Executor executor);
示例
public static void main(String[] args) throws Exception {
CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> {
int t = new Random().nextInt(3);
try {
TimeUnit.SECONDS.sleep(t);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("future1 => " + t);
return t;
});
CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> {
int t = new Random().nextInt(3);
try {
TimeUnit.SECONDS.sleep(t);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("future2 => " + t);
return t;
});
future1.runAfterEither(future2, () -> System.out.println("任務有一方已經完成"));
}
12、runAfterBoth
兩個CompletionStage,都完成了計算才會執行下一步的操作(Runnable)
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);
示例
public static void main(String[] args) throws Exception {
CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> {
int t = new Random().nextInt(3);
try {
TimeUnit.SECONDS.sleep(t);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("future1 => " + t);
return t;
});
CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> {
int t = new Random().nextInt(3);
try {
TimeUnit.SECONDS.sleep(t);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("future2 => " + t);
return t;
});
future1.runAfterBoth(future2, () -> System.out.println("任務已經全部完成"));
}
13、thenCompose 方法
thenCompose 方法允許你對兩個 CompletionStage 進行流水線操作,第一個操作完成時,將其結果作為引數傳遞給第二個操作。
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);
示例
public static void main(String[] args) throws Exception {
CompletableFuture<Integer> f = CompletableFuture.supplyAsync(() -> {
int t = new Random().nextInt(3);
System.out.println("t1 => " + t);
return t;
}).thenCompose(param -> CompletableFuture.supplyAsync(() -> {
int t = param * 2;
System.out.println("t2 => " + t);
return t;
}));
System.out.println("thenCompose 結果 : " + f.get());
}
14、cancel 與isDone 方法
cancel 終止方法執行 會丟擲 CancellationException 完成此CompletableFuture。尚未完成的從屬CompletableFuture也將異常完成。
isDone 如果以任何方式(通常,異常或通過取消)完成,則返回 true。
public boolean cancel(boolean mayInterruptIfRunning);
public boolean isDone();
示例
private static void cancel() throws Exception {
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
try {
TimeUnit.SECONDS.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("執行結束");
});
future.whenComplete((t, action) -> System.out.println("執行完成!"));
future.exceptionally(t -> {
t.printStackTrace();
System.out.println("執行失敗!" + t.getMessage());
return null;
});
TimeUnit.SECONDS.sleep(2);
future.cancel(true);
System.out.println(future.isDone());
}