// tryFire()
// 1、(d = dep) == null : 若上一阶段是异步的,completion放入堆栈后,上一阶段完成了,然后此线程
// 执行tryFire() 就可能和上一阶段执行的线程产生竞争(上一阶段的线程调用postCompletion()方法,执行
// 该completion的 tryFire()方法)。因此,此时dep可能为 null。
// 2、如果将 completion放入上一阶段的堆栈时,刚好上一个阶段已经完成了,则压入堆栈会失败,但是由于上一阶段
// 已经完成了,因此d.uniApply() 一定可以成功调用
public class CompletableFuture<T> implements Future<T>, CompletionStage<T> {
/*
* 概述
* Overview:
*
* CompletableFuture可能有依赖的完成动作,收集在一个链接的堆栈中。
* A CompletableFuture may have dependent completion actions,
* collected in a linked stack. It atomically completes by CASing
* 通过CAS一个result字段原子地完成,然后弹出并运行那些操作。
* a result field, and then pops off and runs those actions. This
* 这适用于普通和异常结果、同步和异步操作、二进制触发器以及各种形式的完成。
* applies across normal vs exceptional outcomes, sync vs async
* actions, binary triggers, and various forms of completions.
*
* 非空的result字段(通过CAS设置)表示完成。
* Non-nullness of field result (set via CAS) indicates done. An
* AltResult用于包装null作为一个结果,并保留异常。
* AltResult is used to box null as a result, as well as to hold
* 使用单个字段使完成检测和触发变得简单。
* exceptions. Using a single field makes completion simple to
* 编码和解码很简单,但是增加了捕获异常和将异常与目标关联的复杂性。
* detect and trigger. Encoding and decoding is straightforward
* but adds to the sprawl of trapping and associating exceptions
* 次要的简化依赖于(静态)NIL(包装null结果)是唯一一个带有空异常字段的AltResult,
* 因此我们通常不需要显式比较。
* with targets. Minor simplifications rely on (static) NIL (to
* box null results) being the only AltResult with a null
* exception field, so we don't usually need explicit comparisons.
* 即使未检查某些泛型强制类型转换(请参阅SuppressWarnings注释),但即使检查了它们,
* 它们仍然是适当的。
* Even though some of the generics casts are unchecked (see
* SuppressWarnings annotations), they are placed to be
* appropriate even if checked.
*
* 依赖的操作由Completion对象表示,连接成Treiber堆栈,它们是由字段“stack”为首的。
* Dependent actions are represented by Completion objects linked
* as Treiber stacks headed by field "stack". There are Completion
* 每种操作都有Completion类,分为单输入(UniCompletion)、双输入(BiCompletion)、
* 投影(使用两个输入中的任何一个(而不是两个)的BiCompletions)、共享(CoCompletion,
* 由两个源中的第二个使用)、零输入源操作和释放等待者的Signallers。
* classes for each kind of action, grouped into single-input
* (UniCompletion), two-input (BiCompletion), projected
* (BiCompletions using either (not both) of two inputs), shared
* (CoCompletion, used by the second of two sources), zero-input
* source actions, and Signallers that unblock waiters. Class
* 类Completion扩展了ForkJoinTask来支持异步执行(没有增加空间开销,因为我们利用
* 它的“标签”方法来维护声明)。
* Completion extends ForkJoinTask to enable async execution
* (adding no space overhead because we exploit its "tag" methods
* 它也被声明为Runnable,以允许使用任意的执行器。
* to maintain claims). It is also declared as Runnable to allow
* usage with arbitrary executors.
*
* 对各种CompletionStage的支持依赖于一个单独的类,以及两个CompletableFuture方法:
* Support for each kind of CompletionStage relies on a separate
* class, along with two CompletableFuture methods:
*
* 一个名为X的Completion类,它对应于函数,以“Uni”、“Bi”或“or”为前缀。
* * A Completion class with name X corresponding to function,
* prefaced with "Uni", "Bi", or "Or". Each class contains
* 每个类包含源、操作和依赖项的字段。
* fields for source(s), actions, and dependent. They are
* 它们非常相似,只是在底层的功能形式上不同。
* boringly similar, differing from others only with respect to
* underlying functional forms. We do this so that users don't
* 我们这样做是为了让用户在通常情况下不会遇到适配器层。
* encounter layers of adaptors in common usages. We also
* 我们还包括不与用户方法对应的“Relay”类/方法;他们将结果从一个阶段复制到另一个阶段。
* include "Relay" classes/methods that don't correspond to user
* methods; they copy results from one stage to another.
*
* 布尔型CompletableFuture方法x(…)(例如uniApply)获取所有需要的参数来检查一个动作是否可
* 以触发,然后运行这个动作或者通过执行它的Completion参数来安排它的异步执行(如果存在的话)。
* * Boolean CompletableFuture method x(...) (for example
* uniApply) takes all of the arguments needed to check that an
* action is triggerable, and then either runs the action or
* arranges its async execution by executing its Completion
* 如果已知是完成的,则该方法返回true。
* argument, if present. The method returns true if known to be
* complete.
*
* Completion方法tryFire(int mode)调用关联的x方法及其持有的参数,并在成功时清除。
* * Completion method tryFire(int mode) invokes the associated x
* method with its held arguments, and on success cleans up.
* mode参数允许tryFire被调用两次(SYNC,然后ASYNC);第一次用于在安排执行时
* 筛选和捕获异常,第二次从任务中调用。
* The mode argument allows tryFire to be called twice (SYNC,
* then ASYNC); the first to screen and trap exceptions while
* arranging to execute, and the second when called from a
* (有几个类不使用异步,所以采用稍微不同的形式。)
* task. (A few classes are not used async so take slightly
* 如果另一个线程已经声明了claim()回调,则会取消函数调用。
* different forms.) The claim() callback suppresses function
* invocation if already claimed by another thread.
*
* 从CompletableFuture x的公共stage方法调用xStage(…)。
* * CompletableFuture method xStage(...) is called from a public
* stage method of CompletableFuture x. It screens user
* 它筛选用户参数并调用 和/或 创建stage对象。
* arguments and invokes and/or creates the stage object. If
* 如果不是异步,并且x已经完成,则立即运行操作。
* not async and x is already complete, the action is run
* 否则会创建一个Completion c,推入x的堆栈(除非完成),并通过c. tryfire启动或触发它。
* immediately. Otherwise a Completion c is created, pushed to
* x's stack (unless done), and started or triggered via
* 这可能也包括了x在push的时候完成的竞争。
* c.tryFire. This also covers races possible if x completes
* 具有两个输入的类(例如BiApply)在push动作时处理两个输入之间的竞争。
* while pushing. Classes with two inputs (for example BiApply)
* deal with races across both while pushing actions. The
* 第二个completion是指向第一个的CoCompletion,共享,这样最多只能执行一个动作。
* second completion is a CoCompletion pointing to the first,
* shared so that at most one performs the action. The
* 多重性方法allOf和anyOf将这两种方法进行配对,形成completions树。
* multiple-arity methods allOf and anyOf do this pairwise to
* form trees of completions.
*
* 注意,方法的泛型类型参数根据“this”是源、依赖项还是completion而不同。
* Note that the generic type parameters of methods vary according
* to whether "this" is a source, dependent, or completion.
*
* 方法postComplete在完成时被调用,除非目标被保证是不可观察的(例如。,尚未返回或链接)。
* Method postComplete is called upon completion unless the target
* is guaranteed not to be observable (i.e., not yet returned or
* 多个线程可以调用postComplete,它原子地弹出每个依赖的操作,并尝试通过
* NESTED模式的tryFire方法触发它。
* linked). Multiple threads can call postComplete, which
* atomically pops each dependent action, and tries to trigger it
* via method tryFire, in NESTED mode. Triggering can propagate
* 触发可以递归地传播,所以NESTED模式返回它完成的依赖项(如果存在的话),
* 以便调用者进一步处理(参见方法postFire)。
* recursively, so NESTED mode returns its completed dependent (if
* one exists) for further processing by its caller (see method
* postFire).
*
* 阻塞方法get()和join()依赖于Signaller Completions来唤醒等待的线程。
* Blocking methods get() and join() rely on Signaller Completions
* that wake up waiting threads. The mechanics are similar to
* 该机制类似于Treiber堆栈等待节点,用于FutureTask、Phaser和SynchronousQueue。
* 有关算法细节,请参阅他们的内部文档。
* Treiber stack wait-nodes used in FutureTask, Phaser, and
* SynchronousQueue. See their internal documentation for
* algorithmic details.
*
* 没有预防措施,随着Completions链的建立,每个都指向其源头,那么CompletableFutures
* 将容易出现垃圾堆积。
* Without precautions, CompletableFutures would be prone to
* garbage accumulation as chains of Completions build up, each
* pointing back to its sources. So we null out fields as soon as
* 因此,我们会尽可能快地空出字段(特别是方法complete.detach)。
* possible (see especially method Completion.detach). The
* 无论如何,筛选检查都需要无害地忽略null参数,这些参数可能是在线程设置字段为null
* 的竞争中获得的。
* screening checks needed anyway harmlessly ignore null arguments
* that may have been obtained during races with threads nulling
* 我们还尝试从可能永远不会弹出的堆栈中取消已触发的Completions链接(参见方法postFire)。
* out fields. We also try to unlink fired Completions from
* stacks that might never be popped (see method postFire).
* 不需要将Completion字段声明为final或volatile,因为它们只有在安全发布时才对其他线程可见。
* Completion fields need not be declared as final or volatile
* because they are only visible to other threads upon safe
* publication.
*/
// 要么是结果,要么是AltResult
volatile Object result; // Either the result or boxed AltResult
// 依赖操作的Treiber堆栈顶部
volatile Completion stack; // Top of Treiber stack of dependent actions
final boolean internalComplete(Object r) { // CAS from null to r
// 使用CAS把result 从null 改成r
return UNSAFE.compareAndSwapObject(this, RESULT, null, r);
}
// 使用CAS修改stack 的值。
final boolean casStack(Completion cmp, Completion val) {
return UNSAFE.compareAndSwapObject(this, STACK, cmp, val);
}
// 如果成功将c压入堆栈,则返回true。
/** Returns true if successfully pushed c onto stack. */
final boolean tryPushStack(Completion c) {
Completion h = stack;
// 设置c 的next 值为h (不需要立即可见,因为下一步使用CAS就能保证可见性)
lazySetNext(c, h);
// 设置 stack为 c
return UNSAFE.compareAndSwapObject(this, STACK, h, c);
}
// 无条件地将c压入堆栈,必要时重试
/** Unconditionally pushes c onto stack, retrying if necessary. */
final void pushStack(Completion c) {
do {} while (!tryPushStack(c));
}
/* ------------- Encoding and decoding outcomes -------------- */
static final class AltResult { // See above
final Throwable ex; // null only for NIL 只有NIL 是null
AltResult(Throwable x) { this.ex = x; }
}
// null值编码
/** The encoding of the null value. */
static final AltResult NIL = new AltResult(null);
// 使用null值完成,除非已经完成。
/** Completes with the null value, unless already completed. */
final boolean completeNull() {
// 使用CAS设置result 为NIL
return UNSAFE.compareAndSwapObject(this, RESULT, null,
NIL);
}
/** Returns the encoding of the given non-exceptional value. */
final Object encodeValue(T t) {
return (t == null) ? NIL : t;
}
// 以非异常结果完成,除非已经完成。
/** Completes with a non-exceptional result, unless already completed. */
final boolean completeValue(T t) {
// 设置 result 值, 如果 t = null,设置为 NIL (result 为null,表示CompletableFuture还没
// 执行过,所以如果执行结果为null,则使用NIL代替)
return UNSAFE.compareAndSwapObject(this, RESULT, null,
(t == null) ? NIL : t);
}
/**
* 返回给定(非空)异常的编码作为一个包装的CompletionException,除非它已经是了。
* Returns the encoding of the given (non-null) exception as a
* wrapped CompletionException unless it is one already.
*/
static AltResult encodeThrowable(Throwable x) {
// 如果异常不是CompletionException 类型的,则包装为 CompletionException
return new AltResult((x instanceof CompletionException) ? x :
new CompletionException(x));
}
// 以异常结果完成,除非已经完成。
/** Completes with an exceptional result, unless already completed. */
final boolean completeThrowable(Throwable x) {
// 使用AltResult包装异常
return UNSAFE.compareAndSwapObject(this, RESULT, null,
encodeThrowable(x));
}
/**
* 返回给定(非空)异常的编码作为一个包装的CompletionException,除非它已经是了。
* Returns the encoding of the given (non-null) exception as a
* wrapped CompletionException unless it is one already. May
* 可以返回给定的对象r(它必须是一个source future的结果),如果它是等价的,也就是说,
* 如果这是一个现有的CompletionException的简单中继。
* return the given Object r (which must have been the result of a
* source future) if it is equivalent, i.e. if this is a simple
* relay of an existing CompletionException.
*/
static Object encodeThrowable(Throwable x, Object r) {
// 如果 x不是CompletionException 类型的,则封装成 CompletionException
if (!(x instanceof CompletionException))
x = new CompletionException(x);
// 如果 x = r.ex,则直接返回
else if (r instanceof AltResult && x == ((AltResult)r).ex)
return r;
// 将CompletionException 封装到 AltResult
return new AltResult(x);
}
/**
* 使用给定的(非空)异常结果作为包装的CompletionException完成,除非它已经是一个CompletionException,
* 或者已经完成(result 不为null)。
* Completes with the given (non-null) exceptional result as a
* wrapped CompletionException unless it is one already, unless
* already completed. May complete with the given Object r
* 如果给定的对象r(它必须是一个源future的结果)是等价的,也就是说,如果这是一个
* 现有CompletionException的简单传播,则可以用它来完成。
* (which must have been the result of a source future) if it is
* equivalent, i.e. if this is a simple propagation of an
* existing CompletionException.
*/
// 使用CAS设置 result
final boolean completeThrowable(Throwable x, Object r) {
return UNSAFE.compareAndSwapObject(this, RESULT, null,
encodeThrowable(x, r));
}
/**
* 返回给定参数的编码:如果异常是非空的,则将其编码为AltResult。否则使用给定的值,如果null封装为NIL。
* Returns the encoding of the given arguments: if the exception
* is non-null, encodes as AltResult. Otherwise uses the given
* value, boxed as NIL if null.
*/
Object encodeOutcome(T t, Throwable x) {
return (x == null) ? (t == null) ? NIL : t
: encodeThrowable(x);
}
/**
* 返回复制结果的编码;如果异常,则重新包装为CompletionException,否则返回参数。
* Returns the encoding of a copied outcome; if exceptional,
* rewraps as a CompletionException, else returns argument.
*/
static Object encodeRelay(Object r) {
Throwable x;
// 如果执行异常了,并且异常类型不是 CompletionException类型的,则将异常包装成
// CompletionException,并封装到AltResult。否则直接返回r
return (((r instanceof AltResult) &&
(x = ((AltResult)r).ex) != null &&
!(x instanceof CompletionException)) ?
new AltResult(new CompletionException(x)) : r);
}
/**
* 用r或r的一个拷贝完成,除非已经完成。
* Completes with r or a copy of r, unless already completed.
* 如果异常,r首先被强制为CompletionException。
* If exceptional, r is first coerced to a CompletionException.
*/
final boolean completeRelay(Object r) {
// 设置result
return UNSAFE.compareAndSwapObject(this, RESULT, null,
encodeRelay(r));
}
/**
* 使用Future.get 约定报告结果
* Reports result using Future.get conventions.
*/
private static <T> T reportGet(Object r)
throws InterruptedException, ExecutionException {
// 根据下面的约定,null表示中断
if (r == null) // by convention below, null means interrupted
// 线程被中断,抛出 InterruptedException
throw new InterruptedException();
if (r instanceof AltResult) {
Throwable x, cause;
if ((x = ((AltResult)r).ex) == null)
// 执行结果为null
return null;
// 任务取消
if (x instanceof CancellationException)
throw (CancellationException)x;
if ((x instanceof CompletionException) &&
(cause = x.getCause()) != null)
x = cause;
// 任务执行异常,抛出ExecutionException
throw new ExecutionException(x);
}
// 返回结果
@SuppressWarnings("unchecked") T t = (T) r;
return t;
}
/**
* 解码结果以返回结果或抛出未检查的异常。
* Decodes outcome to return result or throw unchecked exception.
*/
// 和reportGet()不同的是:1、因为join()方法线程不接受中断,因此waitingGet() 不会返回null
// 2、任务执行异常reportGet()抛出的是ExecutionException异常,而reportJoin()抛出CompletionException
private static <T> T reportJoin(Object r) {
if (r instanceof AltResult) {
Throwable x;
if ((x = ((AltResult)r).ex) == null)
// 任务执行结果为null,返回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;
}
/* ------------- Async task preliminaries -------------- */
/**
* 一个标识符接口,标识由{@code async}方法产生的异步任务。
* A marker interface identifying asynchronous tasks produced by
* {@code async} methods. This may be useful for monitoring,
* 这对于监视、调试和跟踪异步活动可能很有用。
* debugging, and tracking asynchronous activities.
*
* @since 1.8
*/
public static interface AsynchronousCompletionTask {
}
// common池的目标并行度级别 是否大于1
private static final boolean useCommonPool =
(ForkJoinPool.getCommonPoolParallelism() > 1);
/**
* 默认执行器 -- ForkJoinPool.commonpool(),除非它不能支持并行。
* Default executor -- ForkJoinPool.commonPool() unless it cannot
* support parallelism.
*/
private static final Executor asyncPool = useCommonPool ?
ForkJoinPool.commonPool() : new ThreadPerTaskExecutor();
// 如果ForkJoinPool.commonPool()不能支持并行的应急计划
/** Fallback if ForkJoinPool.commonPool() cannot support parallelism */
static final class ThreadPerTaskExecutor implements Executor {
// 创建一个线程,执行给定的任务
public void execute(Runnable r) { new Thread(r).start(); }
}
/**
* 空值检查用户执行器参数,并在禁用并行的情况下将commonPool的使用转换为asyncPool。
* Null-checks user executor argument, and translates uses of
* commonPool to asyncPool in case parallelism disabled.
*/
// 筛选执行器
static Executor screenExecutor(Executor e) {
// 禁用并行的情况下若使用common池,则转换为asyncPool。
if (!useCommonPool && e == ForkJoinPool.commonPool())
return asyncPool;
// 若执行器为null,抛出 NullPointerException
if (e == null) throw new NullPointerException();
return e;
}
// Modes for Completion.tryFire. Signedness matters.
static final int SYNC = 0;
static final int ASYNC = 1;
static final int NESTED = -1;
/* ------------- Base Completion classes and operations -------------- */
@SuppressWarnings("serial")
abstract static class Completion extends ForkJoinTask<Void>
implements Runnable, AsynchronousCompletionTask {
volatile Completion next; // Treiber stack link
/**
* 如果触发,则执行完成操作,如果存在,则返回可能需要传播的依赖项。
* Performs completion action if triggered, returning a
* dependent that may need propagation, if one exists.
*
* @param mode SYNC, ASYNC, or NESTED
*/
// 根据模式运行postComplete 或 将this 返回给调用者。
abstract CompletableFuture<?> tryFire(int mode);
// 如果可能仍可触发,则返回true。由cleanStack使用。
/** Returns true if possibly still triggerable. Used by cleanStack. */
abstract boolean isLive();
// Runnable方法
public final void run() { tryFire(ASYNC); }
// ForkJoinTask方法
public final boolean exec() { tryFire(ASYNC); return true; }
public final Void getRawResult() { return null; }
public final void setRawResult(Void v) {}
}
static void lazySetNext(Completion c, Completion next) {
// 不会保证对变量的写立即可见,但能保证写入顺序
UNSAFE.putOrderedObject(c, NEXT, next);
}
/**
* pop并尝试触发所有可到达的依赖项。只有在已知已完成时才调用。
* Pops and tries to trigger all reachable dependents. Call only
* when known to be done.
*/
final void postComplete() {
/*
* 在每个步骤中,变量f保存当前依赖项以弹出和运行。
* On each step, variable f holds current dependents to pop
* 它一次只沿着一条路径扩展,其他路径放回堆栈以避免无界递归。 (不使用递归遍历二叉树)
* and run. It is extended along only one path at a time,
* pushing others to avoid unbounded recursion.
*/
// r r r
// / this = r / /
// s1 CAS修改stack为n1 s1 n1 s2
// / \ ======> / / \ ====> / \
// s2 n1 s2 s4 n2 s3 n1
// / \ / \ / \ / \
// s3 n3 s4 n2 s3 n3 s4 n2
// CAS修改stack为n1 ,相当于分割成了右边两棵树,同步执行完s1后,由于s1.stack != null,因此返回s1的 dep,f = s1.dep,
// h = s1.stack = s2,h.next = n3,n3 != null,f = s1 != this,因此s2放回r的堆栈中,然后执行n3。
CompletableFuture<?> f = this; Completion h;
while ((h = f.stack) != null ||
(f != this && (h = (f = this).stack) != null)) {
CompletableFuture<?> d; Completion t;
// 使用CAS修改stack 的值 next (可能会有多线程一起执行,所以需要使用CAS)
if (f.casStack(h, t = h.next)) {
if (t != null) {
if (f != this) {
// 将h 放到this 的堆栈中 (注意不是f)
pushStack(h);
continue;
}
h.next = null; // detach 分离
}
// 如果同步执行了h 的任务并且h.stack不为null,则返回h;其他情况返回null
f = (d = h.tryFire(NESTED)) == null ? this : d;
}
}
}
// 遍历stack 并解除过期的 Completions连接
/** Traverses stack and unlinks dead Completions. */
final void cleanStack() {
// p -> previous 表示前一个 Completion
for (Completion p = null, q = stack; q != null;) {
Completion s = q.next;
// q 还是有效的 (未执行过)
if (q.isLive()) {
p = q;
q = s;
}
// q 无效,进行删除
else if (p == null) {
// 使用CAS修改stack = s,即移除q
casStack(q, s);
// q = stack,重新开始 (因为CAS可能失败,所以不使用 q = s)
q = stack;
}
else {
// p.next = s,移除q
p.next = s;
// 判断上一个Completion是否还是有效的
if (p.isLive())
q = s;
else {
// 从stack重新开始
p = null; // restart
q = stack;
}
}
}
}
/* ------------- One-input Completions -------------- */
/** A Completion with a source, dependent, and executor. */
@SuppressWarnings("serial")
abstract static class UniCompletion<T,V> extends Completion {
// 要使用的执行器(如果没有,则为null)
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。只有在已知可触发时才调用。
* Returns true if action can be run. Call only when known to
* 使用FJ标记位确保只有一个线程声明所有权。
* be triggerable. Uses FJ tag bit to ensure that only one
* thread claims ownership. If async, starts as task -- a
* 如果异步,作为任务启动——稍后调用tryFire将运行操作。
* later call to tryFire will run action.
*/
// 若线程可以同步执行任务返回true,否则返回false
final boolean claim() {
Executor e = executor;
// 设置 FrokJoinTask标记
if (compareAndSetForkJoinTaskTag((short)0, (short)1)) {
if (e == null)
// 没有执行器,返回true,使用调用用的线程执行
return true;
// executor 设置为null
executor = null; // disable
// 作为任务启动
e.execute(this);
}
// 没有获取到任务的执行权,或者任务已经进行异步执行了,返回false,表示操作不能再执行
return false;
}
// 判断此Completion是否还是有效的(未执行过)
final boolean isLive() { return dep != null; }
}
// 除非完成,否则将给定的 completion放入堆栈(如果存在)。
/** Pushes the given completion (if it exists) unless done. */
final void push(UniCompletion<?,?> c) {
if (c != null) {
// 若result = null (即source未完成),将c 压入栈顶
while (result == null && !tryPushStack(c))
// CAS失败,则清除 next
lazySetNext(c, null); // clear on failure
}
}
/**
* UniCompletion.tryFire 成功后dependent调用后置处理
* Post-processing by dependent after successful UniCompletion
* 尝试清除源a的堆栈,然后根据模式运行postComplete 或 将this 返回给调用者。
* tryFire. Tries to clean stack of source a, and then either runs
* postComplete or returns this to caller, depending on mode.
*/
// 根据模式运行postComplete 或 将this 返回给调用者
final CompletableFuture<T> postFire(CompletableFuture<?> a, int mode) {
if (a != null && a.stack != null) {
// SYNC = 0, ASYNC = 1, NESTED = -1
// mode = NESTED 时说明是 postComplete调用的这个方法,postComplete会继续往下传播,不需要再次调用
if (mode < 0 || a.result == null)
// 删除过期的Completion
a.cleanStack();
else
// a.result != null 说明a 已经完成了
// this是异步执行的才会执行到这里,如果是postComplete()同步执行的那么mode = NESTED,不会执行到这里。
// 执行完成后帮助a完成后续的依赖操作 (多线程一起执行)
a.postComplete();
}
// a 是source, this 是dependant
if (result != null && stack != null) {
if (mode < 0)
// NESTED 模式,返回this
return this;
else
// 调用后续的依赖操作
postComplete();
}
return null;
}
@SuppressWarnings("serial")
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;
}
// 1、(d = dep) == null : 若上一阶段是异步的,completion放入堆栈后,上一阶段完成了,然后此线程
// 执行tryFire() 就可能和上一阶段执行的线程产生竞争(上一阶段的线程调用postCompletion()方法,执行
// 该completion的 tryFire()方法)。因此,此时dep可能为 null。
// 2、如果将 completion放入上一阶段的堆栈时,刚好上一个阶段已经完成了,则压入堆栈会失败,但是由于上一阶段
// 已经完成了,因此d.uniApply() 一定可以成功调用
// SYNC = 0, ASYNC = 1, NESTED = -1
final CompletableFuture<V> tryFire(int mode) {
CompletableFuture<V> d; CompletableFuture<T> a;
// dep = null 说明任务已经执行过了,直接返回,因为完成的线程会执行后续的操作;
// mode > 0, 判断是否是 ASYNC
// uniApply() 若任已知任务已完成,返回true,否则返回false。
if ((d = dep) == null ||
!d.uniApply(a = src, fn, mode > 0 ? null : this))
// 任务已经被其他线程执行了 || 任务异步执行,直接返回null
return null;
// 任务已执行,clean
dep = null; src = null; fn = null;
// a = src, d = dep 通过uniApply()方法已执行完成的CompletableFuture
return d.postFire(a, mode);
}
}
// The method returns true if known to be complete.
// 若已知任务已经完成了,返回true,否则返回false。
final <S> boolean uniApply(CompletableFuture<S> a,
Function<? super S,? extends T> f,
UniApply<S,T> c) {
Object r; Throwable x;
// 1、c放入堆栈后调用 c.tryFire()方法 和 上一阶段异步完成后调用postCompletion()方法
// 方法,然后调用 c.tryFire()方法可能会存在竞争,因此 a 、f 在这里都可能为null
// 2、(r = a.result) == null 说明 a 未完成。
if (a == null || (r = a.result) == null || f == null)
return false;
// ---- a 已经完成了,执行 f ------
// result == null 说明 this未完成
tryComplete: if (result == null) {
if (r instanceof AltResult) {
// 只有NIL 的ex 是null,表示结果为null。 x != null,说明a 异常了
if ((x = ((AltResult)r).ex) != null) {
// 设置result
completeThrowable(x, r);
break tryComplete;
}
// r.ex = null,说明执行结果为null
r = null;
}
try {
// c -> ASYNC传入null,SYNC、NESTED传入相应的 completion
// claim()如果操作可以运行,则返回true
if (c != null && !c.claim())
// c.claim() 返回false,说明任务已经执行
return false;
@SuppressWarnings("unchecked") S s = (S) r;
// 将调用方CompletableFuture 执行的结果作为参数,使用调用的线程同步执行Function
completeValue(f.apply(s));
} catch (Throwable ex) {
// 设置异常
completeThrowable(ex);
}
}
// 已知已经完成了,返回true
return true;
}
private <V> CompletableFuture<V> uniApplyStage(
Executor e, Function<? super T,? extends V> f) {
// 若f = null,抛出 NullPointerException
if (f == null) throw new NullPointerException();
CompletableFuture<V> d = new CompletableFuture<V>();
// 如果不是异步(e = null),并且this已经完成,则立即运行操作
// uniApply() 若已知f 已经执行完成了,返回true,否则返回false。
if (e != null || !d.uniApply(this, f, null)) {
UniApply<T,V> c = new UniApply<T,V>(e, d, this, f);
// 将c 压入this 的stack 栈顶 (push的时候有可能这时候this完成了)
push(c);
c.tryFire(SYNC);
}
return d;
}
@SuppressWarnings("serial")
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;
}
// SYNC = 0, ASYNC = 1, NESTED = -1
final CompletableFuture<Void> tryFire(int mode) {
CompletableFuture<Void> d; CompletableFuture<T> a;
// dep = null 说明任务已经执行过了,直接返回,因为完成的线程会执行后续的操作; mode > 0, 判断是否是 ASYNC
// uniApply() 若任务同步执行完成了,返回true,否则返回false。
if ((d = dep) == null ||
!d.uniAccept(a = src, fn, mode > 0 ? null : this))
// 任务已经被其他线程执行了 || 任务异步执行,直接返回null
return null;
// 任务已执行,clean
dep = null; src = null; fn = null;
// a = src, d = dep 通过uniApply()方法已执行完成的CompletableFuture
return d.postFire(a, mode);
}
}
// 若已知已经执行完成了,返回true,否则返回false。
final <S> boolean uniAccept(CompletableFuture<S> a,
Consumer<? super S> f, UniAccept<S> c) {
Object r; Throwable x;
// (r = a.result) == null 说明 a 未完成
if (a == null || (r = a.result) == null || f == null)
return false;
// ---- a 已经完成了,执行 f ------
// result == null 说明 this未完成
tryComplete: if (result == null) {
if (r instanceof AltResult) {
// 只有NIL 的ex 是null,表示结果为null。 x != null,说明a 异常了
if ((x = ((AltResult)r).ex) != null) {
// 设置result
completeThrowable(x, r);
break tryComplete; // 结束,返回true
}
// r.ex = null,说明执行结果为null
r = null;
}
try {
// c -> ASYNC传入null,SYNC、NESTED传入相应的 completion
// claim()如果操作可以运行,则返回true
if (c != null && !c.claim())
// 异步执行,返回false。
return false;
@SuppressWarnings("unchecked") S s = (S) r;
// 将此阶段执行的结果作为参数,调用给定的函数
f.accept(s);
// 使用CAS设置result 为NIL (需要使用CAS,因为任务有可能同时被取消)
completeNull();
} catch (Throwable ex) {
// 设置异常
completeThrowable(ex);
}
}
// 已知已经完成了,返回true
return true;
}
private CompletableFuture<Void> uniAcceptStage(Executor e,
Consumer<? super T> f) {
if (f == null) throw new NullPointerException();
CompletableFuture<Void> d = new CompletableFuture<Void>();
// 若非异步执行,则调用uniAccept()方法,当此阶段已经完成时,直接执行给定的函数
if (e != null || !d.uniAccept(this, f, null)) {
UniAccept<T> c = new UniAccept<T>(e, d, this, f);
// 将c 压入this 的stack 栈顶 (push的时候有可能这时候this完成了)
push(c);
c.tryFire(SYNC);
}
return d;
}
@SuppressWarnings("serial")
static final class UniRun<T> extends UniCompletion<T,Void> {
Runnable fn;
UniRun(Executor executor, CompletableFuture<Void> dep,
CompletableFuture<T> src, Runnable fn) {
super(executor, dep, src); this.fn = fn;
}
// SYNC = 0, ASYNC = 1, NESTED = -1
final CompletableFuture<Void> tryFire(int mode) {
CompletableFuture<Void> d; CompletableFuture<T> a;
// dep = null 说明任务已经执行过了,直接返回,因为完成的线程会执行后续的操作; mode > 0, 判断是否是 ASYNC
// uniRun() 若任务同步执行完成了,返回true,否则返回false。
if ((d = dep) == null ||
!d.uniRun(a = src, fn, mode > 0 ? null : this))
return null;
// 任务已执行,clean
dep = null; src = null; fn = null;
return d.postFire(a, mode);
}
}
// 若已知已经执行完成了,返回true,否则返回false。
final boolean uniRun(CompletableFuture<?> a, Runnable f, UniRun<?> c) {
Object r; Throwable x;
// (r = a.result) == null 说明 a 未完成(此阶段未完成,不能执行下一阶段)
if (a == null || (r = a.result) == null || f == null)
return false;
if (result == null) {
if (r instanceof AltResult && (x = ((AltResult)r).ex) != null)
// 设置result 为r
completeThrowable(x, r);
else
try {
// c -> ASYNC传入null,SYNC、NESTED传入相应的 completion
// claim()如果操作可以同步执行,则返回true,否则返回flase
if (c != null && !c.claim())
return false;
// 执行给定的函数
f.run();
// 使用CAS设置result 为NIL (需要使用CAS,因为任务有可能同时被取消)
completeNull();
} catch (Throwable ex) {
// 设置异常
completeThrowable(ex);
}
}
// 已知已经完成了,返回true
return true;
}
private CompletableFuture<Void> uniRunStage(Executor e, Runnable f) {
// 若f = null,抛出异常
if (f == null) throw new NullPointerException();
CompletableFuture<Void> d = new CompletableFuture<Void>();
// 若非异步执行,则调用uniRun()方法,当此阶段已经完成时,直接执行给定的函数。
// 已知已经完成返回true,否则返回false
if (e != null || !d.uniRun(this, f, null)) {
UniRun<T> c = new UniRun<T>(e, d, this, f);
// 将c 压入this 的stack 栈顶 (push的时候有可能这时候this完成了)
push(c);
c.tryFire(SYNC);
}
return d;
}
@SuppressWarnings("serial")
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;
// dep = null说明此任务已经执行过了
// mode > 0, 判断是否是 ASYNC
// uniWhenComplete() 若任已知任务已完成,返回true,否则返回false。
if ((d = dep) == null ||
!d.uniWhenComplete(a = src, fn, mode > 0 ? null : this))
return null;
// 任务已执行,clean
dep = null; src = null; fn = null;
return d.postFire(a, mode);
}
}
final boolean uniWhenComplete(CompletableFuture<T> a,
BiConsumer<? super T,? super Throwable> f,
UniWhenComplete<T> c) {
Object r; T t; Throwable x = null;
// a == null || f == null 说明此任务已经执行过了
// a.result = null,说明a 未完成
if (a == null || (r = a.result) == null || f == null)
return false;
// result = null 说明此任务未完成
if (result == null) {
try {
// 需要同步执行时 c传入null
// claim()若线程可以同步执行任务返回true,否则返回false
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;
}
// 参数传入a 执行的结果 (异常时为null) 和异常 (正常执行时为null)
f.accept(t, x);
// x = null,说明a 正常执行了
if (x == null) {
// 设置结果为 a执行的结果 r
internalComplete(r);
return true;
}
} catch (Throwable ex) {
// 若x = null,则设置 x = ex
if (x == null)
x = ex;
}
// a 异常了,设置结果为相同的异常, 或者 给定的函数执行异常了
completeThrowable(x, r);
}
return true;
}
private CompletableFuture<T> uniWhenCompleteStage(
Executor e, BiConsumer<? super T, ? super Throwable> f) {
if (f == null) throw new NullPointerException();
CompletableFuture<T> d = new CompletableFuture<T>();
// e != null 说明需要异步执行
if (e != null || !d.uniWhenComplete(this, f, null)) {
UniWhenComplete<T> c = new UniWhenComplete<T>(e, d, this, f);
// 将c 放入this的堆栈
push(c);
c.tryFire(SYNC);
}
return d;
}
@SuppressWarnings("serial")
static final class UniHandle<T,V> extends UniCompletion<T,V> {
BiFunction<? super T, Throwable, ? extends V> fn;
UniHandle(Executor executor, CompletableFuture<V> dep,
CompletableFuture<T> src,
BiFunction<? super T, Throwable, ? extends V> fn) {
super(executor, dep, src); this.fn = fn;
}
// SYNC = 0, ASYNC = 1, NESTED = -1
final CompletableFuture<V> tryFire(int mode) {
CompletableFuture<V> d; CompletableFuture<T> a;
// dep = null 说明任务已经执行过了,直接返回,因为完成的线程会执行后续的操作;
// mode > 0, 判断是否是 ASYNC
// uniHandle() 若任已知任务已完成,返回true,否则返回false。
if ((d = dep) == null ||
!d.uniHandle(a = src, fn, mode > 0 ? null : this))
return null;
// 任务已执行,clean
dep = null; src = null; fn = null;
// a = src, d = dep 通过uniHandle()方法已执行完成的CompletableFuture
return d.postFire(a, mode);
}
}
final <S> boolean uniHandle(CompletableFuture<S> a,
BiFunction<? super S, Throwable, ? extends T> f,
UniHandle<S,T> c) {
Object r; S s; Throwable x;
// a == null || f == null 说明此任务已经执行过了
// a.result = null 说明a 未完成
if (a == null || (r = a.result) == null || f == null)
return false;
// result == null 说明 this未完成
if (result == null) {
try {
// c -> ASYNC传入null,SYNC、NESTED传入相应的 completion
// claim()如果操作可以运行,则返回true
if (c != null && !c.claim())
return false;
if (r instanceof AltResult) {
// a 执行异常 或者 a 的执行结果为null,这两种情况s 都是 null
x = ((AltResult)r).ex;
s = null;
} else {
// a 正常执行了, x = null
x = null;
@SuppressWarnings("unchecked") S ss = (S) r;
s = ss;
}
// 执行给定的函数,参数传入a 执行的结果 (异常时为null) 和异常 (正常执行时为null),
// 并设置结果
completeValue(f.apply(s, x));
} catch (Throwable ex) {
// 设置结果为异常
completeThrowable(ex);
}
}
// 已知已经完成了,返回true
return true;
}
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>();
// 如果不是异步(e = null),并且this已经完成,则立即运行操作
// uniHandle() 若已知f 已经执行完成了,返回true,否则返回false。
if (e != null || !d.uniHandle(this, f, null)) {
UniHandle<T,V> c = new UniHandle<T,V>(e, d, this, f);
// 把 c放入this的堆栈
push(c);
c.tryFire(SYNC);
}
return d;
}
@SuppressWarnings("serial")
static final class UniExceptionally<T> extends UniCompletion<T,T> {
Function<? super Throwable, ? extends T> fn;
UniExceptionally(CompletableFuture<T> dep, CompletableFuture<T> src,
Function<? super Throwable, ? extends T> fn) {
super(null, dep, src); this.fn = fn;
}
// exceptionally() 没有异步的方法
final CompletableFuture<T> tryFire(int mode) { // never ASYNC
// assert mode != ASYNC;
CompletableFuture<T> d; CompletableFuture<T> a;
// dep = null 说明任务已经执行过了,直接返回,因为完成的线程会执行后续的操作;
// uniExceptionally() 若任已知任务已完成,返回true,否则返回false。
if ((d = dep) == null || !d.uniExceptionally(a = src, fn, this))
return null;
// 任务已执行,clean
dep = null; src = null; fn = null;
// 任务执行完成后进行后置处理
return d.postFire(a, mode);
}
}
final boolean uniExceptionally(CompletableFuture<T> a,
Function<? super Throwable, ? extends T> f,
UniExceptionally<T> c) {
Object r; Throwable x;
// a == null || f == null 说明此任务已经执行过了
// a.result = null 说明a 未完成
if (a == null || (r = a.result) == null || f == null)
return false;
// result = null 说明此任务未完成
if (result == null) {
try {
// 若a 执行结果为异常
if (r instanceof AltResult && (x = ((AltResult)r).ex) != null) {
// c -> ASYNC传入null,SYNC、NESTED传入相应的 completion
// claim()如果操作可以运行,则返回true
if (c != null && !c.claim())
return false;
// 调用给定的函数,参数传入a 执行的异常。并设置结果
completeValue(f.apply(x));
} else
// 设置结果为r
internalComplete(r);
} catch (Throwable ex) {
// 设置异常
completeThrowable(ex);
}
}
// 已知已经完成了,返回true
return true;
}
private CompletableFuture<T> uniExceptionallyStage(
Function<Throwable, ? extends T> f) {
if (f == null) throw new NullPointerException();
CompletableFuture<T> d = new CompletableFuture<T>();
// uniExceptionally() 若已知f 已经执行完成了,返回true,否则返回false。
if (!d.uniExceptionally(this, f, null)) {
UniExceptionally<T> c = new UniExceptionally<T>(d, this, f);
// 将c 放入this 的堆栈
push(c);
c.tryFire(SYNC);
}
return d;
}
@SuppressWarnings("serial")
static final class UniRelay<T> extends UniCompletion<T,T> { // for Compose
UniRelay(CompletableFuture<T> dep, CompletableFuture<T> src) {
super(null, dep, src);
}
final CompletableFuture<T> tryFire(int mode) {
CompletableFuture<T> d; CompletableFuture<T> a;
// dep = null 说明任务已经执行过了,直接返回,因为完成的线程会执行后续的操作;
// uniRelay() 若任已知任务已完成,返回true,否则返回false。
if ((d = dep) == null || !d.uniRelay(a = src))
return null;
// 任务已执行,clean
src = null; dep = null;
// a 调用给定函数返回的CompletableFuture
return d.postFire(a, mode);
}
}
final boolean uniRelay(CompletableFuture<T> a) {
Object r;
// a = null,说明此CompletableFuture 已经被其他线程执行完成了,所以被设置为null
// a.result = null 说明a 未完成
if (a == null || (r = a.result) == null)
return false;
// a 已经完成,但是未设置 this.result,因此需要设置this.result
if (result == null) // no need to claim
// 设置结果为完成
completeRelay(r);
// 已知this 已经完成,返回true
return true;
}
@SuppressWarnings("serial")
static final class UniCompose<T,V> extends UniCompletion<T,V> {
Function<? super T, ? extends CompletionStage<V>> fn;
UniCompose(Executor executor, CompletableFuture<V> dep,
CompletableFuture<T> src,
Function<? super T, ? extends CompletionStage<V>> fn) {
super(executor, dep, src); this.fn = fn;
}
// SYNC = 0, ASYNC = 1, NESTED = -1
final CompletableFuture<V> tryFire(int mode) {
CompletableFuture<V> d; CompletableFuture<T> a;
// d = null 说明任务已经执行过了,直接返回,因为完成的线程会执行后续的操作;
// mode > 0, 判断是否是 ASYNC
// uniCompose() 若任已知任务已完成,返回true,否则返回false。
if ((d = dep) == null ||
!d.uniCompose(a = src, fn, mode > 0 ? null : this))
return null;
// 任务已完成,clean
dep = null; src = null; fn = null;
// 任务完成后进行后置处理
return d.postFire(a, mode);
}
}
final <S> boolean uniCompose(
CompletableFuture<S> a,
Function<? super S, ? extends CompletionStage<T>> f,
UniCompose<S,T> c) {
Object r; Throwable x;
// 1、c放入堆栈后调用 c.tryFire()方法 和 上一阶段异步完成后调用postCompletion()方法
// 方法,然后调用 c.tryFire()方法可能会存在竞争,因此 a 、f 在这里都可能为null
// 2、(r = a.result) == null 说明 a 未完成
if (a == null || (r = a.result) == null || f == null)
return false;
// ---- a 已经完成了,执行 f ------
// result == null 说明 this未完成,因此可以执行
tryComplete: if (result == null) {
if (r instanceof AltResult) {
// 只有NIL 的ex 是null,表示结果为null。 x != null,说明a 异常了
if ((x = ((AltResult)r).ex) != null) {
// 设置result
completeThrowable(x, r);
break tryComplete;
}
// r.ex = null,说明执行结果为null
r = null;
}
try {
// c -> ASYNC传入null,SYNC、NESTED传入相应的 completion
// claim()如果操作可以运行,则返回true,否则返回false
if (c != null && !c.claim())
return false;
@SuppressWarnings("unchecked") S s = (S) r;
// toCompletableFuture() 返回此 CompletableFuture
CompletableFuture<T> g = f.apply(s).toCompletableFuture();
// g.result == null 说明g 未完成
// uniRelay() 若任已知任务已完成,返回true,否则返回false。
if (g.result == null || !uniRelay(g)) {
UniRelay<T> copy = new UniRelay<T>(this, g);
// 将copy 放入g的堆栈,当g 完成后需要调用 copy.tryFire()
g.push(copy);
copy.tryFire(SYNC);
// this 未完成,返回false
if (result == null)
return false;
}
} catch (Throwable ex) {
// 设置异常
completeThrowable(ex);
}
}
// 已知已经完成了,返回true
return true;
}
// 返回的是一个新创建的CompletableFuture,而不是f 的执行结果
private <V> CompletableFuture<V> uniComposeStage(
Executor e, Function<? super T, ? extends CompletionStage<V>> f) {
if (f == null) throw new NullPointerException();
Object r; Throwable x;
// e = null 说明非异步执行
// result != null 说明此阶段(this)已经完成
if (e == null && (r = result) != null) {
// try to return function result directly
if (r instanceof AltResult) {
// r.ex != null 说明此阶段执行异常了
if ((x = ((AltResult)r).ex) != null) {
// encodeThrowable() 将异常包装成CompletionException,并封装到 AltResult
// 创建CompletableFuture,并设置结果
return new CompletableFuture<V>(encodeThrowable(x, r));
}
// r.ex = null,说明此阶段的执行结果为null,所以设置 r = null
r = null;
}
try {
@SuppressWarnings("unchecked") T t = (T) r;
// toCompletableFuture() 返回此 CompletableFuture
// 执行给定的函数,并将结果转成 CompletableFuture
CompletableFuture<V> g = f.apply(t).toCompletableFuture();
Object s = g.result;
// s != null 说明g已经执行完成了,否则说明g是异步执行的,未完成
if (s != null)
// encodeRelay() 如果执行异常了,并且异常类型不是 CompletionException类型的,
// 则将异常包装成CompletionException,并封装到AltResult。否则直接返回r
return new CompletableFuture<V>(encodeRelay(s));
// g 未完成
CompletableFuture<V> d = new CompletableFuture<V>();
UniRelay<V> copy = new UniRelay<V>(d, g);
// 将copy 放入g 的堆栈,当g 完成后需要调用 copy.tryFire()
g.push(copy);
copy.tryFire(SYNC);
return d;
} catch (Throwable ex) {
return new CompletableFuture<V>(encodeThrowable(ex));
}
}
CompletableFuture<V> d = new CompletableFuture<V>();
// 异步的是创建UniCompose,同步并且此阶段已经完成创建的是 UniRelay
UniCompose<T,V> c = new UniCompose<T,V>(e, d, this, f);
// 将 c 放入this 的堆栈
push(c);
c.tryFire(SYNC);
return d;
}
/* ------------- Two-input Completions -------------- */
// 一个操作带有两个源的 Completion
/** A Completion for an action with two sources */
@SuppressWarnings("serial")
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;
}
}
// 委托给BiCompletion 的Completion
/** A Completion delegating to a BiCompletion */
@SuppressWarnings("serial")
static final class CoCompletion extends Completion {
BiCompletion<?,?,?> base;
CoCompletion(BiCompletion<?,?,?> base) { this.base = base; }
final CompletableFuture<?> tryFire(int mode) {
BiCompletion<?,?,?> c; CompletableFuture<?> d;
// c.tryFire(mode) 在ASYNC 模式下,如果同步执行了c的操作,并且c.dep的堆栈不为空,则返回c.dep,
// 其他情况返回null
if ((c = base) == null || (d = c.tryFire(mode)) == null)
return null;
base = null; // detach 解除引用
// 返回c.dep
return d;
}
final boolean isLive() {
BiCompletion<?,?,?> c;
return (c = base) != null && c.dep != null;
}
}
// 除非两者都完成,否则将completion 压入this 和 b的顶栈
/** Pushes completion to this and b unless both done. */
final void bipush(CompletableFuture<?> b, BiCompletion<?,?,?> c) {
if (c != null) {
Object r;
// 若this 未完成,将c 压入this 的顶栈
while ((r = result) == null && !tryPushStack(c))
// CAS失败,则清除 c.next
lazySetNext(c, null); // clear on failure
if (b != null && b != this && b.result == null) {
// c放入this的堆栈后就不能再放到b的堆栈,否则this 和 b的堆栈就会互相影响
// (一方修改了b.next,另一方就跟着改变),因此需要将c封装成CoCompletion,再构建一个对象
Completion q = (r != null) ? c : new CoCompletion(c);
// 若b 未完成,将q 压入b 的顶栈
while (b.result == null && !b.tryPushStack(q))
// CAS失败,则清除 q.next
lazySetNext(q, null); // clear on failure
}
}
}
// BiCompletion.tryFire 成功后的后置处理
/** Post-processing after successful BiCompletion tryFire. */
final CompletableFuture<T> postFire(CompletableFuture<?> a,
CompletableFuture<?> b, int mode) {
// 清理第二个源
if (b != null && b.stack != null) { // clean second source
// SYNC = 0, ASYNC = 1, NESTED = -1
if (mode < 0 || b.result == null)
// 遍历堆栈,删除过期的链接
b.cleanStack();
else
// 处理后续的依赖操作
b.postComplete();
}
return postFire(a, mode);
}
@SuppressWarnings("serial")
static final class BiApply<T,U,V> extends BiCompletion<T,U,V> {
BiFunction<? super T,? super U,? extends V> fn;
// e, d, this, b, f
BiApply(Executor executor, CompletableFuture<V> dep,
CompletableFuture<T> src, CompletableFuture<U> snd,
BiFunction<? super T,? super U,? extends V> fn) {
super(executor, dep, src, snd);
this.fn = fn;
}
// SYNC = 0, ASYNC = 1, NESTED = -1
final CompletableFuture<V> tryFire(int mode) {
CompletableFuture<V> d;
CompletableFuture<T> a;
CompletableFuture<U> b;
// dep = null 说明任务已经执行过了,直接返回,因为完成的线程会执行后续的操作; mode > 0, 判断是否是 ASYNC
// biApply()若已知任务已完成,返回true,否则返回false。
if ((d = dep) == null ||
!d.biApply(a = src, b = snd, fn, mode > 0 ? null : this))
return null;
// 任务执行完成,clean
dep = null; src = null; snd = null; fn = null;
// 任务完成后进行后置处理
return d.postFire(a, b, mode);
}
}
// a : 第一个源,即调用thenCombine()方法的 CompletableFuture ; b: o.toCompletableFuture() (第二个源)
// 若任务同步执行完成了,返回true,否则返回false。
final <R,S> boolean biApply(CompletableFuture<R> a,
CompletableFuture<S> b,
BiFunction<? super R,? super S,? extends T> f,
BiApply<R,S,T> c) {
Object r, s; Throwable x;
// a、b只要一个未完成,或者f = null,即返回false
// 当存在竞争时,a、b、f都可能为null
if (a == null || (r = a.result) == null ||
b == null || (s = b.result) == null || f == null)
return false;
// result == null 说明任务为完成
tryComplete: if (result == null) {
if (r instanceof AltResult) {
if ((x = ((AltResult)r).ex) != null) {
// a异常了,设置 this的结果为异常
completeThrowable(x, r);
break tryComplete;
}
// NIL 的ex = null,表示执行结果为null,所以设置r = null
r = null;
}
if (s instanceof AltResult) {
if ((x = ((AltResult)s).ex) != null) {
// b异常了,设置 this的结果为异常
completeThrowable(x, s);
break tryComplete;
}
// b的执行结果为null,所以设置s = null
s = null;
}
try {
// c只有当mode为ASYNC 的时候传入null,即线程池的线程正在执行任务
// claim()若线程可以同步执行任务返回true,否则返回false
if (c != null && !c.claim())
return false;
// 第一个源执行的结果作为 apply的第一个参数,第二个源执行的结果作为apply的第二个参数
@SuppressWarnings("unchecked") R rr = (R) r;
@SuppressWarnings("unchecked") S ss = (S) s;
// 执行函数,并设置结果
completeValue(f.apply(rr, ss));
} catch (Throwable ex) {
// 设置结果为异常
completeThrowable(ex);
}
}
// 已知已经完成了,返回true
return true;
}
// BiFunction -> R apply(T t, U u)
// 本阶段执行的结果作为 apply的第一个参数,o执行的结果作为apply的第二个参数
private <U,V> CompletableFuture<V> biApplyStage(
Executor e, CompletionStage<U> o,
BiFunction<? super T,? super U,? extends V> f) {
CompletableFuture<U> b;
// 判空,toCompletableFuture() 返回 CompletableFuture
if (f == null || (b = o.toCompletableFuture()) == null)
throw new NullPointerException();
CompletableFuture<V> d = new CompletableFuture<V>();
// 如果不是异步执行 (e = null),则调用biApply() 方法
if (e != null || !d.biApply(this, b, f, null)) {
BiApply<T,U,V> c = new BiApply<T,U,V>(e, d, this, b, f);
// 除非两者都完成,否则将c 压入this 和 b的顶栈 (c只能用一次,因此第二次使用需要进行包装)
bipush(b, c);
c.tryFire(SYNC);
}
return d;
}
@SuppressWarnings("serial")
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;
}
// SYNC = 0, ASYNC = 1, NESTED = -1
final CompletableFuture<Void> tryFire(int mode) {
CompletableFuture<Void> d;
CompletableFuture<T> a;
CompletableFuture<U> b;
// dep = null 说明任务已经执行过了,直接返回,因为完成的线程会执行后续的操作; mode > 0, 判断是否是 ASYNC
// biAccept()若已知任务已完成,返回true,否则返回false。
if ((d = dep) == null ||
!d.biAccept(a = src, b = snd, fn, mode > 0 ? null : this))
return null;
// 任务执行完成,clean
dep = null; src = null; snd = null; fn = null;
// 任务完成后进行后置处理
return d.postFire(a, b, mode);
}
}
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只要一个未完成,或者f = null,即返回false
// 当存在竞争时,a、b、f都可能为null
if (a == null || (r = a.result) == null ||
b == null || (s = b.result) == null || f == null)
return false;
// 若 result != null,则任务已经完成,返回true
// (当存在竞争时,可能两个线程都返回true,一个执行了任务,一个判断result != null)
tryComplete: if (result == null) {
if (r instanceof AltResult) {
if ((x = ((AltResult)r).ex) != null) {
// a异常了,设置 this的结果为异常
completeThrowable(x, r);
break tryComplete;
}
// NIL 的ex = null,表示执行结果为null,所以设置r = null
r = null;
}
if (s instanceof AltResult) {
if ((x = ((AltResult)s).ex) != null) {
// b异常了,设置 this的结果为异常
completeThrowable(x, s);
break tryComplete;
}
// b的执行结果为null,所以设置s = null
s = null;
}
try {
// c只有当mode为ASYNC 的时候传入null,即线程池的线程正在执行任务
// claim()若线程可以同步执行任务返回true,否则返回false
if (c != null && !c.claim())
return false;
// 第一个源执行的结果作为 apply的第一个参数,第二个源执行的结果作为apply的第二个参数
@SuppressWarnings("unchecked") R rr = (R) r;
@SuppressWarnings("unchecked") S ss = (S) s;
// 执行给定的函数
f.accept(rr, ss);
// 设置结果为NIL
completeNull();
} catch (Throwable ex) {
// 设置结果为异常
completeThrowable(ex);
}
}
// 已知任务已经完成,返回true
return true;
}
private <U> CompletableFuture<Void> biAcceptStage(
Executor e, CompletionStage<U> o,
BiConsumer<? super T,? super U> f) {
CompletableFuture<U> b;
// toCompletableFuture() 返回此 CompletableFuture
if (f == null || (b = o.toCompletableFuture()) == null)
throw new NullPointerException();
CompletableFuture<Void> d = new CompletableFuture<Void>();
// 如果不是异步执行 (e = null),则调用biAccept() 方法
if (e != null || !d.biAccept(this, b, f, null)) {
BiAccept<T,U> c = new BiAccept<T,U>(e, d, this, b, f);
// 除非两者都完成,否则将c 压入this 和 b的顶栈
// (c只能用一次,因此第二次使用需要把c保证成 CoCompletion)
bipush(b, c);
c.tryFire(SYNC);
}
return d;
}
@SuppressWarnings("serial")
static final class BiRun<T,U> extends BiCompletion<T,U,Void> {
Runnable fn;
BiRun(Executor executor, CompletableFuture<Void> dep,
CompletableFuture<T> src,
CompletableFuture<U> snd,
Runnable fn) {
super(executor, dep, src, snd); this.fn = fn;
}
final CompletableFuture<Void> tryFire(int mode) {
CompletableFuture<Void> d;
CompletableFuture<T> a;
CompletableFuture<U> b;
// dep = null 说明任务已经执行过了,直接返回,因为完成的线程会执行后续的操作;
// mode > 0, 判断是否是 ASYNC; biRun()若已知任务已完成,返回true,否则返回false。
if ((d = dep) == null ||
!d.biRun(a = src, b = snd, fn, mode > 0 ? null : this))
return null;
// 任务执行完成,clean
dep = null; src = null; snd = null; fn = null;
// 任务完成后进行后置处理
return d.postFire(a, b, mode);
}
}
final boolean biRun(CompletableFuture<?> a, CompletableFuture<?> b,
Runnable f, BiRun<?,?> c) {
Object r, s; Throwable x;
// a、b只要一个未完成,或者f = null,即返回false
// 当存在竞争时,a、b、f都可能为null
if (a == null || (r = a.result) == null ||
b == null || (s = b.result) == null || f == null)
return false;
// 若 result != null,则任务已经完成,返回true
// (当存在竞争时,可能两个线程都返回true,一个执行了任务,一个判断result != null)
if (result == null) {
if (r instanceof AltResult && (x = ((AltResult)r).ex) != null)
// a异常了,设置 this的结果为异常
completeThrowable(x, r);
else if (s instanceof AltResult && (x = ((AltResult)s).ex) != null)
// b异常了,设置 this的结果为异常
completeThrowable(x, s);
else
try {
// c只有当mode为ASYNC 的时候传入null,即线程池的线程正在执行任务
// claim()若线程可以同步执行任务返回true,否则返回false
if (c != null && !c.claim())
return false;
// 执行给定的函数
f.run();
// 设置结果为NIL
completeNull();
} catch (Throwable ex) {
// 设置结果为异常
completeThrowable(ex);
}
}
// 已知任务已经完成,返回true
return true;
}
private CompletableFuture<Void> biRunStage(Executor e, CompletionStage<?> o,
Runnable f) {
CompletableFuture<?> b;
// toCompletableFuture() 返回此 CompletableFuture
if (f == null || (b = o.toCompletableFuture()) == null)
throw new NullPointerException();
CompletableFuture<Void> d = new CompletableFuture<Void>();
// 如果不是异步执行 (e = null),则调用biRun() 方法
if (e != null || !d.biRun(this, b, f, null)) {
BiRun<T,?> c = new BiRun<>(e, d, this, b, f);
// 除非两者都完成,否则将c 压入this 和 b的顶栈
// (c只能用一次,因此第二次使用需要把c保证成 CoCompletion)
bipush(b, c);
c.tryFire(SYNC);
}
return d;
}
@SuppressWarnings("serial")
static final class BiRelay<T,U> extends BiCompletion<T,U,Void> { // for And
BiRelay(CompletableFuture<Void> dep,
CompletableFuture<T> src,
CompletableFuture<U> snd) {
super(null, dep, src, snd);
}
final CompletableFuture<Void> tryFire(int mode) {
CompletableFuture<Void> d;
CompletableFuture<T> a;
CompletableFuture<U> b;
// dep = null 说明任务已经执行过了,直接返回,因为完成的线程会执行后续的操作;
// biRelay()若已知任务已完成,返回true,否则返回false。
if ((d = dep) == null || !d.biRelay(a = src, b = snd))
return null;
// 任务执行完成,clean
src = null; snd = null; dep = null;
// 任务完成后进行后置处理
return d.postFire(a, b, mode);
}
}
boolean biRelay(CompletableFuture<?> a, CompletableFuture<?> b) {
Object r, s; Throwable x;
// a、b 只要有一个未完成,则返回false (即使有一个任务出现异常,也要等a、b都完成后,此任务才能完成)
if (a == null || (r = a.result) == null ||
b == null || (s = b.result) == null)
return false;
// 判断此任务未完成
if (result == null) {
if (r instanceof AltResult && (x = ((AltResult)r).ex) != null)
// a 异常了,设置结果为异常
completeThrowable(x, r);
else if (s instanceof AltResult && (x = ((AltResult)s).ex) != null)
// b 异常了,设置结果为异常
completeThrowable(x, s);
else
// a、b 都正常执行,设置结果为NIL
completeNull();
}
// 已知任务已经完成,返回true
return true;
}
// 递归构造一个completions 树
/** Recursively constructs a tree of completions. */
static CompletableFuture<Void> andTree(CompletableFuture<?>[] cfs,
int lo, int hi) {
CompletableFuture<Void> d = new CompletableFuture<Void>();
if (lo > hi) // empty
// 如果给定的cfs 是空的,则直接设置d 的结果为 NIL
d.result = NIL;
else {
// CF(r)
// / \
// 0123 4566
// / \ / \
// 01 23 45 66
// / \ / \ / \ / \
// 0 1 2 3 4 5 6 6
// 比如 lo = 0, hi = 6,则 构成的completions 树如上图所示,返回CF(r)。
// 当所有的 CompletableFuture都完成后CF(r)才会完成
CompletableFuture<?> a, b;
int mid = (lo + hi) >>> 1;
if ((a = (lo == mid ? cfs[lo] :
andTree(cfs, lo, mid))) == null ||
(b = (lo == hi ? a : (hi == mid+1) ? cfs[hi] :
andTree(cfs, mid+1, hi))) == null)
throw new NullPointerException();
if (!d.biRelay(a, b)) {
BiRelay<?,?> c = new BiRelay<>(d, a, b);
// 将c 放入a 和b 的堆栈中
a.bipush(b, c);
c.tryFire(SYNC);
}
}
return d;
}
/* ------------- Projected (Ored) BiCompletions -------------- */
// 将c 放入 this和b 的堆栈,除非有一个已经完成了。
/** Pushes completion to this and b unless either done. */
final void orpush(CompletableFuture<?> b, BiCompletion<?,?,?> c) {
if (c != null) {
// 判断 this 和 b 都未完成
while ((b == null || b.result == null) && result == null) {
// 将c 放入 this 的堆栈
if (tryPushStack(c)) {
// 判断b 未完成
if (b != null && b != this && b.result == null) {
// c 只能用一次,所以需要包装成 CoCompletion
// (如果两个都用c,只要一个修改了c.next 另一个也会被修改)
Completion q = new CoCompletion(c);
// 将q 放入 b 的堆栈
while (result == null && b.result == null &&
!b.tryPushStack(q))
// 放入堆栈失败,将c.next 设置回null
lazySetNext(q, null); // clear on failure
}
break;
}
// 放入堆栈失败,将c.next 设置回null
lazySetNext(c, null); // clear on failure 失败时进行清理
}
}
}
@SuppressWarnings("serial")
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;
}
// SYNC = 0, ASYNC = 1, NESTED = -1
final CompletableFuture<V> tryFire(int mode) {
CompletableFuture<V> d;
CompletableFuture<T> a;
CompletableFuture<U> b;
// dep = null 说明任务已经执行过了,直接返回,因为完成的线程会执行后续的操作; mode > 0, 判断是否是 ASYNC
// orApply()若已知任务已完成,返回true,否则返回false。
if ((d = dep) == null ||
!d.orApply(a = src, b = snd, fn, mode > 0 ? null : this))
return null;
// 任务执行完成,clean
dep = null; src = null; snd = null; fn = null;
// 任务完成后进行后置处理
return d.postFire(a, b, mode);
}
}
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两个都未完成,或者f = null,即返回false
// 当存在竞争时,a、b、f都可能为null
// 如果a已经完成,则取a 的结果,a 未完成才会取b的结果
if (a == null || b == null ||
((r = a.result) == null && (r = b.result) == null) || f == null)
return false;
// 若 result != null,则任务已经完成,返回true
// (当存在竞争时,可能两个线程都返回true,一个执行了任务,一个判断result != null)
tryComplete: if (result == null) {
try {
// c只有当mode为ASYNC 的时候传入null,即线程池的线程正在执行任务
// (或者非异步执行任务,第一次调用该方法时,传入null)
// claim()若线程可以同步执行任务返回true,否则返回false
if (c != null && !c.claim())
return false;
// r 优先取a的结果,a未完成,b已完成才会取b的结果
if (r instanceof AltResult) {
if ((x = ((AltResult)r).ex) != null) {
// 设置 this的结果为异常
completeThrowable(x, r);
break tryComplete;
}
r = null;
}
@SuppressWarnings("unchecked") R rr = (R) r;
// 执行给定的函数并设置结果
completeValue(f.apply(rr));
} catch (Throwable ex) {
// 设置结果为异常
completeThrowable(ex);
}
}
// 已知任务已经完成,返回true
return true;
}
private <U extends T,V> CompletableFuture<V> orApplyStage(
Executor e, CompletionStage<U> o,
Function<? super T, ? extends V> f) {
CompletableFuture<U> b;
// toCompletableFuture() 返回此 CompletableFuture
if (f == null || (b = o.toCompletableFuture()) == null)
throw new NullPointerException();
CompletableFuture<V> d = new CompletableFuture<V>();
// 如果不是异步执行 (e = null),则调用orApply() 方法
if (e != null || !d.orApply(this, b, f, null)) {
OrApply<T,U,V> c = new OrApply<T,U,V>(e, d, this, b, f);
// 将c 放入 this和b 的堆栈,除非有一个已经完成了
orpush(b, c);
c.tryFire(SYNC);
}
return d;
}
@SuppressWarnings("serial")
static final class OrAccept<T,U extends T> extends BiCompletion<T,U,Void> {
Consumer<? super T> fn;
OrAccept(Executor executor, CompletableFuture<Void> dep,
CompletableFuture<T> src,
CompletableFuture<U> snd,
Consumer<? super T> fn) {
super(executor, dep, src, snd); this.fn = fn;
}
// SYNC = 0, ASYNC = 1, NESTED = -1
final CompletableFuture<Void> tryFire(int mode) {
CompletableFuture<Void> d;
CompletableFuture<T> a;
CompletableFuture<U> b;
// dep = null 说明任务已经执行过了,直接返回,因为完成的线程会执行后续的操作; mode > 0, 判断是否是 ASYNC
// orAccept()若已知任务已完成,返回true,否则返回false。
if ((d = dep) == null ||
!d.orAccept(a = src, b = snd, fn, mode > 0 ? null : this))
return null;
// 任务执行完成,clean
dep = null; src = null; snd = null; fn = null;
// 任务完成后进行后置处理
return d.postFire(a, b, mode);
}
}
final <R,S extends R> boolean orAccept(CompletableFuture<R> a,
CompletableFuture<S> b,
Consumer<? super R> f,
OrAccept<R,S> c) {
Object r; Throwable x;
// a、b两个都未完成,或者f = null,即返回false
// 如果a已经完成,则取a 的结果,a 未完成才会取b的结果
if (a == null || b == null ||
((r = a.result) == null && (r = b.result) == null) || f == null)
return false;
// result = null 说明此任务未完成
tryComplete: if (result == null) {
try {
// c只有当mode为ASYNC 的时候传入null,即线程池的线程正在执行任务
// (或者非异步执行任务,第一次调用该方法时,传入null)
// claim()若线程可以同步执行任务返回true,否则返回false
if (c != null && !c.claim())
return false;
// r 优先取a的结果,a未完成,b已完成才会取b的结果
if (r instanceof AltResult) {
if ((x = ((AltResult)r).ex) != null) {
// 设置 this的结果为异常
completeThrowable(x, r);
break tryComplete;
}
r = null;
}
@SuppressWarnings("unchecked") R rr = (R) r;
// 执行给定的函数
f.accept(rr);
// 设置结果为NIL
completeNull();
} catch (Throwable ex) {
// 设置结果为异常
completeThrowable(ex);
}
}
// 已知任务已经完成,返回true
return true;
}
private <U extends T> CompletableFuture<Void> orAcceptStage(
Executor e, CompletionStage<U> o, Consumer<? super T> f) {
CompletableFuture<U> b;
// toCompletableFuture() 返回此 CompletableFuture
if (f == null || (b = o.toCompletableFuture()) == null)
throw new NullPointerException();
CompletableFuture<Void> d = new CompletableFuture<Void>();
// 如果不是异步执行 (e = null),则调用orAccept() 方法
if (e != null || !d.orAccept(this, b, f, null)) {
OrAccept<T,U> c = new OrAccept<T,U>(e, d, this, b, f);
// 将c 放入 this和b 的堆栈,除非有一个已经完成了
orpush(b, c);
c.tryFire(SYNC);
}
return d;
}
@SuppressWarnings("serial")
static final class OrRun<T,U> extends BiCompletion<T,U,Void> {
Runnable fn;
OrRun(Executor executor, CompletableFuture<Void> dep,
CompletableFuture<T> src,
CompletableFuture<U> snd,
Runnable fn) {
super(executor, dep, src, snd); this.fn = fn;
}
// SYNC = 0, ASYNC = 1, NESTED = -1
final CompletableFuture<Void> tryFire(int mode) {
CompletableFuture<Void> d;
CompletableFuture<T> a;
CompletableFuture<U> b;
// dep = null 说明任务已经执行过了,直接返回,因为完成的线程会执行后续的操作; mode > 0, 判断是否是 ASYNC
// orRun()若已知任务已完成,返回true,否则返回false。
if ((d = dep) == null ||
!d.orRun(a = src, b = snd, fn, mode > 0 ? null : this))
return null;
// 任务执行完成,clean
dep = null; src = null; snd = null; fn = null;
// 任务完成后进行后置处理
return d.postFire(a, b, mode);
}
}
final boolean orRun(CompletableFuture<?> a, CompletableFuture<?> b,
Runnable f, OrRun<?,?> c) {
Object r; Throwable x;
// a、b两个都未完成,或者f = null,即返回false
// 如果a已经完成,则取a 的结果,a 未完成才会取b的结果
if (a == null || b == null ||
((r = a.result) == null && (r = b.result) == null) || f == null)
return false;
// result = null 说明此任务未完成
if (result == null) {
try {
// c只有当mode为ASYNC 的时候传入null,即线程池的线程正在执行任务
// (或者非异步执行任务,第一次调用该方法时,传入null)
// claim()若线程可以同步执行任务返回true,否则返回false
if (c != null && !c.claim())
return false;
if (r instanceof AltResult && (x = ((AltResult)r).ex) != null)
// 设置 this的结果为异常
completeThrowable(x, r);
else {
// 执行给定的函数
f.run();
// 设置结果为NIL
completeNull();
}
} catch (Throwable ex) {
// 设置结果为异常
completeThrowable(ex);
}
}
// 已知任务已经完成,返回true
return true;
}
private CompletableFuture<Void> orRunStage(Executor e, CompletionStage<?> o,
Runnable f) {
CompletableFuture<?> b;
// toCompletableFuture() 返回此 CompletableFuture
if (f == null || (b = o.toCompletableFuture()) == null)
throw new NullPointerException();
CompletableFuture<Void> d = new CompletableFuture<Void>();
// 如果不是异步执行 (e = null),则调用orRun() 方法
if (e != null || !d.orRun(this, b, f, null)) {
OrRun<T,?> c = new OrRun<>(e, d, this, b, f);
// 将c 放入 this和b 的堆栈,除非有一个已经完成了
orpush(b, c);
c.tryFire(SYNC);
}
return d;
}
@SuppressWarnings("serial")
static final class OrRelay<T,U> extends BiCompletion<T,U,Object> { // for Or
OrRelay(CompletableFuture<Object> dep, CompletableFuture<T> src,
CompletableFuture<U> snd) {
super(null, dep, src, snd);
}
final CompletableFuture<Object> tryFire(int mode) {
CompletableFuture<Object> d;
CompletableFuture<T> a;
CompletableFuture<U> b;
// dep = null 说明任务已经执行过了,直接返回,因为完成的线程会执行后续的操作;
// orRelay()若已知任务已完成,返回true,否则返回false。
if ((d = dep) == null || !d.orRelay(a = src, b = snd))
return null;
// 任务执行完成,clean
src = null; snd = null; dep = null;
// 任务完成后进行后置处理
return d.postFire(a, b, mode);
}
}
final boolean orRelay(CompletableFuture<?> a, CompletableFuture<?> b) {
Object r;
// 若a 和 b 都未完成,返回false
// 如果a已经完成,则取a 的结果,a 未完成才会取b的结果
if (a == null || b == null ||
((r = a.result) == null && (r = b.result) == null))
return false;
if (result == null) {
// 若未设置此任务结果,则设置结果
completeRelay(r);
}
// 已知任务已经完成,返回true
return true;
}
// 递归构造一个completions 树
/** Recursively constructs a tree of completions. */
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;
// CF(r)
// / \
// CF(0) CF(1)
// / \ / \
// cfs[0] cfs[1] cfs[2] cfs[3]
// CF: CompletableFuture,创建completions 树后返回CF(r)。如果不是使用这样形式的,而是
// 把d 放到每个元素的堆栈,那么d 只能使用一次,其他需要使用 CoCompletion(d)
// 若 lo = hi,则 a = b.
// 若 lo = 1,hi = 2,则 mid = 1 ==> a = cfs[1]; b = cfs[2]
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();
// a 可能等于 b
// orRelay() 若已知任务已经完成,返回true,否则返回false
if (!d.orRelay(a, b)) {
OrRelay<?,?> c = new OrRelay<>(d, a, b);
// 将c 放入 a和b 的堆栈,除非有一个已经完成了
a.orpush(b, c);
c.tryFire(SYNC);
}
}
return d;
}
// 没有输入的异步形式
/* ------------- Zero-input Async forms -------------- */
@SuppressWarnings("serial")
static final class AsyncSupply<T> extends ForkJoinTask<Void>
implements Runnable, AsynchronousCompletionTask {
// dep -> dependant
CompletableFuture<T> dep; Supplier<T> fn;
AsyncSupply(CompletableFuture<T> dep, Supplier<T> fn) {
this.dep = dep; this.fn = fn;
}
// ForkJoinTask定义的方法
public final Void getRawResult() { return null; }
public final void setRawResult(Void v) {}
// ForkJoinPool执行此方法
public final boolean exec() { run(); return true; }
// 如果不是ForkJoinPool,则执行run()方法
public void run() {
CompletableFuture<T> d; Supplier<T> f;
if ((d = dep) != null && (f = fn) != null) {
// 设置 dep、 fn 为null,help gc
dep = null; fn = null;
if (d.result == null) {
try {
// f.get() 执行任务, 并使用CAS设置结果值result
d.completeValue(f.get());
} catch (Throwable ex) {
// 保存异常,并将异常封装到AltResult
d.completeThrowable(ex);
}
}
// 调用后续的依赖操作
d.postComplete();
}
}
}
static <U> CompletableFuture<U> asyncSupplyStage(Executor e,
Supplier<U> f) {
if (f == null) throw new NullPointerException();
CompletableFuture<U> d = new CompletableFuture<U>();
// 将 f进行封装
e.execute(new AsyncSupply<U>(d, f));
return d;
}
@SuppressWarnings("serial")
static final class AsyncRun extends ForkJoinTask<Void>
implements Runnable, AsynchronousCompletionTask {
CompletableFuture<Void> dep; Runnable fn;
AsyncRun(CompletableFuture<Void> dep, Runnable fn) {
this.dep = dep; this.fn = fn;
}
// 实现ForkJoinTask 抽象方法
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();
// 设置result 为NIL (AltResult)
d.completeNull();
} catch (Throwable ex) {
// 把异常封装到AltResult,并设置result
d.completeThrowable(ex);
}
}
// 调用后续的依赖操作
d.postComplete();
}
}
}
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;
}
/* ------------- Signallers -------------- */
/**
* 用于记录并释放一个等待的线程的Completion。
* Completion for recording and releasing a waiting thread. This
* 这个类实现了ManagedBlocker,以避免阻塞操作在forkjoinpool中堆积时出现饥饿。
* class implements ManagedBlocker to avoid starvation when
* blocking actions pile up in ForkJoinPools.
*/
@SuppressWarnings("serial")
static final class Signaller extends Completion
implements ForkJoinPool.ManagedBlocker {
// 定时的等待时间
long nanos; // wait time if timed
// 如果是定时的,非0
final long deadline; // non-zero if timed
// > 0 表示可以中断, < 0 表示已中断 , 0 不接受中断
volatile int interruptControl; // > 0: interruptible, < 0: interrupted
volatile Thread thread;
Signaller(boolean interruptible, long nanos, long deadline) {
this.thread = Thread.currentThread();
// 如果接受中断,值为1,不接受中断值为0
this.interruptControl = interruptible ? 1 : 0;
this.nanos = nanos;
this.deadline = deadline;
}
// 没必要进行原子声明,因为只会有一个线程调用这个方法。把Signaller 放入堆栈的线程
// 不会调用 tryFire()方法,而postComplete() 通过CAS操作,只会有一个线程获取此
// Signaller对象,然后调用此Signaller对象的tryFire()方法
final CompletableFuture<?> tryFire(int ignore) {
// 没必要进行原子声明
Thread w; // no need to atomically claim
// 判断此 Signaller 未过期
if ((w = thread) != null) {
// 设置thread = null,表示此 Signaller已过期
thread = null;
// 唤醒线程
LockSupport.unpark(w);
}
// 返回null,因为Signaller没有堆栈,不会有后续操作
return null;
}
// 如果不需要阻塞,返回true
public boolean isReleasable() {
// thread = null,说明此Signaller 已过期,线程不能进入等待状态,返回true
if (thread == null)
return true;
// 检查当前线程是否已经中断,并清除中断状态
if (Thread.interrupted()) {
int i = interruptControl;
// 设置interruptControl = -1,表示线程已中断
// (修改interruptControl并没有关系,因为如果线程接受中断,那么会返回true,结束while()循环,接着
// waitingGet()方法会返回null,表示线程被中断; 如果线程不接受中断,那么线程再次被中断中断后也没必
// 要再返回true了)
interruptControl = -1;
// 判断线程是否接受中断,> 0 表示可以中断
if (i > 0)
// 若接受中断,返回true,不需要阻塞
return true;
}
// deadline非0,表示定时等待
// 如果是定时等待,并且已经超时了
if (deadline != 0L &&
(nanos <= 0L || (nanos = deadline - System.nanoTime()) <= 0L)) {
// 设置thread = null,表示此 Signaller已过期 (超时了)
thread = null;
// 超时了,返回true,表示线程不需要阻塞
return true;
}
// 返回false,表示线程需要阻塞
return false;
}
// 阻塞线程。如果不需要额外的阻塞,返回true
public boolean block() {
// 再次判断线程是否需要阻塞
if (isReleasable())
return true;
// deadline == 0L 表示一直等待,没有定时
else if (deadline == 0L)
LockSupport.park(this);
// deadline != 0L,表示定时等待,在指定的时间内进行等待
else if (nanos > 0L)
LockSupport.parkNanos(this, nanos);
// 线程被唤醒后,需要再次判断线程是否需要阻塞
return isReleasable();
}
// thread = null,则表示此Completion 已过期
final boolean isLive() { return thread != null; }
}
/**
* 在等待后返回原始结果,如果可中断并且线程被中断则返回null。
* Returns raw result after waiting, or null if interruptible and
* interrupted.
*/
// interruptible 表示线程是否接受中断
private Object waitingGet(boolean interruptible) {
Signaller q = null;
// queued 表示 q 是否已压入this 堆栈
boolean queued = false;
int spins = -1;
Object r;
// result = null 说明任务未完成
while ((r = result) == null) {
if (spins < 0)
// 判断CPU是否是多线程的
spins = (Runtime.getRuntime().availableProcessors() > 1) ?
1 << 8 : 0; // Use brief spin-wait on multiprocessors 在多处理器上使用简短的自旋等待
else if (spins > 0) {
if (ThreadLocalRandom.nextSecondarySeed() >= 0)
--spins;
}
// ----- spins = 0 ------
// 当spins = 0时,线程进入等待还需要经过3个步骤:1、创建Signaller 2、把Signaller放入堆栈 3、进入等待
else if (q == null)
q = new Signaller(interruptible, 0L, 0L);
// q 未放入堆栈,需要放入this 堆栈
else if (!queued)
// 将q 放入 this 的堆栈,成功返回true,失败返回false
queued = tryPushStack(q);
// 如果接受中断,并且线程已中断 (q.interruptControl < 0表示线程已中断)
else if (interruptible && q.interruptControl < 0) {
// 设置thread = null,即 q 已过期
q.thread = null;
// 遍历stack 并解除过期的 Completions连接。Signaller 的thread = null即表示已过期
cleanStack();
// 返回null,表示线程被中断
return null;
}
// q 未过期,并且 this 未完成
else if (q.thread != null && result == null) {
try {
// 判断线程是否应该阻塞,如果是则进入等待状态
ForkJoinPool.managedBlock(q);
} catch (InterruptedException ie) {
// 线程被中断,设置 q.interruptControl = -1
q.interruptControl = -1;
}
}
}
// ------- result != null 表示 this 已经完成了 -------
if (q != null) {
// 设置 q.thread = null,表示 q 已过期
q.thread = null;
// 判断线程是否被中断
if (q.interruptControl < 0) {
// 如果线程已被中断,且线程接受中断,则设置 r = null (返回null表示线程已被中断)
if (interruptible)
r = null; // report interruption 报告中断
else
// 线程不接受中断,重新设置中断状态
Thread.currentThread().interrupt();
}
}
// this任务完成后进行后置处理
postComplete();
// 返回结果
return r;
}
/**
* 在等待后返回原始结果,或在中断时返回null,或在超时时抛出TimeoutException。
* Returns raw result after waiting, or null if interrupted, or
* throws TimeoutException on timeout.
*/
private Object timedGet(long nanos) throws TimeoutException {
if (Thread.interrupted())
return null;
// 若给定的等待时间 <= 0 ,抛出TimeoutException
if (nanos <= 0L)
throw new TimeoutException();
// 计算超时绝对时间
long d = System.nanoTime() + nanos;
// interruptible 传入true,接受线程中断
Signaller q = new Signaller(true, nanos, d == 0L ? 1L : d); // avoid 0 避免 0,因为0表示非定时等待
boolean queued = false;
Object r;
// 我们故意不在这里进行自旋(就像waitingGet所做的那样),因为上面对nanoTime()的调用很像自旋。
// We intentionally don't spin here (as waitingGet does) because
// the call to nanoTime() above acts much like a spin.
while ((r = result) == null) { // 判断任务未完成
if (!queued)
// 将 q放入this 堆栈
queued = tryPushStack(q);
// q.interruptControl < 0 说明线程已经被中断了
// q.nanos <= 0L 说明超时了
// 线程被中断或者超时了
else if (q.interruptControl < 0 || q.nanos <= 0L) {
// 设置q.thread = null,表示q 已经过期了
q.thread = null;
// 遍历stack 并解除过期的 Completions连接
cleanStack();
if (q.interruptControl < 0)
// 如果线程被中断,返回null
return null;
// 超时,抛出TimeoutException
throw new TimeoutException();
}
// 判断q 未过期,并且 this未完成
else if (q.thread != null && result == null) {
try {
// 判断线程是否应该阻塞,如果是则阻塞该线程
ForkJoinPool.managedBlock(q);
} catch (InterruptedException ie) {
// 线程被中断,设置 q.interruptControl = -1
q.interruptControl = -1;
}
}
}
// ------- result != null 表示 this 已经完成了 -------
if (q.interruptControl < 0)
// 若线程已被中断,则设置r = null表示线程被中断
r = null;
// 设置q.thread = null,表示q 已经过期了
q.thread = null;
// 帮忙进行后置处理
postComplete();
return r;
}
/* ------------- public methods -------------- */
/**
* 创造一个新的不完整的CompletableFuture。
* Creates a new incomplete CompletableFuture.
*/
public CompletableFuture() {
}
/**
* 用给定的编码结果创建一个新的完整的CompletableFuture。
* Creates a new complete CompletableFuture with given encoded result.
*/
private CompletableFuture(Object r) {
this.result = r;
}
/**
* 返回一个新的CompletableFuture,它由运行在{@link ForkJoinPool#commonPool()}中
* 的任务异步完成,该任务的值是通过调用给定的Supplier获得的。
* Returns a new CompletableFuture that is asynchronously completed
* by a task running in the {@link ForkJoinPool#commonPool()} with
* the value obtained by calling the given Supplier.
*
* @param supplier a function returning the value to be used
* to complete the returned CompletableFuture
* @param <U> the function's return type
* @return the new CompletableFuture
*/
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier) {
// 使用默认的执行器
return asyncSupplyStage(asyncPool, supplier);
}
/**
* 返回一个新的CompletableFuture,它由在给定执行器中运行的任务与通过调用给定Supplier获得的值异步完成。
* Returns a new CompletableFuture that is asynchronously completed
* by a task running in the given executor with the value obtained
* by calling the given Supplier.
*
* @param supplier a function returning the value to be used
* to complete the returned CompletableFuture
* @param executor the executor to use for asynchronous execution
* @param <U> the function's return type
* @return the new CompletableFuture
*/
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier,
Executor executor) {
// screenExecutor(executor) 检查执行器是否为null,若执行器是common池,则在禁用并行的情况下转换为asyncPool
return asyncSupplyStage(screenExecutor(executor), supplier);
}
/**
* 返回一个新的CompletableFuture,它在运行给定操作后由运行在 ForkJoinPool.commonPool()中的任务 异步完成。
* Returns a new CompletableFuture that is asynchronously completed
* by a task running in the {@link ForkJoinPool#commonPool()} after
* it runs the given action.
*
* @param runnable the action to run before completing the
* returned CompletableFuture
* @return the new CompletableFuture
*/
public static CompletableFuture<Void> runAsync(Runnable runnable) {
return asyncRunStage(asyncPool, runnable);
}
/**
* 返回一个新的CompletableFuture,它在运行给定操作之后由在给定执行程序中运行的任务异步完成。
* Returns a new CompletableFuture that is asynchronously completed
* by a task running in the given executor after it runs the given
* action.
*
* @param runnable the action to run before completing the
* returned CompletableFuture
* @param executor the executor to use for asynchronous execution
* @return the new CompletableFuture
*/
public static CompletableFuture<Void> runAsync(Runnable runnable,
Executor executor) {
// screenExecutor() 筛选执行器,若为null抛出异常
return asyncRunStage(screenExecutor(executor), runnable);
}
/**
* 返回已经使用给定值完成的新的CompletableFuture。
* Returns a new CompletableFuture that is already completed with
* the given value.
*
* @param value the value
* @param <U> the type of the value
* @return the completed CompletableFuture
*/
public static <U> CompletableFuture<U> completedFuture(U value) {
return new CompletableFuture<U>((value == null) ? NIL : value);
}
/**
* 如果以任何方式完成,返回{@code true}:正常,异常,或通过取消。
* Returns {@code true} if completed in any fashion: normally,
* exceptionally, or via cancellation.
*
* @return {@code true} if completed
*/
public boolean isDone() {
return result != null;
}
/**
* 如果需要,则等待这个future完成,然后返回它的结果。
* Waits if necessary for this future to complete, and then
* returns its result.
*
* @return the result value
* @throws CancellationException if this future was cancelled
* @throws ExecutionException if this future completed exceptionally
* @throws InterruptedException if the current thread was interrupted
* while waiting
*/
public T get() throws InterruptedException, ExecutionException {
Object r;
// result = null,说明此future 未完成,等待其完成并获取结果
return reportGet((r = result) == null ? waitingGet(true) : r);
}
/**
* 如果有必要,将等待这个future的完成,最多等待给定的时间,然后返回它的结果(如果可用)。
* Waits if necessary for at most the given time for this future
* to complete, and then returns its result, if available.
*
* @param timeout the maximum time to wait
* @param unit the time unit of the timeout argument
* @return the result value
* @throws CancellationException if this future was cancelled
* @throws ExecutionException if this future completed exceptionally
* @throws InterruptedException if the current thread was interrupted
* while waiting
* @throws TimeoutException if the wait timed out
*/
public T get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException {
Object r;
// 将时间转成纳秒
long nanos = unit.toNanos(timeout);
// 若任务未完成,调用 timedGet()方法定时等待任务完成
return reportGet((r = result) == null ? timedGet(nanos) : r);
}
/**
* 在完成时返回结果值,或者在异常完成时抛出(未检查的)异常。
* Returns the result value when complete, or throws an
* (unchecked) exception if completed exceptionally. To better
* 为了更好地符合通用函数形式的使用,如果完成此CompletableFuture涉及的计算抛出异常,
* 该方法将抛出一个(未检查的){@link CompletionException},并将底层异常作为其原因。
* conform with the use of common functional forms, if a
* computation involved in the completion of this
* CompletableFuture threw an exception, this method throws an
* (unchecked) {@link CompletionException} with the underlying
* exception as its cause.
*
* @return the result value
* @throws CancellationException if the computation was cancelled
* @throws CompletionException if this future completed
* exceptionally or a completion computation threw an exception
*/
// 任务执行异常reportJoin()抛出CompletionException,而reportGet()抛出的是ExecutionException异常
public T join() {
Object r;
// 如果任务还未完成,则等待任务完成,线程不接受中断,因此waitingGet() 不会返回null
return reportJoin((r = result) == null ? waitingGet(false) : r);
}
/**
* 如果已完成,则返回结果值(或抛出任何遇到的异常),否则返回给定的值IfAbsent。
* Returns the result value (or throws any encountered exception)
* if completed, else returns the given valueIfAbsent.
*
* @param valueIfAbsent the value to return if not completed 如果没有完成,返回的值
* @return the result value, if completed, else the given valueIfAbsent
* @throws CancellationException if the computation was cancelled
* @throws CompletionException if this future completed
* exceptionally or a completion computation threw an exception
*/
public T getNow(T valueIfAbsent) {
Object r;
// 若任务未完成,返回 valueIfAbsent
return ((r = result) == null) ? valueIfAbsent : reportJoin(r);
}
/**
* 如果尚未完成,则将{@link #get()}和相关方法返回的值设置为给定值。
* If not already completed, sets the value returned by {@link
* #get()} and related methods to the given value.
*
* @param value the result value
* @return {@code true} if this invocation caused this CompletableFuture
* to transition to a completed state, else {@code false}
*/
public boolean complete(T value) {
// 使用CAS设置结果,如果value = null,则设置为NIL。返回是否设置成功
boolean triggered = completeValue(value);
// 如果设置失败,说明此任务已经完成了,因此也可以进行完成后的后置处理
postComplete();
return triggered;
}
/**
* 如果尚未完成,将导致{@link #get()}和相关方法的调用抛出给定的异常。
* If not already completed, causes invocations of {@link #get()}
* and related methods to throw the given exception.
*
* @param ex the exception
* @return {@code true} if this invocation caused this CompletableFuture
* to transition to a completed state, else {@code false}
*/
public boolean completeExceptionally(Throwable ex) {
if (ex == null) throw new NullPointerException();
// 把ex 封装到AltResult,然后使用CAS设置 result,返回是否设置成功
boolean triggered = internalComplete(new AltResult(ex));
// 如果设置失败,说明此任务已经完成了,因此也可以进行完成后的后置处理
postComplete();
return triggered;
}
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);
}
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);
}
public CompletableFuture<Void> thenRun(Runnable action) {
// 返回一个新的CompletableFuture,当此阶段正常完成时,执行给定的操作。
return uniRunStage(null, action);
}
public CompletableFuture<Void> thenRunAsync(Runnable action) {
// 此操作完成后使用默认的执行器异步执行给定的函数
return uniRunStage(asyncPool, action);
}
public CompletableFuture<Void> thenRunAsync(Runnable action,
Executor executor) {
// 此操作完成后使用给定的执行器异步执行给定的函数
return uniRunStage(screenExecutor(executor), action);
}
public <U,V> CompletableFuture<V> thenCombine(
CompletionStage<? extends U> other,
BiFunction<? super T,? super U,? extends V> fn) {
// 返回一个新的CompletionStage,当这个和另一个给定的阶段都正常完成时,
// 两个结果作为提供函数的参数执行。
return biApplyStage(null, other, fn);
}
public <U,V> CompletableFuture<V> thenCombineAsync(
CompletionStage<? extends U> other,
BiFunction<? super T,? super U,? extends V> fn) {
// 返回一个新的CompletionStage,当这个和另一个给定阶段正常完成时,将使用
// 此阶段的默认异步执行工具执行,使用两个结果作为提供函数的参数。
return biApplyStage(asyncPool, other, fn);
}
public <U,V> CompletableFuture<V> thenCombineAsync(
CompletionStage<? extends U> other,
BiFunction<? super T,? super U,? extends V> fn, Executor executor) {
// 返回一个新的CompletionStage,当这个和另一个给定阶段正常完成时,
// 使用提供的执行器执行,使用两个结果作为提供的函数的参数
return biApplyStage(screenExecutor(executor), other, fn);
}
public <U> CompletableFuture<Void> thenAcceptBoth(
CompletionStage<? extends U> other,
BiConsumer<? super T, ? super U> action) {
// 返回一个新的CompletionStage,当这个和另一个给定的阶段都正常完成时,
// 两个结果作为提供的操作的参数被执行。
return biAcceptStage(null, other, action);
}
public <U> CompletableFuture<Void> thenAcceptBothAsync(
CompletionStage<? extends U> other,
BiConsumer<? super T, ? super U> action) {
// 返回一个新的CompletionStage,当这个和另一个给定阶段正常完成时,
// 将使用此阶段的默认异步执行工具执行,其中两个结果作为提供的操作的参数
return biAcceptStage(asyncPool, other, action);
}
public <U> CompletableFuture<Void> thenAcceptBothAsync(
CompletionStage<? extends U> other,
BiConsumer<? super T, ? super U> action, Executor executor) {
// 返回一个新的CompletionStage,当这个和另一个给定阶段正常完成时,
// 使用提供的执行器执行,其中两个结果作为提供的函数的参数。
return biAcceptStage(screenExecutor(executor), other, action);
}
public CompletableFuture<Void> runAfterBoth(CompletionStage<?> other,
Runnable action) {
// 返回一个新的CompletionStage,当这个和另一个给定的阶段都正常完成时,
// 执行给定的动作
return biRunStage(null, other, action);
}
public CompletableFuture<Void> runAfterBothAsync(CompletionStage<?> other,
Runnable action) {
// 返回一个新的CompletionStage,当这个和另一个给定阶段正常完成时,
// 使用此阶段的默认异步执行工具执行给定的操作。
return biRunStage(asyncPool, other, action);
}
public CompletableFuture<Void> runAfterBothAsync(CompletionStage<?> other,
Runnable action,
Executor executor) {
// 返回一个新的CompletionStage,当这个和另一个给定阶段正常完成时,
// 使用提供的执行器执行给定的操作
return biRunStage(screenExecutor(executor), other, action);
}
public <U> CompletableFuture<U> applyToEither(
CompletionStage<? extends T> other, Function<? super T, U> fn) {
// 返回一个新的CompletionStage,当这个或另一个给定阶段正常完成时,
// 使用相应的结果作为参数,执行提供的函数。
return orApplyStage(null, other, fn);
}
public <U> CompletableFuture<U> applyToEitherAsync(
CompletionStage<? extends T> other, Function<? super T, U> fn) {
// 返回一个新的CompletionStage,当这个或另一个给定阶段正常完成时,将使用
// 此阶段的默认异步执行工具执行,使用相应的结果作为提供函数的参数。
return orApplyStage(asyncPool, other, fn);
}
public <U> CompletableFuture<U> applyToEitherAsync(
CompletionStage<? extends T> other, Function<? super T, U> fn,
Executor executor) {
// 返回一个新的CompletionStage,当这个或另一个给定阶段正常完成时,
// 将使用提供的执行器执行,使用相应的结果作为提供函数的参数。
return orApplyStage(screenExecutor(executor), other, fn);
}
public CompletableFuture<Void> acceptEither(
CompletionStage<? extends T> other, Consumer<? super T> action) {
// 返回一个新的CompletionStage,当这个或另一个给定阶段正常完成时,
// 使用相应的结果作为参数执行提供的操作。
return orAcceptStage(null, other, action);
}
public CompletableFuture<Void> acceptEitherAsync(
CompletionStage<? extends T> other, Consumer<? super T> action) {
// 返回一个新的CompletionStage,当这个或另一个给定阶段正常完成时,
// 将使用此阶段的默认异步执行工具执行,使用相应的结果作为提供的函数的参数。
return orAcceptStage(asyncPool, other, action);
}
public CompletableFuture<Void> acceptEitherAsync(
CompletionStage<? extends T> other, Consumer<? super T> action,
Executor executor) {
// 返回一个新的CompletionStage,当这个或另一个给定阶段正常完成时,
// 将使用提供的执行器执行,使用相应的结果作为参数执行提供的函数。
return orAcceptStage(screenExecutor(executor), other, action);
}
public CompletableFuture<Void> runAfterEither(CompletionStage<?> other,
Runnable action) {
// 返回一个新的CompletionStage,当这个或另一个给定阶段正常完成时,执行给定的操作。
return orRunStage(null, other, action);
}
public CompletableFuture<Void> runAfterEitherAsync(CompletionStage<?> other,
Runnable action) {
// 返回一个新的CompletionStage,当这个或另一个给定阶段正常完成时,
// 使用此阶段的默认异步执行工具执行给定的操作。
return orRunStage(asyncPool, other, action);
}
public CompletableFuture<Void> runAfterEitherAsync(CompletionStage<?> other,
Runnable action,
Executor executor) {
// 返回一个新的CompletionStage,当这个或另一个给定阶段正常完成时,
// 使用提供的执行器执行给定的操作。
return orRunStage(screenExecutor(executor), other, action);
}
public <U> CompletableFuture<U> thenCompose(
Function<? super T, ? extends CompletionStage<U>> fn) {
// 返回一个新的CompletionStage,当这个阶段正常完成时,这个阶段执行的结果
// 将作为提供函数的参数执行
return uniComposeStage(null, fn);
}
public <U> CompletableFuture<U> thenComposeAsync(
Function<? super T, ? extends CompletionStage<U>> fn) {
// 返回一个新的CompletionStage,当此阶段正常完成时,将使用此阶段的默认
// 异步执行工具执行,此阶段执行的结果作为提供的函数的参数。
return uniComposeStage(asyncPool, fn);
}
public <U> CompletableFuture<U> thenComposeAsync(
Function<? super T, ? extends CompletionStage<U>> fn,
Executor executor) {
// 返回一个新的CompletionStage,当此阶段正常完成时,将使用提供的执行程序
// 执行,此阶段的结果作为提供函数的参数
return uniComposeStage(screenExecutor(executor), fn);
}
public CompletableFuture<T> whenComplete(
BiConsumer<? super T, ? super Throwable> action) {
// 返回与此阶段相同的结果或异常的新的CompletionStage,当此阶段完成时,将使用结果
//(或 null如果没有))和此阶段的异常(或 null如果没有))执行给定操作
return uniWhenCompleteStage(null, action);
}
public CompletableFuture<T> whenCompleteAsync(
BiConsumer<? super T, ? super Throwable> action) {
// 返回一个与此阶段相同结果或异常的新CompletionStage,当此阶段完成时,
// 使用此阶段的默认异步执行工具执行给定操作,结果(或 null如果没有))
// 和异常(或 null如果没有)作为参数。
return uniWhenCompleteStage(asyncPool, action);
}
public CompletableFuture<T> whenCompleteAsync(
BiConsumer<? super T, ? super Throwable> action, Executor executor) {
// 返回与此阶段相同结果或异常的新CompletionStage,当此阶段完成时,
// 使用提供的执行器执行给定的操作,使用此阶段执行的结果(或 null如果
// 没有))和异常(或 null如果没有))作为参数
return uniWhenCompleteStage(screenExecutor(executor), action);
}
public <U> CompletableFuture<U> handle(
BiFunction<? super T, Throwable, ? extends U> fn) {
// 返回一个新的CompletionStage,当此阶段正常或异常完成时,将使用此阶段
// 的结果和异常作为所提供函数的参数执行。 当完成作为参数时,使用结果(或null
// 如果没有))和此阶段的异常(或null如果没有))调用给定函数。
return uniHandleStage(null, fn);
}
public <U> CompletableFuture<U> handleAsync(
BiFunction<? super T, Throwable, ? extends U> fn) {
// 返回一个新的CompletionStage,当该阶段正常或异常完成时,将使用此阶段
// 的默认异步执行工具执行,此阶段的结果和异常作为提供函数的参数。 当完成时,
// 使用结果(或null如果没有))和此阶段的异常(或null如果没有))作为参数调用给定函数。
return uniHandleStage(asyncPool, fn);
}
public <U> CompletableFuture<U> handleAsync(
BiFunction<? super T, Throwable, ? extends U> fn, Executor executor) {
// 返回一个新的CompletionStage,当此阶段正常或异常完成时,将使用提供的执行器
// 执行提供的函数,并使用此阶段的结果和异常作为的参数。 当完成时,使用结果(或null
// 如果没有))和此阶段的异常(或null如果没有))作为参数调用给定函数。
return uniHandleStage(screenExecutor(executor), fn);
}
/**
* 返回此 CompletableFuture
* Returns this CompletableFuture.
*
* @return this CompletableFuture
*/
public CompletableFuture<T> toCompletableFuture() {
return this;
}
// not in interface CompletionStage
/**
* 返回一个新的CompletableFuture,该函数在CompletableFuture完成时完成,
* 当此阶段异常完成时,给定函数的结果使用触发该CompletableFuture完成的异常;
* Returns a new CompletableFuture that is completed when this
* CompletableFuture completes, with the result of the given
* function of the exception triggering this CompletableFuture's
* completion when it completes exceptionally; otherwise, if this
* 否则,如果此CompletableFuture正常完成,则返回的CompletableFuture也会以相同的值正常完成。
* CompletableFuture completes normally, then the returned
* CompletableFuture also completes normally with the same value.
* 注意:此功能更灵活的版本是使用whenComplete和handle方法。
* Note: More flexible versions of this functionality are
* available using methods {@code whenComplete} and {@code handle}.
*
* @param fn the function to use to compute the value of the
* returned CompletableFuture if this CompletableFuture completed
* exceptionally
* @return the new CompletableFuture
*/
public CompletableFuture<T> exceptionally(
Function<Throwable, ? extends T> fn) {
// 返回一个新的CompletionStage,当此阶段异常完成时,将以此阶段的异常作为提供函数的参数执行。
// 否则,如果此阶段正常完成,则返回的阶段也将以相同的值正常完成。
return uniExceptionallyStage(fn);
}
/* ------------- Arbitrary-arity constructions -------------- */
/**
* 返回一个新的CompletableFuture,当所有给定的CompletableFutures完成时完成。
* Returns a new CompletableFuture that is completed when all of
* the given CompletableFutures complete. If any of the given
* 如果给定的CompletableFutures中的任何一个异常完成,那么返回的CompletableFuture也会异常完成,
* 使用CompletionException保持此异常作为其原因。
* CompletableFutures complete exceptionally, then the returned
* CompletableFuture also does so, with a CompletionException
* holding this exception as its cause. Otherwise, the results,
* 否则,给定的CompletableFutures的结果(如果有的话)不会反映在返回的CompletableFuture中,
* 但是可以通过单独检查它们来获得。
* if any, of the given CompletableFutures are not reflected in
* the returned CompletableFuture, but may be obtained by
* inspecting them individually. If no CompletableFutures are
* 如果没有提供CompletableFutures,则返回一个已完成的CompletableFuture,值为null 。
* provided, returns a CompletableFuture completed with the value
* {@code null}.
*
* 这种方法的应用之一是等待完成一组独立的CompletableFutures,然后再继续执行程序,
* 如: CompletableFuture.allOf(c1, c2, c3).join();
* <p>Among the applications of this method is to await completion
* of a set of independent CompletableFutures before continuing a
* program, as in: {@code CompletableFuture.allOf(c1, c2,
* c3).join();}.
*
* @param cfs the CompletableFutures
* @return a new CompletableFuture that is completed when all of the
* given CompletableFutures complete
* @throws NullPointerException if the array or any of its elements are
* {@code null}
*/
public static CompletableFuture<Void> allOf(CompletableFuture<?>... cfs) {
return andTree(cfs, 0, cfs.length - 1);
}
/**
* 返回一个新的CompletableFuture,它在任何一个给定的CompletableFutures完成时完成,
* 使用相同的结果。
* Returns a new CompletableFuture that is completed when any of
* the given CompletableFutures complete, with the same result.
* 否则,如果它异常地完成,返回的CompletableFuture也会这样做,
* 使用CompletionException持有这个异常作为它的原因。
* Otherwise, if it completed exceptionally, the returned
* CompletableFuture also does so, with a CompletionException
* holding this exception as its cause. If no CompletableFutures
* 如果没有提供CompletableFutures,则返回一个不会完成的CompletableFuture。
* are provided, returns an incomplete CompletableFuture.
*
* @param cfs the CompletableFutures
* @return a new CompletableFuture that is completed with the
* result or exception of any of the given CompletableFutures when
* one completes
* @throws NullPointerException if the array or any of its elements are
* {@code null}
*/
// 返回的CompletableFuture在任何一个给定的CompletableFutures完成时完成,使用相应的结果。
public static CompletableFuture<Object> anyOf(CompletableFuture<?>... cfs) {
return orTree(cfs, 0, cfs.length - 1);
}
/* ------------- Control and status methods -------------- */
/**
* 如果尚未完成,则使用{@link CancellationException}完成此CompletableFuture。
* If not already completed, completes this CompletableFuture with
* a {@link CancellationException}. Dependent CompletableFutures
* 未完成的依赖CompletableFutures也将异常完成,使用CompletionException,
* 原因是这个CancellationException。
* that have not already completed will also complete
* exceptionally, with a {@link CompletionException} caused by
* this {@code CancellationException}.
*
* 此值对此实现没有影响,因为中断不用于控制处理。
* @param mayInterruptIfRunning this value has no effect in this
* implementation because interrupts are not used to control
* processing.
*
* @return {@code true} if this task is now cancelled
*/
// mayInterruptIfRunning 参数没有用
public boolean cancel(boolean mayInterruptIfRunning) {
// 若任务未完成,CAS设置结果为 CancellationException (封装成AltResult)
boolean cancelled = (result == null) &&
internalComplete(new AltResult(new CancellationException()));
// 任务完成后进行后置处理
postComplete();
// CAS 设置成功 或者 被其他线程取消了
return cancelled || isCancelled();
}
/**
* 如果此CompletableFuture在正常完成之前被取消,则返回{@code true}。
* Returns {@code true} if this CompletableFuture was cancelled
* before it completed normally.
*
* @return {@code true} if this CompletableFuture was cancelled
* before it completed normally
*/
public boolean isCancelled() {
Object r;
// 判断此任务是否被取消
return ((r = result) instanceof AltResult) &&
(((AltResult)r).ex instanceof CancellationException);
}
/**
* 如果此CompletableFuture以任何方式异常完成,则返回{@code true}。
* Returns {@code true} if this CompletableFuture completed
* exceptionally, in any way. Possible causes include
* 可能的原因包括取消、显式调用{@code completeexception}和突然终止CompletionStage操作。
* cancellation, explicit invocation of {@code
* completeExceptionally}, and abrupt termination of a
* CompletionStage action.
*
* @return {@code true} if this CompletableFuture completed
* exceptionally
*/
// 判断是否异常完成
public boolean isCompletedExceptionally() {
Object r;
return ((r = result) instanceof AltResult) && r != NIL;
}
/**
* 强制设置或重置方法{@link #get()}和相关方法随后返回的值,无论是否已经完成。
* Forcibly sets or resets the value subsequently returned by
* method {@link #get()} and related methods, whether or not
* already completed. This method is designed for use only in
* 该方法仅适用于错误恢复操作,即使在这种情况下,可以使后续的依赖completions 重新
* 建立结果而不是重写结果。
* error recovery actions, and even in such situations may result
* in ongoing dependent completions using established versus
* overwritten outcomes.
*
* @param value the completion value
*/
public void obtrudeValue(T value) {
// 设置结果为给定的值
result = (value == null) ? NIL : value;
// 调用后置处理 (因为可能还没进行过后置处理,即 result 原来的值为null)
postComplete();
}
/**
* 强制导致后续调用方法get()和相关方法抛出给定异常,无论是否已经完成
* Forcibly causes subsequent invocations of method {@link #get()}
* and related methods to throw the given exception, whether or
* not already completed. This method is designed for use only in
* 该方法仅适用于错误恢复操作,即使在这种情况下,可以使后续的依赖completions 重新
* 建立结果而不是重写结果。
* error recovery actions, and even in such situations may result
* in ongoing dependent completions using established versus
* overwritten outcomes.
*
* @param ex the exception
* @throws NullPointerException if the exception is null
*/
public void obtrudeException(Throwable ex) {
if (ex == null) throw new NullPointerException();
// 强制设置结果为给定的异常
result = new AltResult(ex);
// 调用后置处理 (因为可能还没进行过后置处理,即 result 原来的值为null)
postComplete();
}
/**
* 返回等待此CompletableFuture完成的CompletableFutures的估计数
* Returns the estimated number of CompletableFutures whose
* completions are awaiting completion of this CompletableFuture.
* 该方法设计用于监控系统状态,不用于同步控制。
* This method is designed for use in monitoring system state, not
* for synchronization control.
*
* @return the number of dependent CompletableFutures
*/
public int getNumberOfDependents() {
int count = 0;
// 遍历堆栈
for (Completion p = stack; p != null; p = p.next)
++count;
return count;
}
/**
* 返回一个标识此CompletableFuture的字符串及其完成状态。
* Returns a string identifying this CompletableFuture, as well as
* its completion state. The state, in brackets, contains the
* 括号中的状态包含字符串"Completed Normally"或字符串"Completed Exceptionally" ,
* 或字符串"Not completed"后面依赖于其完成的CompletableFutures数量(如果有)。
* String {@code "Completed Normally"} or the String {@code
* "Completed Exceptionally"}, or the String {@code "Not
* completed"} followed by the number of CompletableFutures
* dependent upon its completion, if any.
*
* @return a string identifying this CompletableFuture, as well as its state
*/
public String toString() {
Object r = result;
int count;
return super.toString() +
((r == null) ?
(((count = getNumberOfDependents()) == 0) ?
"[Not completed]" :
"[Not completed, " + count + " dependents]") :
(((r instanceof AltResult) && ((AltResult)r).ex != null) ?
"[Completed exceptionally]" :
"[Completed normally]"));
}
// Unsafe mechanics
private static final sun.misc.Unsafe UNSAFE;
private static final long RESULT;
private static final long STACK;
private static final long NEXT;
static {
try {
final sun.misc.Unsafe u;
UNSAFE = u = sun.misc.Unsafe.getUnsafe();
Class<?> k = CompletableFuture.class;
RESULT = u.objectFieldOffset(k.getDeclaredField("result"));
STACK = u.objectFieldOffset(k.getDeclaredField("stack"));
NEXT = u.objectFieldOffset
(Completion.class.getDeclaredField("next"));
} catch (Exception x) {
throw new Error(x);
}
}
}