简单解析
首先尝试不看源码情况下讲清楚CompletableFuture. CompletableFuture主要由两个类组成,CompletableFuture与Completion,其中Completion有非常多实现类,像是一元的UniCompletion,二元的BiCompletion等,整体逻辑都是差不多的,这里以基于一元UniCompletion的UniApply来讲解.
cf1是被观察者,当cf1 result为null时候,这时候执行thenApply,会生成一个UniApply对象加入到cf1 stack中,当cf1 result有值以后,会执行stack中每一个Completion.
源码解析
uniApplyStage
//执行thenApply后调用此函数
private <V> CompletableFuture<V> uniApplyStage(
Executor e, Function<? super T,? extends V> f) {
if (f == null) throw new NullPointerException();
Object r;
//当前cf result不为空的话,不需要入栈,直接执行
if ((r = result) != null)
return uniApplyNow(r, e, f);
CompletableFuture<V> d = newIncompleteFuture();
//构建一个UniApply,入栈到当前cf的stack
unipush(new UniApply<T,V>(e, d, this, f));
return d;
}
postComplete
public boolean complete(T value) {
//cas方式赋值result
boolean triggered = completeValue(value);
postComplete();
return triggered;
}
final void postComplete() {
CompletableFuture<?> f = this; Completion h;
while ((h = f.stack) != null ||
(f != this && (h = (f = this).stack) != null)) {
CompletableFuture<?> d; Completion t;
//f的stack由h替换成h.next
if (STACK.compareAndSet(f, h, t = h.next)) {
if (t