11 CompletableFuture 源码注释

// tryFire()// 1、(d = dep) == null : 若上一阶段是异步的,completion放入堆栈后,上一阶段完成了,然后此线程// 执行tryFire() 就可能和上一阶段执行的线程产生竞争(上一阶段的线程调用postCompletion()方法,执行// 该completion的 tryFire()方法)。因此,此时dep可能为 null。// 2、如果将 completion放入上一阶段的堆栈时,刚好上一个阶段已经完成了,则压入堆栈会失败,但是由于上一...
摘要由CSDN通过智能技术生成


// 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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值