CompletableFuture為異步編程框架,當我們在使用線程池處理任務時,我們只能通過阻塞的Future#get()獲取異步的結果,當任務處理需要的時間比較長時,效率和性能就會比較差。而CompletableFuture彌補了Future,其主要是在任務處理完成后,調用應用的回調函數,這樣應用就無需通過Future#get()的方式獲取處理結果,而是通過任務的回調來通知應用結果,這樣極大的提高了應用的效率。同時CompletableFuture還提供了任務串行、并行等處理,方便了任務的異步邏輯組合。
1、CompletableFuture繼承關系
CompletableFuture主要繼承于Future接口及CompletionStage接口,Future為異步結果接口,CompletionStage定義了CompletableFuture異步處理及依賴接口。
2、Completion繼承關系
Completion為CompletableFuture的任務依賴堆,保存了當前CompletableFuture依賴的任務。其繼承于ForkJoinTask,主要繼承結構如下:
UniCompletion為基礎抽象類,其包含了任務的線程池信息、依賴任務及任務執行體。
2.1、Completion解析
abstract static class Completion extends ForkJoinTask<Void>
implements Runnable, AsynchronousCompletionTask {
//堆中的下個任務
volatile Completion next; // Treiber stack link
//執行被觸發的任務,返回需要傳播的依賴任務
abstract CompletableFuture<?> tryFire(int mode);
//任務是否可觸發
abstract boolean isLive();
public final void run() { tryFire(ASYNC); }
public final boolean exec() { tryFire(ASYNC); return true; }
public final Void getRawResult() { return null; }
public final void setRawResult(Void v) {}
}
2.2、UniCompletion解析
abstract static class UniCompletion<T,V> extends Completion {
//執行當前任務的線程池
Executor executor; // executor to use (null if none)
//當然依賴的任務
CompletableFuture<V> dep; // the dependent to complete
//當前任務的執行實體
CompletableFuture<T> src; // source for action
UniCompletion(Executor executor, CompletableFuture<V> dep,
CompletableFuture<T> src) {
this.executor = executor; this.dep = dep; this.src = src;
}
//若當前任務可執行,則返回true。若異步執行,則提交當前任務
final boolean claim() {
Executor e = executor;
if (compareAndSetForkJoinTaskTag((short)0, (short)1)) {
if (e == null)
return true;
executor = null; // disable
e.execute(this);
}
return false;
}
final boolean isLive() { return dep != null; }
}
2.3、BiCompletion解析
BiCompletion主要增加了一個任務。
abstract static class BiCompletion<T,U,V> extends UniCompletion<T,V> {
CompletableFuture<U> snd; // second source for action
BiCompletion(Executor executor, CompletableFuture<V> dep,
CompletableFuture<T> src, CompletableFuture<U> snd) {
super(executor, dep, src); this.snd = snd;
}
}
3、主要方法詳解
3.1、工廠方法創建CompletableFuture
CompletableFuture的工廠方法方便用戶創建及使用CompletableFuture。主要分為兩類,執行有返回值的任務(Callable)和無返回值的任務(Runnable)
//在線程池中異步執行一個有返回值的任務,返回結果封裝在CompletableFuture中,
//任務體為supplier中
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier) {
return asyncSupplyStage(asyncPool, supplier);
}
//在線程池中異步執行一個有返回值的任務,返回結果封裝在CompletableFuture中,
//顯式提供線程池executor
//任務體為supplier中
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier,
Executor executor) {
return asyncSupplyStage(screenExecutor(executor), supplier);
}
//在線程池中異步執行一個無返回值的任務,返回結果封裝在CompletableFuture中;
//任務體為supplier中
public static CompletableFuture<Void> runAsync(Runnable runnable) {
return asyncRunStage(asyncPool, runnable);
}
//在線程池中異步執行一個無返回值的任務,返回結果封裝在CompletableFuture中;
//顯式提供線程池executor
//任務體為supplier中
public static CompletableFuture<Void> runAsync(Runnable runnable,
Executor executor) {
return asyncRunStage(screenExecutor(executor), runnable);
}
//獲取一個已完成的CompletableFuture,并用value作為結果。
//任務體為supplier中
public static <U> CompletableFuture<U> completedFuture(U value) {
return new CompletableFuture<U>((value == null) ? NIL : value);
}
//執行有返回值的任務,主要是將任務封裝為一個AsyncSupply并交由線程池執行
static <U> CompletableFuture<U> asyncSupplyStage(Executor e,
Supplier<U> f) {
if (f == null) throw new NullPointerException();
CompletableFuture<U> d = new CompletableFuture<U>();
e.execute(new AsyncSupply<U>(d, f));
return d;
}
//執行無返回值的任務,主要是將任務封裝為一個AsyncRun并交由線程池執行
static CompletableFuture<Void> asyncRunStage(Executor e, Runnable f) {
if (f == null) throw new NullPointerException();
CompletableFuture<Void> d = new CompletableFuture<Void>();
e.execute(new AsyncRun(d, f));
return d;
}
AsyncSupply及AsyncRun實現:
//封裝的task,用于執行無返回值的任務
static final class AsyncRun extends ForkJoinTask<Void>
implements Runnable, AsynchronousCompletionTask {
//dep:當前任務的異步執行結果的Future;fn:當前任務的執行體,函數式編程
CompletableFuture<Void> dep; Runnable fn;
AsyncRun(CompletableFuture<Void> dep, Runnable fn) {
this.dep = dep; this.fn = fn;
}
public final Void getRawResult() { return null; }
public final void setRawResult(Void v) {}
public final boolean exec() { run(); return true; }
public void run() {
CompletableFuture<Void> d; Runnable f;
if ((d = dep) != null && (f = fn) != null) {
dep = null; fn = null;
//任務未執行結束?
if (d.result == null) {
try {
//執行任務
f.run();
//設置執行結果問null的AltResult
d.completeNull();
} catch (Throwable ex) {
//若異常則設置異常結果
d.completeThrowable(ex);
}
}
//傳播任務完成的消息,執行所有依賴此任務的其他任務,依賴任務存儲在棧中
d.postComplete();
}
}
}
//封裝的task,用于執行有返回值的任務
static final class AsyncSupply<T> extends ForkJoinTask<Void>
implements Runnable, AsynchronousCompletionTask {
//dep:當前任務的異步執行結果的Future;fn:當前任務的執行體,函數式編程
CompletableFuture<T> dep; Supplier<T> fn;
AsyncSupply(CompletableFuture<T> dep, Supplier<T> fn) {
this.dep = dep; this.fn = fn;
}
public final Void getRawResult() { return null; }
public final void setRawResult(Void v) {}
public final boolean exec() { run(); return true; }
public void run() {
CompletableFuture<T> d; Supplier<T> f;
if ((d = dep) != null && (f = fn) != null) {
dep = null; fn = null;
//任務未執行?
if (d.result == null) {
try {
//執行任務,并設置任務的執行結果
d.completeValue(f.get());
} catch (Throwable ex) {
//執行異常則設置異常結果
d.completeThrowable(ex);
}
}
//傳播任務完成的消息,執行所有依賴此任務的其他任務,依賴任務存儲在棧中
d.postComplete();
}
}
}
final void postComplete() {
//f:當前CompletableFuture
CompletableFuture<?> f = this; Completion h;
//當前CompletableFuture的依賴棧不為空;
//或當f的stack為空時,使f重新指向當前的CompletableFuture,繼續后面的結點
//一次執行一個依賴任務的處理
while ((h = f.stack) != null ||
(f != this && (h = (f = this).stack) != null)) {
CompletableFuture<?> d; Completion t;
//更新堆的頭節點下個節點
if (f.casStack(h, t = h.next)) {
//頭結點的下個節點不為空?
if (t != null) {
// 如果f不是當前CompletableFuture,則將它的頭結點壓入到當前CompletableFuture的stack中,
// 使樹形結構變成鏈表結構,避免遞歸層次過深
if (f != this) {
// 繼續下一個結點,批量壓入到當前棧中
pushStack(h);
continue;
}
// 如果是當前CompletableFuture, 解除頭節點與棧的聯系
h.next = null; // detach
}
// 調用頭節點的tryFire()方法,該方法可看作Completion的鉤子方法,
// 執行完邏輯后,會向后傳播的
f = (d = h.tryFire(NESTED)) == null ? this : d;
}
}
}
3.2、獲取CompletableFuture的異步結果
CompletableFuture繼承于Future,實現了獲取異步執行結果的一些方法。
//異步任務是否已經完成
public boolean isDone() {
return result != null;
}
//獲取異步的執行結果,若任務未執行完成,則阻塞等待;
//若執行結果中有異常,則直接拋出異常
public T get() throws InterruptedException, ExecutionException {
Object r;
return reportGet((r = result) == null ? waitingGet(true) : r);
}
//在給定的超時時間內獲取異步結果
public T get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException {
Object r;
long nanos = unit.toNanos(timeout);
return reportGet((r = result) == null ? timedGet(nanos) : r);
}
//阻塞等待任務執行完成并獲取任務結果
public T join() {
Object r;
return reportJoin((r = result) == null ? waitingGet(false) : r);
}
//立即獲取執行結果,若任務還未執行完成則直接使用給定的默認值,否則返回結果;
//若執行結果中有異常,則直接拋出異常
public T getNow(T valueIfAbsent) {
Object r;
return ((r = result) == null) ? valueIfAbsent : reportJoin(r);
}
//獲取異步執行結果,若結果有異常,則直接拋出異常
private static <T> T reportJoin(Object r) {
if (r instanceof AltResult) {
Throwable x;
if ((x = ((AltResult)r).ex) == null)
return null;
if (x instanceof CancellationException)
throw (CancellationException)x;
if (x instanceof CompletionException)
throw (CompletionException)x;
throw new CompletionException(x);
}
@SuppressWarnings("unchecked") T t = (T) r;
return t;
}
3.3、計算結果完成后的相關處理(UniWhenComplete)
當CompletableFuture計算結果完成時,我們需要對結果進行處理,或者當CompletableFuture產生異常的時候需要對異常進行處理。方法中以Async結尾的會在新的線程池中執行,沒有Async結尾的會在之前的CompletableFuture執行的線程中執行。
//當完成后同步執行action
public CompletableFuture<T> whenComplete(
BiConsumer<? super T, ? super Throwable> action) {
return uniWhenCompleteStage(null, action);
}
//完成后異步執行action
public CompletableFuture<T> whenCompleteAsync(
BiConsumer<? super T, ? super Throwable> action) {
return uniWhenCompleteStage(asyncPool, action);
}
//完成后異步執行action,帶線程池
public CompletableFuture<T> whenCompleteAsync(
BiConsumer<? super T, ? super Throwable> action, Executor executor) {
return uniWhenCompleteStage(screenExecutor(executor), action);
}
//異常后執行
public CompletableFuture<T> exceptionally(
Function<Throwable, ? extends T> fn) {
return uniExceptionallyStage(fn);
}
uniWhenCompleteStage相關處理:
private CompletableFuture<T> uniWhenCompleteStage(
Executor e, BiConsumer<? super T, ? super Throwable> f) {
if (f == null) throw new NullPointerException();
CompletableFuture<T> d = new CompletableFuture<T>();
//若線程池為空,則調用uniWhenComplete方法進行任務狀態判斷及處理
//若線程池非空,則構建UniWhenComplete任務并將任務入隊,同時調用tryFire()進行同步處理
if (e != null || !d.uniWhenComplete(this, f, null)) {
UniWhenComplete<T> c = new UniWhenComplete<T>(e, d, this, f);
push(c);
//調用鉤子方法,對任務進行處理并處理相關依賴
c.tryFire(SYNC);
}
return d;
}
final boolean uniWhenComplete(CompletableFuture<T> a,
BiConsumer<? super T,? super Throwable> f,
UniWhenComplete<T> c) {
Object r; T t; Throwable x = null;
//檢查依賴的任務是否完成,未完成則直接返回false
if (a == null || (r = a.result) == null || f == null)
return false;
//當前任務未完成?
if (result == null) {
try {
//uniWhenComplete中所有c都為空,無需考慮
if (c != null && !c.claim())
return false;
//判斷執行結果是否異常
if (r instanceof AltResult) {
x = ((AltResult)r).ex;
t = null;
} else {
@SuppressWarnings("unchecked") T tr = (T) r;
t = tr;
}
//執行任務
f.accept(t, x);
if (x == null) {
internalComplete(r);
return true;
}
} catch (Throwable ex) {
if (x == null)
x = ex;
}
//設置異常結果
completeThrowable(x, r);
}
return true;
}
//whenComplete任務的封裝
static final class UniWhenComplete<T> extends UniCompletion<T,T> {
BiConsumer<? super T, ? super Throwable> fn;
UniWhenComplete(Executor executor, CompletableFuture<T> dep,
CompletableFuture<T> src,
BiConsumer<? super T, ? super Throwable> fn) {
super(executor, dep, src); this.fn = fn;
}
final CompletableFuture<T> tryFire(int mode) {
CompletableFuture<T> d; CompletableFuture<T> a;
if ((d = dep) == null ||
!d.uniWhenComplete(a = src, fn, mode > 0 ? null : this))
return null;
dep = null; src = null; fn = null;
return d.postFire(a, mode);
}
}
3.4、計算結果完成時的轉換處理(thenApply)
計算結果完成時的轉換的處理會將上個計算結果轉換為當前任務的輸入參數。Async結尾的方法由原來的線程計算,以Async結尾的方法由默認的線程池ForkJoinPool.commonPool()或者指定的線程池executor運行。
//
public <U> CompletableFuture<U> thenApply(
Function<? super T,? extends U> fn) {
return uniApplyStage(null, fn);
}
public <U> CompletableFuture<U> thenApplyAsync(
Function<? super T,? extends U> fn) {
return uniApplyStage(asyncPool, fn);
}
public <U> CompletableFuture<U> thenApplyAsync(
Function<? super T,? extends U> fn, Executor executor) {
return uniApplyStage(screenExecutor(executor), fn);
}
uniApplyStage()處理解析:
private <V> CompletableFuture<V> uniApplyStage(
Executor e, Function<? super T,? extends V> f) {
if (f == null) throw new NullPointerException();
CompletableFuture<V> d = new CompletableFuture<V>();
//當線程池為空時,直接調用uniApply對任務進行處理
//當線程池非空時,將任務加入堆棧,并調用tryFire對任務進行處理
if (e != null || !d.uniApply(this, f, null)) {
UniApply<T,V> c = new UniApply<T,V>(e, d, this, f);
push(c);
c.tryFire(SYNC);
}
return d;
}
final <S> boolean uniApply(CompletableFuture<S> a,
Function<? super S,? extends T> f,
UniApply<S,T> c) {
Object r; Throwable x;
//依賴任務未完成?直接返回false
if (a == null || (r = a.result) == null || f == null)
return false;
//當前任務未完成?
tryComplete: if (result == null) {
//依賴的任務處理異常?則設置當前任務異常結果
if (r instanceof AltResult) {
if ((x = ((AltResult)r).ex) != null) {
completeThrowable(x, r);
break tryComplete;
}
r = null;
}
try {
//thenApply中所有c都為空,無需考慮
if (c != null && !c.claim())
return false;
@SuppressWarnings("unchecked") S s = (S) r;
//執行任務并設置任務結果
completeValue(f.apply(s));
} catch (Throwable ex) {
//執行任務異常則設置異常結果
completeThrowable(ex);
}
}
return true;
}
//thenApply任務的封裝
static final class UniApply<T,V> extends UniCompletion<T,V> {
Function<? super T,? extends V> fn;
UniApply(Executor executor, CompletableFuture<V> dep,
CompletableFuture<T> src,
Function<? super T,? extends V> fn) {
super(executor, dep, src); this.fn = fn;
}
final CompletableFuture<V> tryFire(int mode) {
CompletableFuture<V> d; CompletableFuture<T> a;
if ((d = dep) == null ||
!d.uniApply(a = src, fn, mode > 0 ? null : this))
return null;
dep = null; src = null; fn = null;
return d.postFire(a, mode);
}
}
3.5、計算結果完成時的消費處理(thenAccept)
計算結果完成時的消費的處理是將上一步任務處理的結果作為本次任務處理的輸入參數,并且thenAccept的處理只會對上一步的結果進行處理,而不會返回任何處理結果。
public CompletableFuture<Void> thenAccept(Consumer<? super T> action) {
return uniAcceptStage(null, action);
}
public CompletableFuture<Void> thenAcceptAsync(Consumer<? super T> action) {
return uniAcceptStage(asyncPool, action);
}
public CompletableFuture<Void> thenAcceptAsync(Consumer<? super T> action,
Executor executor) {
return uniAcceptStage(screenExecutor(executor), action);
}
uniAcceptStage()的處理流程:
private CompletableFuture<Void> uniAcceptStage(Executor e,
Consumer<? super T> f) {
if (f == null) throw new NullPointerException();
CompletableFuture<Void> d = new CompletableFuture<Void>();
//線程池為空則調用uniAccept同步處理任務;
//線程池非空則將任務封裝為UniAccept并推入堆棧,同時調用tryFire()進行任務處理
if (e != null || !d.uniAccept(this, f, null)) {
UniAccept<T> c = new UniAccept<T>(e, d, this, f);
push(c);
c.tryFire(SYNC);
}
return d;
}
final <S> boolean uniAccept(CompletableFuture<S> a,
Consumer<? super S> f, UniAccept<S> c) {
Object r; Throwable x;
//依賴任務未完成?直接返回false
if (a == null || (r = a.result) == null || f == null)
return false;
//當前任務未完成?
tryComplete: if (result == null) {
//依賴任務結果異常,則設置當前的異常結果
if (r instanceof AltResult) {
if ((x = ((AltResult)r).ex) != null) {
completeThrowable(x, r);
break tryComplete;
}
r = null;
}
try {
//uniAccept中c全部為null,無需考慮
if (c != null && !c.claim())
return false;
@SuppressWarnings("unchecked") S s = (S) r;
//執行當前任務
f.accept(s);
//設置空結果
completeNull();
} catch (Throwable ex) {
//執行異常則設置異常結果
completeThrowable(ex);
}
}
return true;
}
//uniAccept的任務封裝
static final class UniAccept<T> extends UniCompletion<T,Void> {
Consumer<? super T> fn;
UniAccept(Executor executor, CompletableFuture<Void> dep,
CompletableFuture<T> src, Consumer<? super T> fn) {
super(executor, dep, src); this.fn = fn;
}
final CompletableFuture<Void> tryFire(int mode) {
CompletableFuture<Void> d; CompletableFuture<T> a;
if ((d = dep) == null ||
!d.uniAccept(a = src, fn, mode > 0 ? null : this))
return null;
dep = null; src = null; fn = null;
return d.postFire(a, mode);
}
}
3.6、多個結果完成時消費(thenAcceptBoth、runAfterBoth)
多個結果完成時處理會等待當前結果CompletableFuture及依賴的other完成時執行action,thenAcceptBoth會將依賴的當前CompletableFuture及other的執行結果作為action的輸入參數。
runAfterBoth則只等待兩個依賴的任務執行完成再執行。
public <U> CompletableFuture<Void> thenAcceptBoth(
CompletionStage<? extends U> other,
BiConsumer<? super T, ? super U> action) {
return biAcceptStage(null, other, action);
}
public <U> CompletableFuture<Void> thenAcceptBothAsync(
CompletionStage<? extends U> other,
BiConsumer<? super T, ? super U> action) {
return biAcceptStage(asyncPool, other, action);
}
public <U> CompletableFuture<Void> thenAcceptBothAsync(
CompletionStage<? extends U> other,
BiConsumer<? super T, ? super U> action, Executor executor) {
return biAcceptStage(screenExecutor(executor), other, action);
}
public CompletableFuture<Void> runAfterBoth(CompletionStage<?> other,
Runnable action) {
return biRunStage(null, other, action);
}
public CompletableFuture<Void> runAfterBothAsync(CompletionStage<?> other,
Runnable action) {
return biRunStage(asyncPool, other, action);
}
public CompletableFuture<Void> runAfterBothAsync(CompletionStage<?> other,
Runnable action,
Executor executor) {
return biRunStage(screenExecutor(executor), other, action);
}
biAcceptStage()及biRunStage()的處理流程基本相同,不同點為biAcceptStage()會將依賴的兩個任務作為執行處理的入參,而biRunStage()不會。
以下是biAcceptStage()的處理流程:
//處理thenAcceptBoth類型的任務
//e:線程池;
//o:依賴的一個任務
//f:具體執行邏輯,會將當前CompletableFuture及o的執行結果作為輸入
private <U> CompletableFuture<Void> biAcceptStage(
Executor e, CompletionStage<U> o,
BiConsumer<? super T,? super U> f) {
CompletableFuture<U> b;
if (f == null || (b = o.toCompletableFuture()) == null)
throw new NullPointerException();
CompletableFuture<Void> d = new CompletableFuture<Void>();
//線程池為空時,調用biAccept()同步執行處理
//線程池非空,則將任務封裝為BiAccept并推入堆棧,調用tryFire()進行任務處理
if (e != null || !d.biAccept(this, b, f, null)) {
BiAccept<T,U> c = new BiAccept<T,U>(e, d, this, b, f);
bipush(b, c);
c.tryFire(SYNC);
}
return d;
}
//任務的同步處理
//a,b:依賴的任務
//f:具體執行邏輯
//c:為空,無需考慮
final <R,S> boolean biAccept(CompletableFuture<R> a,
CompletableFuture<S> b,
BiConsumer<? super R,? super S> f,
BiAccept<R,S> c) {
Object r, s; Throwable x;
//判斷依賴的任務a,b是否執行完畢
if (a == null || (r = a.result) == null ||
b == null || (s = b.result) == null || f == null)
return false;
//當前任務未執行完成?
tryComplete: if (result == null) {
//若a或b任務執行有異常,則設置當前任務的異常結果
if (r instanceof AltResult) {
if ((x = ((AltResult)r).ex) != null) {
completeThrowable(x, r);
break tryComplete;
}
r = null;
}
if (s instanceof AltResult) {
if ((x = ((AltResult)s).ex) != null) {
completeThrowable(x, s);
break tryComplete;
}
s = null;
}
try {
if (c != null && !c.claim())
return false;
@SuppressWarnings("unchecked") R rr = (R) r;
@SuppressWarnings("unchecked") S ss = (S) s;
//執行任務,并將a,b任務的執行結果作為參數輸入
f.accept(rr, ss);
//設置返回結果為null
completeNull();
} catch (Throwable ex) {
//任務執行異常則設置異常結果
completeThrowable(ex);
}
}
return true;
}
//thenAcceptBoth類型任務的封裝
static final class BiAccept<T,U> extends BiCompletion<T,U,Void> {
BiConsumer<? super T,? super U> fn;
BiAccept(Executor executor, CompletableFuture<Void> dep,
CompletableFuture<T> src, CompletableFuture<U> snd,
BiConsumer<? super T,? super U> fn) {
super(executor, dep, src, snd); this.fn = fn;
}
final CompletableFuture<Void> tryFire(int mode) {
CompletableFuture<Void> d;
CompletableFuture<T> a;
CompletableFuture<U> b;
if ((d = dep) == null ||
!d.biAccept(a = src, b = snd, fn, mode > 0 ? null : this))
return null;
dep = null; src = null; snd = null; fn = null;
return d.postFire(a, b, mode);
}
}
3.7、某個結果完成時消費(applyToEither、acceptEither,runAfterEither)
applyToEither及acceptEither會將兩個結果中任意一個的執行結果作為當前執行的輸入參數,而applyToEither會返回執行結果,acceptEither則返回空的執行結果。runAfterEither則不會將依賴的執行結果作為參數,其只是當依賴的任意一個任務完成時進行處理,并返回空的執行結果。
public <U> CompletableFuture<U> applyToEither(
CompletionStage<? extends T> other, Function<? super T, U> fn) {
return orApplyStage(null, other, fn);
}
public <U> CompletableFuture<U> applyToEitherAsync(
CompletionStage<? extends T> other, Function<? super T, U> fn) {
return orApplyStage(asyncPool, other, fn);
}
public <U> CompletableFuture<U> applyToEitherAsync(
CompletionStage<? extends T> other, Function<? super T, U> fn,
Executor executor) {
return orApplyStage(screenExecutor(executor), other, fn);
}
public CompletableFuture<Void> acceptEither(
CompletionStage<? extends T> other, Consumer<? super T> action) {
return orAcceptStage(null, other, action);
}
public CompletableFuture<Void> acceptEitherAsync(
CompletionStage<? extends T> other, Consumer<? super T> action) {
return orAcceptStage(asyncPool, other, action);
}
public CompletableFuture<Void> acceptEitherAsync(
CompletionStage<? extends T> other, Consumer<? super T> action,
Executor executor) {
return orAcceptStage(screenExecutor(executor), other, action);
}
public CompletableFuture<Void> runAfterEither(CompletionStage<?> other,
Runnable action) {
return orRunStage(null, other, action);
}
public CompletableFuture<Void> runAfterEitherAsync(CompletionStage<?> other,
Runnable action) {
return orRunStage(asyncPool, other, action);
}
public CompletableFuture<Void> runAfterEitherAsync(CompletionStage<?> other,
Runnable action,
Executor executor) {
return orRunStage(screenExecutor(executor), other, action);
}
orApplyStage()、orAcceptStage()、orRunStage()的處理基本相同。以下以orApplyStage()為例來分析其處理流程:
private <U extends T,V> CompletableFuture<V> orApplyStage(
Executor e, CompletionStage<U> o,
Function<? super T, ? extends V> f) {
CompletableFuture<U> b;
if (f == null || (b = o.toCompletableFuture()) == null)
throw new NullPointerException();
CompletableFuture<V> d = new CompletableFuture<V>();
//若線程池為空,則調用orApply()進行任務的同步處理
//若線程池非空,則將依賴及處理封裝為OrApply并推入堆棧,然后調用tryFire()進行任務處理
if (e != null || !d.orApply(this, b, f, null)) {
OrApply<T,U,V> c = new OrApply<T,U,V>(e, d, this, b, f);
orpush(b, c);
c.tryFire(SYNC);
}
return d;
}
final <R,S extends R> boolean orApply(CompletableFuture<R> a,
CompletableFuture<S> b,
Function<? super R, ? extends T> f,
OrApply<R,S,T> c) {
Object r; Throwable x;
//依賴的任務a,b都未執行完成?
if (a == null || b == null ||
((r = a.result) == null && (r = b.result) == null) || f == null)
return false;
//當前任務未完成?
tryComplete: if (result == null) {
try {
if (c != null && !c.claim())
return false;
//依賴任務處理異常,設置當前異常結果
if (r instanceof AltResult) {
if ((x = ((AltResult)r).ex) != null) {
completeThrowable(x, r);
break tryComplete;
}
r = null;
}
@SuppressWarnings("unchecked") R rr = (R) r;
//進行任務處理,并設置處理結果
completeValue(f.apply(rr));
} catch (Throwable ex) {
completeThrowable(ex);
}
}
return true;
}
//orApplyStage的任務封裝。
static final class OrApply<T,U extends T,V> extends BiCompletion<T,U,V> {
Function<? super T,? extends V> fn;
OrApply(Executor executor, CompletableFuture<V> dep,
CompletableFuture<T> src,
CompletableFuture<U> snd,
Function<? super T,? extends V> fn) {
super(executor, dep, src, snd); this.fn = fn;
}
final CompletableFuture<V> tryFire(int mode) {
CompletableFuture<V> d;
CompletableFuture<T> a;
CompletableFuture<U> b;
if ((d = dep) == null ||
!d.orApply(a = src, b = snd, fn, mode > 0 ? null : this))
return null;
dep = null; src = null; snd = null; fn = null;
return d.postFire(a, b, mode);
}
}
3.8、異步結果的組合處理(thenCompose)
thenCompose會連接兩個CompletableFuture,其處理是當前CompletableFuture完成時將結果作為fn處理的入參進行處理。
public <U> CompletableFuture<U> thenCompose(
Function<? super T, ? extends CompletionStage<U>> fn) {
return uniComposeStage(null, fn);
}
public <U> CompletableFuture<U> thenComposeAsync(
Function<? super T, ? extends CompletionStage<U>> fn) {
return uniComposeStage(asyncPool, fn);
}
public <U> CompletableFuture<U> thenComposeAsync(
Function<? super T, ? extends CompletionStage<U>> fn,
Executor executor) {
return uniComposeStage(screenExecutor(executor), fn);
}
uniComposeStage()處理流程:
private <V> CompletableFuture<V> uniComposeStage(
Executor e, Function<? super T, ? extends CompletionStage<V>> f) {
if (f == null) throw new NullPointerException();
Object r; Throwable x;
//無線程池,且當前任務處理完成
if (e == null && (r = result) != null) {
//若當前處理結果異常,則直接返回異常結果
if (r instanceof AltResult) {
if ((x = ((AltResult)r).ex) != null) {
return new CompletableFuture<V>(encodeThrowable(x, r));
}
r = null;
}
try {
//將當前處理結果作為f的輸入,并執行f處理
@SuppressWarnings("unchecked") T t = (T) r;
CompletableFuture<V> g = f.apply(t).toCompletableFuture();
Object s = g.result;
//f處理完成?則直接返回處理結果
//未完成則封裝處理并將任務入棧
if (s != null)
return new CompletableFuture<V>(encodeRelay(s));
CompletableFuture<V> d = new CompletableFuture<V>();
UniRelay<V> copy = new UniRelay<V>(d, g);
g.push(copy);
copy.tryFire(SYNC);
return d;
} catch (Throwable ex) {
return new CompletableFuture<V>(encodeThrowable(ex));
}
}
//當前任務未處理完成,則封裝當前任務及依賴并入棧
CompletableFuture<V> d = new CompletableFuture<V>();
UniCompose<T,V> c = new UniCompose<T,V>(e, d, this, f);
push(c);
c.tryFire(SYNC);
return d;
}
3.9、等待多個執行結果完成
//所有任務都執行完畢
public static CompletableFuture<Void> allOf(CompletableFuture<?>... cfs) {
return andTree(cfs, 0, cfs.length - 1);
}
//某個任務執行完畢
public static CompletableFuture<Object> anyOf(CompletableFuture<?>... cfs) {
return orTree(cfs, 0, cfs.length - 1);
}
static CompletableFuture<Object> orTree(CompletableFuture<?>[] cfs,
int lo, int hi) {
CompletableFuture<Object> d = new CompletableFuture<Object>();
//遞歸將任務進行遍歷,若某個任務已經完成,則直接設置結果為已完成任務的結果
if (lo <= hi) {
CompletableFuture<?> a, b;
int mid = (lo + hi) >>> 1;
if ((a = (lo == mid ? cfs[lo] :
orTree(cfs, lo, mid))) == null ||
(b = (lo == hi ? a : (hi == mid+1) ? cfs[hi] :
orTree(cfs, mid+1, hi))) == null)
throw new NullPointerException();
if (!d.orRelay(a, b)) {
OrRelay<?,?> c = new OrRelay<>(d, a, b);
a.orpush(b, c);
c.tryFire(SYNC);
}
}
return d;
}
3.10、對異步結果進行處理(handle)
handle()主要獲取當前任務的執行結果,并將其作為fn函數的輸入參數,并接執行結果設置為返回的CompletableFuture的結果。
public <U> CompletableFuture<U> handle(
BiFunction<? super T, Throwable, ? extends U> fn) {
return uniHandleStage(null, fn);
}
public <U> CompletableFuture<U> handleAsync(
BiFunction<? super T, Throwable, ? extends U> fn) {
return uniHandleStage(asyncPool, fn);
}
public <U> CompletableFuture<U> handleAsync(
BiFunction<? super T, Throwable, ? extends U> fn, Executor executor) {
return uniHandleStage(screenExecutor(executor), fn);
}
uniHandleStage()的處理流程:
private <V> CompletableFuture<V> uniHandleStage(
Executor e, BiFunction<? super T, Throwable, ? extends V> f) {
if (f == null) throw new NullPointerException();
CompletableFuture<V> d = new CompletableFuture<V>();
//若線程池為空,則直接調用uniHandle同步執行任務,
//否則將任務及依賴信息封裝為UniHandle入棧,然后調用tryFire()進行任務處理
if (e != null || !d.uniHandle(this, f, null)) {
UniHandle<T,V> c = new UniHandle<T,V>(e, d, this, f);
push(c);
c.tryFire(SYNC);
}
return d;
}
final <S> boolean uniHandle(CompletableFuture<S> a,
BiFunction<? super S, Throwable, ? extends T> f,
UniHandle<S,T> c) {
Object r; S s; Throwable x;
//依賴任務未完成?返回false
if (a == null || (r = a.result) == null || f == null)
return false;
//當前結果為完成?
if (result == null) {
try {
if (c != null && !c.claim())
return false;
//依賴執行結果異常?則設置當前結果為異常結果
if (r instanceof AltResult) {
x = ((AltResult)r).ex;
s = null;
} else {
x = null;
@SuppressWarnings("unchecked") S ss = (S) r;
s = ss;
}
//將依賴的結果作為當前函數的輸入參數,并執行函數,設置當前執行結果
completeValue(f.apply(s, x));
} catch (Throwable ex) {
completeThrowable(ex);
}
}
return true;
}