6 CountedCompleter 源码注释

本文详细解读了Java中的CountedCompleter类,这是一个用于并行计算的任务完成计数器。通过分析源码,揭示了其如何在多线程环境下协调任务执行与计数的关系,帮助理解并发编程中的协同机制。
摘要由CSDN通过智能技术生成

package java.util.concurrent;

/**
 * A ForkJoinTask ,当触发并且没有剩余的待处理操作时执行完成操作。
 * A {@link ForkJoinTask} with a completion action performed when
 * triggered and there are no remaining pending actions.
 * 总的来说,与其他形式的forkjointask相比,CountedCompleters在存在子任务停滞和阻塞的情况下更健壮,
 * 但是程序不太直观。
 * CountedCompleters are in general more robust in the
 * presence of subtask stalls and blockage than are other forms of
 * ForkJoinTasks, but are less intuitive to program.  Uses of
 * CountedCompleter的使用与其他基于完成的组件(例如CompletionHandler )的使用类似,
 * 但可能需要多个未完成的完成才能触发完成操作onCompletion(CountedCompleter) ,而不仅仅是一个。
 * CountedCompleter are similar to those of other completion based
 * components (such as {@link java.nio.channels.CompletionHandler})
 * except that multiple <em>pending</em> completions may be necessary
 * to trigger the completion action {@link #onCompletion(CountedCompleter)},
 * not just one.
 * 除非另有初始化, pending count从0开始,但也可以(原子)使用方法改变setPendingCount(int) ,
 * addToPendingCount(int)和compareAndSetPendingCount(int, int) 。
 * Unless initialized otherwise, the {@linkplain #getPendingCount pending
 * count} starts at zero, but may be (atomically) changed using
 * methods {@link #setPendingCount}, {@link #addToPendingCount}, and
 * {@link #compareAndSetPendingCount}.
 * 在调用tryComplete()时,如果待处理的行动计数不为零,则递减; 否则,执行完成操作,
 * 如果完成者本身具有completer,则该过程将继续完成。
 * Upon invocation of {@link
 * #tryComplete}, if the pending action count is nonzero, it is
 * decremented; otherwise, the completion action is performed, and if
 * this completer itself has a completer, the process is continued
 * 与相关同步组件(如Phaser和Semaphore)的情况一样 ,这些方法仅影响内部计数;
 * 他们没有建立任何进一步的内部簿记。
 * with its completer.  As is the case with related synchronization
 * components such as {@link java.util.concurrent.Phaser Phaser} and
 * {@link java.util.concurrent.Semaphore Semaphore}, these methods
 * affect only internal counts; they do not establish any further
 * internal bookkeeping. In particular, the identities of pending
 * 特别地,没有维护未完成任务的身份。 如下所示,您可以在需要时创建子类,记录一些
 * 或所有待处理任务或其结果。
 * tasks are not maintained. As illustrated below, you can create
 * subclasses that do record some or all pending tasks or their
 * results when needed.  As illustrated below, utility methods
 * 如下所示,还提供了支持定制完成遍历的实用程序方法。
 * supporting customization of completion traversals are also
 *  然而,由于CountedCompleters仅提供基本的同步机制,因此创建进一步的抽象子类
 *  来维护适合于一组相关用法的链接、字段和其他支持方法可能会很有用。
 * provided. However, because CountedCompleters provide only basic
 * synchronization mechanisms, it may be useful to create further
 * abstract subclasses that maintain linkages, fields, and additional
 * support methods appropriate for a set of related usages.
 *
 * 具体的CountedCompleter类必须定义方法compute() ,在大多数情况下(如下所示),
 * 在返回之前调用tryComplete()一次。
 * <p>A concrete CountedCompleter class must define method {@link
 * #compute}, that should in most cases (as illustrated below), invoke
 * {@code tryComplete()} once before returning. The class may also
 * 该类还可以可选地重写方法onCompletion(CountedCompleter)以在正常完成时执行动作,
 * 并且方法onExceptionalCompletion(Throwable, CountedCompleter)在任何异常时执行动作。
 * optionally override method {@link #onCompletion(CountedCompleter)}
 * to perform an action upon normal completion, and method
 * {@link #onExceptionalCompletion(Throwable, CountedCompleter)} to
 * perform an action upon any exception.
 *
 * CountedCompleter通常不会有结果,在这种情况下,它们通常被声明为CountedCompleter<Void> ,
 * 并将始终返回null作为结果值。
 * <p>CountedCompleters most often do not bear results, in which case
 * they are normally declared as {@code CountedCompleter<Void>}, and
 * will always return {@code null} as a result value.  In other cases,
 * 在其他情况下,你应该重写方法getRawResult()为 join(), invoke() ,以及相关方法提供从结果。
 * you should override method {@link #getRawResult} to provide a
 * result from {@code join(), invoke()}, and related methods.  In
 * 通常,该方法应该返回CountedCompleter对象的一个字段(或一个或多个字段的函数)的值,
 * 该对象在完成时保存结果。
 * general, this method should return the value of a field (or a
 * function of one or more fields) of the CountedCompleter object that
 * holds the result upon completion. Method {@link #setRawResult} by
 * 默认方法setRawResult(T)在CountedCompleters中不起作用。
 * default plays no role in CountedCompleters.  It is possible, but
 * 重写此方法以维护包含结果数据的其他对象或字段是可能的,但很少适用。
 * rarely applicable, to override this method to maintain other
 * objects or fields holding result data.
 *
 * 一个CountedCompleter本身不具有一个完整的(即getCompleter()返回null )
 * 可以用作这个添加的功能的常规ForkJoinTask。
 * <p>A CountedCompleter that does not itself have a completer (i.e.,
 * one for which {@link #getCompleter} returns {@code null}) can be
 * used as a regular ForkJoinTask with this added functionality.
 * 然而,任何完成者又具有另一个完成者仅用作其他计算的内部帮助器,因此其自己的任务状态
 * (如方法如ForkJoinTask.isDone()所报告)是任意的; 这种状态改变只有在明确调用complete(T) ,
 * ForkJoinTask.cancel(boolean) , ForkJoinTask.completeExceptionally(Throwable)
 * 或compute方法的异常结束后 。
 * However, any completer that in turn has another completer serves
 * only as an internal helper for other computations, so its own task
 * status (as reported in methods such as {@link ForkJoinTask#isDone})
 * is arbitrary; this status changes only upon explicit invocations of
 * {@link #complete}, {@link ForkJoinTask#cancel},
 * {@link ForkJoinTask#completeExceptionally(Throwable)} or upon
 * exceptional completion of method {@code compute}.
 * 在任何异常完成之后,如果有任何异常可能会被传递到任务的完成者(以及其完成者等),
 * 如果存在并且尚未完成。
 * Upon any
 * exceptional completion, the exception may be relayed to a task's
 * completer (and its completer, and so on), if one exists and it has
 * not otherwise already completed. Similarly, cancelling an internal
 * 同样地,取消一个内部的CountedCompleter只对该完成者有局部的影响,所以并不常用。
 * CountedCompleter has only a local effect on that completer, so is
 * not often useful.
 *
 * <p><b>Sample Usages.</b>
 *
 *        并行递归分解。CountedCompleters可能被安排在与RecursiveAction经常使用
 *        的类似的树中,尽管与设置相关的结构通常有所不同。
 * <p><b>Parallel recursive decomposition.</b> CountedCompleters may
 * be arranged in trees similar to those often used with {@link
 * RecursiveAction}s, although the constructions involved in setting
 * them up typically vary.
 * 这里,每个任务的完成者是其计算树中的父项。 即使它们需要更多的簿记,
 * CountedCompleters可能是更好的选择,当应用可能耗时的操作(不能进一步细分)对于数组或集合的每个元素;
 * Here, the completer of each task is its
 * parent in the computation tree. Even though they entail a bit more
 * bookkeeping, CountedCompleters may be better choices when applying
 * a possibly time-consuming operation (that cannot be further
 * subdivided) to each element of an array or collection; especially
 * 特别是当某些元素完成操作所需的时间与其他元素明显不同时,这可能是由于内部变化(例如I/O),
 * 也可能是由于诸如垃圾收集之类的辅助效果。
 * when the operation takes a significantly different amount of time
 * to complete for some elements than others, either because of
 * intrinsic variation (for example I/O) or auxiliary effects such as
 * garbage collection.
 * 因为CountedCompleters提供了它们自己的延续,其他线程不需要阻塞等待来执行它们。
 * Because CountedCompleters provide their own
 * continuations, other threads need not block waiting to perform
 * them.
 *
 * 例如,这是一个初始版本的类,它使用二分法递归分解将工作分成单个部分(叶子任务)。
 * <p>For example, here is an initial version of a class that uses
 * divide-by-two recursive decomposition to divide work into single
 * pieces (leaf tasks).
 * 即使将工作分解为单独的调用,基于树的技术通常比直接分支叶子任务更为可取,因为它们
 * 可以减少线程间通信并改善负载平衡。
 * Even when work is split into individual calls,
 * tree-based techniques are usually preferable to directly forking
 * leaf tasks, because they reduce inter-thread communication and
 * improve load balancing.
 * 在递归情况下,每对要完成的子任务的第二个触发其父任务的完成(因为没有执行结果组合,
 * 所以方法{@code onCompletion}的默认无操作实现没有被重写)。
 * In the recursive case, the second of each
 * pair of subtasks to finish triggers completion of its parent
 * (because no result combination is performed, the default no-op
 * implementation of method {@code onCompletion} is not overridden).
 * 静态实用程序方法设置基本任务并调用它(这里隐含地使用ForkJoinPool.commonPool() )。
 * A static utility method sets up the base task and invokes it
 * (here, implicitly using the {@link ForkJoinPool#commonPool()}).
 *
 * <pre> {@code
 * class MyOperation<E> { void apply(E e) { ... }  }
 *
 * class ForEach<E> extends CountedCompleter<Void> {
 *
 *   public static <E> void forEach(E[] array, MyOperation<E> op) {
 *     new ForEach<E>(null, array, op, 0, array.length).invoke();
 *   }
 *
 *   final E[] array; final MyOperation<E> op; final int lo, hi;
 *   ForEach(CountedCompleter<?> p, E[] array, MyOperation<E> op, int lo, int hi) {
 *     super(p);
 *     this.array = array; this.op = op; this.lo = lo; this.hi = hi;
 *   }
 *
 *   public void compute() { // version 1
 *     if (hi - lo >= 2) {
 *       int mid = (lo + hi) >>> 1;
 *       setPendingCount(2); // must set pending count before fork
 *       new ForEach(this, array, op, mid, hi).fork(); // right child
 *       new ForEach(this, array, op, lo, mid).fork(); // left child
 *     }
 *     else if (hi > lo)
 *       op.apply(array[lo]);
 *     tryComplete();
 *   }
 * }}</pre>
 *
 * 可以注意到,在递归情况下,任务在分叉它的右任务之后什么也不做,因此可以在返回之前直接调用它的左任务,
 * 从而改进这种设计。(这类似于尾部递归移除。)
 * This design can be improved by noticing that in the recursive case,
 * the task has nothing to do after forking its right task, so can
 * directly invoke its left task before returning. (This is an analog
 * of tail recursion removal.)  Also, because the task returns upon
 * 另外,因为任务在执行其左任务时返回(而不是通过调用tryComplete ),待处理的计数设置为1:
 * executing its left task (rather than falling through to invoke
 * {@code tryComplete}) the pending count is set to one:
 *
 * <pre> {@code
 * class ForEach<E> ...
 *   public void compute() { // version 2
 *     if (hi - lo >= 2) {
 *       int mid = (lo + hi) >>> 1;
 *       setPendingCount(1); // only one pending
 *       new ForEach(this, array, op, mid, hi).fork(); // right child
 *       new ForEach(this, array, op, lo, mid).compute(); // direct invoke
 *     }
 *     else {
 *       if (hi > lo)
 *         op.apply(array[lo]);
 *       tryComplete();
 *     }
 *   }
 * }</pre>
 *
 * 作为进一步的改进,请注意左边的任务甚至不需要存在。我们可以使用原始任务进行迭代,并为每个fork添加一个待处理计数,
 * 而不是创建一个新任务。
 * As a further improvement, notice that the left task need not even exist.
 * Instead of creating a new one, we can iterate using the original task,
 * and add a pending count for each fork.  Additionally, because no task
 * 另外,因为这个树中没有任务实现onCompletion(CountedCompleter)方法, tryComplete()可以替换为propagateCompletion() 。
 * in this tree implements an {@link #onCompletion(CountedCompleter)} method,
 * {@code tryComplete()} can be replaced with {@link #propagateCompletion}.
 *
 * <pre> {@code
 * class ForEach<E> ...
 *   public void compute() { // version 3
 *     int l = lo,  h = hi;
 *     while (h - l >= 2) {
 *       int mid = (l + h) >>> 1;
 *       addToPendingCount(1);
 *       new ForEach(this, array, op, mid, h).fork(); // right child
 *       h = mid;
 *     }
 *     if (h > l)
 *       op.apply(array[l]);
 *     propagateCompletion();
 *   }
 * }</pre>
 *
 * 这些类的额外改进可能需要预先计算待处理的计数,以便它们可以在构造函数中建立,
 * 专门用于叶子步骤的类,按每个重复的四个细分,而不是两个细分,并使用自适应阈值,
 * 而不是总是细分为单个元素。
 * Additional improvements of such classes might entail precomputing
 * pending counts so that they can be established in constructors,
 * specializing classes for leaf steps, subdividing by say, four,
 * instead of two per iteration, and using an adaptive threshold
 * instead of always subdividing down to single elements.
 *
 * 搜索。 CountedCompleters的树可以在数据结构的不同部分搜索一个值或属性,一旦发现结果,
 * 就会在AtomicReference中报告结果。其他线程可以轮询结果,以避免不必要的工作。
 * <p><b>Searching.</b> A tree of CountedCompleters can search for a
 * value or property in different parts of a data structure, and
 * report a result in an {@link
 * java.util.concurrent.atomic.AtomicReference AtomicReference} as
 * soon as one is found. The others can poll the result to avoid
 * 您还可以添加{@linkplain #cancel cancel}其他任务,但通常更简单、更有效的方法
 * 是让它们注意到设置了结果,如果设置了结果,则跳过进一步的处理。
 * unnecessary work. (You could additionally {@linkplain #cancel
 * cancel} other tasks, but it is usually simpler and more efficient
 * to just let them notice that the result is set and if so skip
 * further processing.)
 * 再次说明与一个数组使用完全分区(同样,在实践中,叶任务将几乎总是处理一个以上的元素):
 * Illustrating again with an array using full
 * partitioning (again, in practice, leaf tasks will almost always
 * process more than one element):
 *
 * <pre> {@code
 * class Searcher<E> extends CountedCompleter<E> {
 *   final E[] array; final AtomicReference<E> result; final int lo, hi;
 *   Searcher(CountedCompleter<?> p, E[] array, AtomicReference<E> result, int lo, int hi) {
 *     super(p);
 *     this.array = array; this.result = result; this.lo = lo; this.hi = hi;
 *   }
 *   public E getRawResult() { return result.get(); }
 *   public void compute() { // similar to ForEach version 3
 *     int l = lo,  h = hi;
 *     while (result.get() == null && h >= l) {
 *       if (h - l >= 2) {
 *         int mid = (l + h) >>> 1;
 *         addToPendingCount(1);
 *         new Searcher(this, array, result, mid, h).fork();
 *         h = mid;
 *       }
 *       else {
 *         E x = array[l];
 *         if (matches(x) && result.compareAndSet(null, x))
 *           quietlyCompleteRoot(); // root task is now joinable
 *         break;
 *       }
 *     }
 *     tryComplete(); // normally complete whether or not found
 *   }
 *   boolean matches(E e) { ... } // return true if found
 *
 *   public static <E> E search(E[] array) {
 *       return new Searcher<E>(null, array, new AtomicReference<E>(), 0, array.length).invoke();
 *   }
 * }}</pre>
 *
 * 在此示例中,以及其他任务除了compareAndSet设置常见结果之外没有其他效果,tryComplete的后续无条件tryComplete
 * 可以被设置为有条件的( if (result.get() == null) tryComplete(); ),因为一旦根任务完成,就不需要进一步的簿记管理完成。
 * In this example, as well as others in which tasks have no other
 * effects except to compareAndSet a common result, the trailing
 * unconditional invocation of {@code tryComplete} could be made
 * conditional ({@code if (result.get() == null) tryComplete();})
 * because no further bookkeeping is required to manage completions
 * once the root task completes.
 *
 * 记录子任务。 组合多个子任务结果的CountedCompleter任务通常需要在方法
 * {@link #onCompletion(CountedCompleter)}中访问这些结果。
 * <p><b>Recording subtasks.</b> CountedCompleter tasks that combine
 * results of multiple subtasks usually need to access these results
 * in method {@link #onCompletion(CountedCompleter)}. As illustrated in the following
 *  如下面的类所示(执行map-reduce的简化形式,其中映射和缩减都是类型为E ),分而治之设计
 *  的一种方法是使每个子任务记录成为兄弟,以便它可以可以在方法onCompletion访问。
 * class (that performs a simplified form of map-reduce where mappings
 * and reductions are all of type {@code E}), one way to do this in
 * divide and conquer designs is to have each subtask record its
 * sibling, so that it can be accessed in method {@code onCompletion}.
 * 这种技术适用于结合左和右结果的顺序无关紧要的减少; 有序减少需要明确的左/右指定。
 * 上述示例中可以看到其他流程图的变体。
 * This technique applies to reductions in which the order of
 * combining left and right results does not matter; ordered
 * reductions require explicit left/right designations.  Variants of
 * other streamlinings seen in the above examples may also apply.
 *
 * <pre> {@code
 * class MyMapper<E> { E apply(E v) {  ...  } }
 * class MyReducer<E> { E apply(E x, E y) {  ...  } }
 * class MapReducer<E> extends CountedCompleter<E> {
 *   final E[] array; final MyMapper<E> mapper;
 *   final MyReducer<E> reducer; final int lo, hi;
 *   MapReducer<E> sibling;
 *   E result;
 *   MapReducer(CountedCompleter<?> p, E[] array, MyMapper<E> mapper,
 *              MyReducer<E> reducer, int lo, int hi) {
 *     super(p);
 *     this.array = array; this.mapper = mapper;
 *     this.reducer = reducer; this.lo = lo; this.hi = hi;
 *   }
 *   public void compute() {
 *     if (hi - lo >= 2) {
 *       int mid = (lo + hi) >>> 1;
 *       MapReducer<E> left = new MapReducer(this, array, mapper, reducer, lo, mid);
 *       MapReducer<E> right = new MapReducer(this, array, mapper, reducer, mid, hi);
 *       left.sibling = right;
 *       right.sibling = left;
 *       setPendingCount(1); // only right is pending
 *       right.fork();
 *       left.compute();     // directly execute left
 *     }
 *     else {
 *       if (hi > lo)
 *           result = mapper.apply(array[lo]);
 *       tryComplete();
 *     }
 *   }
 *   public void onCompletion(CountedCompleter<?> caller) {
 *     if (caller != this) {
 *       MapReducer<E> child = (MapReducer<E>)caller;
 *       MapReducer<E> sib = child.sibling;
 *       if (sib == null || sib.result == null)
 *         result = child.result;
 *       else
 *         result = reducer.apply(child.result, sib.result);
 *     }
 *   }
 *   public E getRawResult() { return result; }
 *
 *   public static <E> E mapReduce(E[] array, MyMapper<E> mapper, MyReducer<E> reducer) {
 *     return new MapReducer<E>(null, array, mapper, reducer,
 *                              0, array.length).invoke();
 *   }
 * }}</pre>
 *
 * 在这里,方法{@code onCompletion}采用许多结合结果的完成设计的通用形式。
 * Here, method {@code onCompletion} takes a form common to many
 * completion designs that combine results.
 *  这种回调式方法在每个任务中触发一次,在挂起计数的两个不同上下文中的任一个中,或者当任务本身调用时
 *  其挂起的计数为零时变为零:(1),或者tryComplete时的挂起计数为零,或(2)通过任何其子任务,当
 *  它们完成并将待处理的计数递减到零时。
 * This callback-style method
 * is triggered once per task, in either of the two different contexts
 * in which the pending count is, or becomes, zero: (1) by a task
 * itself, if its pending count is zero upon invocation of {@code
 * tryComplete}, or (2) by any of its subtasks when they complete and
 * decrement the pending count to zero. The {@code caller} argument
 * {@code caller}参数区分情况。 通常,当呼叫方为this时,不需要采取任何行动。
 * 否则,可以使用调用者参数(通常通过转换)来提供要组合的值(和/或链接到其他值)。
 * distinguishes cases.  Most often, when the caller is {@code this},
 * no action is necessary. Otherwise the caller argument can be used
 * (usually via a cast) to supply a value (and/or links to other
 * values) to be combined.
 * 假设正确地使用了挂起计数,那么{@code onCompletion}中的操作将在任务及其子任务完成时发生(一次)。
 * Assuming proper use of pending counts, the
 * actions inside {@code onCompletion} occur (once) upon completion of
 * a task and its subtasks. No additional synchronization is required
 * 在此方法中不需要额外的同步来确保对此任务或其他完成任务的字段的访问的线程安全性。
 * within this method to ensure thread safety of accesses to fields of
 * this task or other completed tasks.
 *
 * 完成遍历 。如果使用onCompletion处理完成不适用或不方便,您可以使用方法firstComplete()和nextComplete()创建自定义遍历。
 * <p><b>Completion Traversals</b>. If using {@code onCompletion} to
 * process completions is inapplicable or inconvenient, you can use
 * methods {@link #firstComplete} and {@link #nextComplete} to create
 * custom traversals.  For example, to define a MapReducer that only
 * 例如,要定义一个mapreduce,它只以第三个ForEach例子的形式将右边的任务分开,
 * 完成必须沿着未完成的子任务链接协同减少,可以这样做:
 * splits out right-hand tasks in the form of the third ForEach
 * example, the completions must cooperatively reduce along
 * unexhausted subtask links, which can be done as follows:
 *
 * <pre> {@code
 * class MapReducer<E> extends CountedCompleter<E> { // version 2
 *   final E[] array; final MyMapper<E> mapper;
 *   final MyReducer<E> reducer; final int lo, hi;
 *   MapReducer<E> forks, next; // record subtask forks in list
 *   E result;
 *   MapReducer(CountedCompleter<?> p, E[] array, MyMapper<E> mapper,
 *              MyReducer<E> reducer, int lo, int hi, MapReducer<E> next) {
 *     super(p);
 *     this.array = array; this.mapper = mapper;
 *     this.reducer = reducer; this.lo = lo; this.hi = hi;
 *     this.next = next;
 *   }
 *   public void compute() {
 *     int l = lo,  h = hi;
 *     while (h - l >= 2) {
 *       int mid = (l + h) >>> 1;
 *       addToPendingCount(1);
 *       (forks = new MapReducer(this, array, mapper, reducer, mid, h, forks)).fork();
 *       h = mid;
 *     }
 *     if (h > l)
 *       result = mapper.apply(array[l]);
 *     // process completions by reducing along and advancing subtask links
 *     for (CountedCompleter<?> c = firstComplete(); c != null; c = c.nextComplete()) {
 *       for (MapReducer t = (MapReducer)c, s = t.forks;  s != null; s = t.forks = s.next)
 *         t.result = reducer.apply(t.result, s.result);
 *     }
 *   }
 *   public E getRawResult() { return result; }
 *
 *   public static <E> E mapReduce(E[] array, MyMapper<E> mapper, MyReducer<E> reducer) {
 *     return new MapReducer<E>(null, array, mapper, reducer,
 *                              0, array.length, null).invoke();
 *   }
 * }}</pre>
 *
 * <p><b>Triggers.</b> Some CountedCompleters are themselves never
 * forked, but instead serve as bits of plumbing in other designs;
 * including those in which the completion of one or more async tasks
 * triggers another async task. For example:
 *
 * <pre> {@code
 * class HeaderBuilder extends CountedCompleter<...> { ... }
 * class BodyBuilder extends CountedCompleter<...> { ... }
 * class PacketSender extends CountedCompleter<...> {
 *   PacketSender(...) { super(null, 1); ... } // trigger on second completion
 *   public void compute() { } // never called
 *   public void onCompletion(CountedCompleter<?> caller) { sendPacket(); }
 * }
 * // sample use:
 * PacketSender p = new PacketSender();
 * new HeaderBuilder(p, ...).fork();
 * new BodyBuilder(p, ...).fork();
 * }</pre>
 *
 * @since 1.8
 * @author Doug Lea
 */

/**
 * 1、CountedCompleter 类型的子任务不能调用invoke、invokeAll 方法(根任务可以),否则线程会一直等待任务完成,
 *   而叶子任务执行完成也不会设置任务状态为完成,因此会一直等待。
 *
 */
public abstract class CountedCompleter<T> extends ForkJoinTask<T> {
    private static final long serialVersionUID = 5232453752276485070L;

    /** This task's completer, or null if none */
    final CountedCompleter<?> completer;
    /** The number of pending tasks until completion */
    volatile int pending;

    /**
     * 使用给定的 completer 和 初始待完成数 创建一个新的  CountedCompleter
     * Creates a new CountedCompleter with the given completer
     * and initial pending count.
     *
     * @param completer this task's completer, or {@code null} if none
     * @param initialPendingCount the initial pending count
     */
    protected CountedCompleter(CountedCompleter<?> completer,
                               int initialPendingCount) {
        this.completer = completer;
        this.pending = initialPendingCount;
    }

    /**
     * 使用给定的completer 创建一个新的 CountedCompleter 并初始化待完成数为0
     * Creates a new CountedCompleter with the given completer
     * and an initial pending count of zero.
     *
     * @param completer this task's completer, or {@code null} if none
     */
    protected CountedCompleter(CountedCompleter<?> completer) {
        this.completer = completer;
    }

    /**
     * Creates a new CountedCompleter with no completer
     * and an initial pending count of zero.
     */
    protected CountedCompleter() {
        this.completer = null;
    }

    /**
     * 这个任务执行的主要计算。
     * The main computation performed by this task.
     */
    public abstract void compute();

    /**
     * 当方法{@link #tryComplete}被调用且未完成数为零,或者当无条件方法{@link #complete}被调用时,
     * 执行一个操作。默认情况下,这个方法不执行任何操作。
     * Performs an action when method {@link #tryComplete} is invoked
     * and the pending count is zero, or when the unconditional
     * method {@link #complete} is invoked.  By default, this method
     * does nothing.
     * 您可以通过检查给定调用方参数的标识来区分情况。如果不等于{@code this},
     * 那么它通常是一个子任务,可能包含要组合的结果(和/或 关联到其他结果)。
     * You can distinguish cases by checking the
     * identity of the given caller argument. If not equal to {@code
     * this}, then it is typically a subtask that may contain results
     * (and/or links to other results) to combine.
     *
     * 任务调用这个方法(可能为任务本身 -- this)
     * @param caller the task invoking this method (which may
     * be this task itself)
     */
    public void onCompletion(CountedCompleter<?> caller) {
    }

    /**
     * 方法ForkJoinTask.completeExceptionally(Throwable)被调用或方法compute()引发异常,
     * 并且此任务尚未正常完成时执行操作。
     * Performs an action when method {@link
     * #completeExceptionally(Throwable)} is invoked or method {@link
     * #compute} throws an exception, and this task has not already
     * otherwise completed normally. On entry to this method, this task
     *  进入这个方法,这个任务ForkJoinTask.isCompletedAbnormally() 。
     * {@link ForkJoinTask#isCompletedAbnormally}.  The return value
     * 该方法的返回值控制进一步的传播:如果true并且此任务具有尚未完成的completer,
     * 那么该completer也异常完成,与此完成者相同的异常。
     * of this method controls further propagation: If {@code true}
     * and this task has a completer that has not completed, then that
     * completer is also completed exceptionally, with the same
     * exception as this completer.  The default implementation of
     * 默认实现除了返回true,不进行任何操作。
     * this method does nothing except return {@code true}.
     *
     * @param ex the exception
     * @param caller the task invoking this method (which may
     * be this task itself)
     * @return {@code true} if this exception should be propagated to this
     * task's completer, if one exists
     */
    public boolean onExceptionalCompletion(Throwable ex, CountedCompleter<?> caller) {
        return true;
    }

    /**
     * 返回在此任务的构造函数中建立的completer,如果没有返回null
     * Returns the completer established in this task's constructor,
     * or {@code null} if none.
     *
     * @return the completer
     */
    public final CountedCompleter<?> getCompleter() {
        return completer;
    }

    /**
     * 返回当前的未完成数
     * Returns the current pending count.
     *
     * @return the current pending count
     */
    public final int getPendingCount() {
        return pending;
    }

    /**
     * 设置未完成数为给定的值
     * Sets the pending count to the given value.
     *
     * @param count the count
     */
    public final void setPendingCount(int count) {
        pending = count;
    }

    /**
     * 未完成数增加(原子地)给定的值
     * Adds (atomically) the given value to the pending count.
     *
     * @param delta the value to add
     */
    public final void addToPendingCount(int delta) {
        U.getAndAddInt(this, PENDING, delta);
    }

    /**
     * 只有在当前持有给定的期望值时,才会(原子地)将未完成数设置为给定的值。
     * Sets (atomically) the pending count to the given count only if
     * it currently holds the given expected value.
     *
     * @param expected the expected value
     * @param count the new value
     * @return {@code true} if successful
     */
    public final boolean compareAndSetPendingCount(int expected, int count) {
        return U.compareAndSwapInt(this, PENDING, expected, count);
    }

    /**
     * 如果未完成数非0,则(原子地)递减。
     * If the pending count is nonzero, (atomically) decrements it.
     *
     * @return the initial (undecremented) pending count holding on entry
     * to this method
     */
    public final int decrementPendingCountUnlessZero() {
        int c;
        do {} while ((c = pending) != 0 &&
                     !U.compareAndSwapInt(this, PENDING, c, c - 1));
        return c;
    }

    /**
     * 返回当前计算的根
     * Returns the root of the current computation; i.e., this
     * task if it has no completer, else its completer's root.
     *
     * @return the root of the current computation
     */
    public final CountedCompleter<?> getRoot() {
        CountedCompleter<?> a = this, p;
        while ((p = a.completer) != null)
            a = p;
        return a;
    }

    /**
     * 如果挂起的计数非零,则递减计数;否则调用{@link #onCompletion(CountedCompleter)},
     * 然后类似地尝试完成此任务的completer(如果存在该任务的completer),否则将此任务标记为完成。
     * If the pending count is nonzero, decrements the count;
     * otherwise invokes {@link #onCompletion(CountedCompleter)}
     * and then similarly tries to complete this task's completer,
     * if one exists, else marks this task as complete.
     */
    public final void tryComplete() {
        CountedCompleter<?> a = this, s = a;

        //                        r
        //                      /   \
        //                     b     c
        //                    / \   /  \
        //                   d   e f    g

        //  1、当任务d完成时,此时  a = s = d,调用 d.onCompletion(d)方法,传入的还是d,这种情况下
        //     onCompletion()方法一般都会判断参数是否为 this,是则不进行任何操作;
        //  2、s = d, a = a.completer = b,若任务b未完成数不为0,则任务b的未完成数递减,然后返回;
        //     若任务b的未完成数为0,则调用 b.onCompletion(d);
        //  3、s = b, a = r,循环步骤2...

        for (int c;;) {
            if ((c = a.pending) == 0) {
                // 如果为完成数为0,则调用 onCompletion()方法
                a.onCompletion(s);  // 第一次调用传入的是 this,继续调用传入的则是其子任务
                if ((a = (s = a).completer) == null) {
                    // 已经到达根节点任务了,此时所有任务都已经完成了,设置根节点任务的状态为 NORMAL
                    s.quietlyComplete();
                    return;
                }
            }
            // a 可能是this,也可能是其父节点任务,当子任务完成时,若其负节点任务未完成为0,则调用
            // 父节点任务的 onCompletion()方法,并传入其子任务,若父节点任务未完成,则未完成数递减
            else if (U.compareAndSwapInt(a, PENDING, c, c - 1))
                return;
        }
    }

    /**
     * 相当于{@link #tryComplete},但不调用{@link #onCompletion(CountedCompleter)}:
     * Equivalent to {@link #tryComplete} but does not invoke {@link
     * #onCompletion(CountedCompleter)} along the completion path:
     * 如果挂起的计数非零,则递减计数; 然后类似地尝试完成此任务的completer(如果存在该任务的completer),
     * 否则则将此任务标记为完成。
     * If the pending count is nonzero, decrements the count;
     * otherwise, similarly tries to complete this task's completer, if
     * one exists, else marks this task as complete. This method may be
     * 在不应该或不需要为计算中的每个完成者调用{@code onCompletion}的情况下,此方法可能很有用。
     * useful in cases where {@code onCompletion} should not, or need
     * not, be invoked for each completer in a computation.
     */
    public final void propagateCompletion() {
        CountedCompleter<?> a = this, s = a;
        for (int c;;) {
            if ((c = a.pending) == 0) {
                // pending = 0,向上传播其完成
                if ((a = (s = a).completer) == null) {
                    // 已经到达根节点任务了,此时所有任务都已经完成了,设置根节点任务的状态为 NORMAL
                    s.quietlyComplete();
                    return;
                }
            }
            // pending 不为0,递减
            else if (U.compareAndSwapInt(a, PENDING, c, c - 1))
                return;
        }
    }

    /**
     * 不管未完成数,调用onCompletion(CountedCompleter) ,将此任务标记为完成,
     * 并进一步触发此任务的completer 的tryComplete()(如果存在)。
     * Regardless of pending count, invokes
     * {@link #onCompletion(CountedCompleter)}, marks this task as
     * complete and further triggers {@link #tryComplete} on this
     * task's completer, if one exists.  The given rawResult is
     * 在调用onCompletion(CountedCompleter)或标记这个任务已完成之前,
     * 给定rawResult作为参数传递给setRawResult(T);这个值只对重写了setRawResult()
     * 方法的类有效。
     * used as an argument to {@link #setRawResult} before invoking
     * {@link #onCompletion(CountedCompleter)} or marking this task
     * as complete; its value is meaningful only for classes
     * overriding {@code setRawResult}.  This method does not modify
     * 这个方法不会修改未完成数。
     * the pending count.
     *
     * 当一些子任务中的任何一个任务获取结果时,强制完成,此方法可能非常有用。
     * <p>This method may be useful when forcing completion as soon as
     * any one (versus all) of several subtask results are obtained.
     * 但是,在不重写{@code setRawResult}的常见(也是推荐的)情况下,
     * 使用{@code quietlyCompleteRoot();}可以更简单地获得这种效果。
     * However, in the common (and recommended) case in which {@code
     * setRawResult} is not overridden, this effect can be obtained
     * more simply using {@code quietlyCompleteRoot();}.
     *
     * @param rawResult the raw result
     */
    // 在不重写setRawResult(rawResult)方法的情况下,使用 quietlyCompleteRoot()
    // 注意:此方法不修改未完成数
    public void complete(T rawResult) {
        CountedCompleter<?> p;

        // 设置结果,只对重写了这个方法的类有效果
        setRawResult(rawResult);

        // 调用onCompletion(this)
        onCompletion(this);

        // 设置任务状态为 NORMAL
        quietlyComplete();

        // 如果有completer,则调用completer的 tryComplete()方法,传播任务完成
        if ((p = completer) != null)
            p.tryComplete();
    }

    /**
     * 如果这个任务的未完成数为0,则返回这个任务;
     * If this task's pending count is zero, returns this task;
     * 否则,递减其未完成数,并返回null。
     * otherwise decrements its pending count and returns {@code
     * 此方法被设计为在完成遍历循环中与{@link #nextComplete}一起使用。
     * null}. This method is designed to be used with {@link
     * #nextComplete} in completion traversal loops.
     *
     * @return this task, if pending count was zero, else {@code null}
     */
    public final CountedCompleter<?> firstComplete() {
        for (int c;;) {
            if ((c = pending) == 0)
                return this;
            else if (U.compareAndSwapInt(this, PENDING, c, c - 1))
                return null;
        }
    }

    /**
     * 如果此任务没有completer,调用ForkJoinTask.quietlyComplete()并返回null 。
     * If this task does not have a completer, invokes {@link
     * ForkJoinTask#quietlyComplete} and returns {@code null}.  Or, if
     * 或者,如果completer的未完成数不为零,则递减未完成数,并返回null 。
     * 否则,返回completer。
     * the completer's pending count is non-zero, decrements that
     * pending count and returns {@code null}.  Otherwise, returns the
     * completer.  This method can be used as part of a completion
     * 此方法可用于同构任务层次结构的完成遍历循环的一部分:
     * traversal loop for homogeneous task hierarchies:
     *
     * <pre> {@code
     * for (CountedCompleter<?> c = firstComplete();
     *      c != null;
     *      c = c.nextComplete()) {
     *   // ... process c ...
     * }}</pre>
     *
     * @return the completer, or {@code null} if none
     */
    public final CountedCompleter<?> nextComplete() {
        CountedCompleter<?> p;
        if ((p = completer) != null)
            return p.firstComplete();
        else {
            // 修改根任务状态为 NORMAL (completer == null 说明是根任务)
            quietlyComplete();
            return null;
        }
    }

    /**
     * 等价于 getRoot().quietlyComplete()
     * Equivalent to {@code getRoot().quietlyComplete()}.
     */
    public final void quietlyCompleteRoot() {
        for (CountedCompleter<?> a = this, p;;) {
            // 找到根任务,并设置其状态为 NORMAL
            if ((p = a.completer) == null) {
                a.quietlyComplete();
                return;
            }
            a = p;
        }
    }

    /**
     * 如果此任务尚未完成,则尝试处理该任务位于完成路径上的其他未处理任务的给定数目(如果已知存在该任务)。
     * If this task has not completed, attempts to process at most the
     * given number of other unprocessed tasks for which this task is
     * on the completion path, if any are known to exist.
     *
     * 小于等于0,不会处理任何任务
     * @param maxTasks the maximum number of tasks to process.  If
     *                 less than or equal to zero, then no tasks are
     *                 processed.
     */
    public final void helpComplete(int maxTasks) {
        Thread t; ForkJoinWorkerThread wt;
        // status >= 0 说明任务未完成
        if (maxTasks > 0 && status >= 0) {
            if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread)
                (wt = (ForkJoinWorkerThread)t).pool.
                    helpComplete(wt.workQueue, this, maxTasks);
            else
                ForkJoinPool.common.externalHelpComplete(this, maxTasks);
        }
    }

    /**
     * 支持 ForkJoinTask 异常传播
     * Supports ForkJoinTask exception propagation.
     */
    void internalPropagateException(Throwable ex) {
        CountedCompleter<?> a = this, s = a;

        // 1、调用onExceptionalCompletion(ex, s),返回true,说明需要传播异常 (默认返回true)
        // 2、这里不需要设置this的任务状态,因为setExceptionalCompletion() 方法已经记录了异常,并设置了this的任务状态
        //    为EXCEPTIONAL,然后才调用的internalPropagateException() 方法,所以这里只需要设置this的所有父节点及以上的
        //    任务状态,并记录异常即可
        // 3、recordExceptionalCompletion记录异常,并设置状态为 EXCEPTIONAL,然后判断任务状态是否为异常
        while (a.onExceptionalCompletion(ex, s) &&
               (a = (s = a).completer) != null && a.status >= 0 &&
               a.recordExceptionalCompletion(ex) == EXCEPTIONAL)
            ;
    }

    /**
     * 实现CountedCompleters的执行约定。
     * Implements execution conventions for CountedCompleters.
     */
    protected final boolean exec() {
        compute();
        // 返回false,说明不用设置任务状态
        return false;
    }

    /**
     * 返回计算的结果。默认情况下返回null ,这适用于Void操作,
     * 但在其他情况下应该被覆盖,几乎总是返回一个在完成后保存结果的字段或函数。
     * Returns the result of the computation. By default
     * returns {@code null}, which is appropriate for {@code Void}
     * actions, but in other cases should be overridden, almost
     * always to return a field or function of a field that
     * holds the result upon completion.
     *
     * @return the result of the computation
     */
    public T getRawResult() { return null; }

    /**
     * 带有结果的CountedCompleters 可以可选地用于帮助维护结果数据的方法。 默认情况下,什么都不做。
     * A method that result-bearing CountedCompleters may optionally
     * use to help maintain result data.  By default, does nothing.
     * 不建议重写。 但是,如果覆盖此方法来更新现有对象或字段,则通常将其定义为线程安全。
     * Overrides are not recommended. However, if this method is
     * overridden to update existing objects or fields, then it must
     * in general be defined to be thread-safe.
     */
    // 不建议重写,因为一般情况下 compute()计算的结果在compute()方法里面就会进行保存。
    protected void setRawResult(T t) { }

    // Unsafe mechanics
    private static final sun.misc.Unsafe U;
    private static final long PENDING;
    static {
        try {
            U = sun.misc.Unsafe.getUnsafe();
            PENDING = U.objectFieldOffset
                (CountedCompleter.class.getDeclaredField("pending"));
        } catch (Exception e) {
            throw new Error(e);
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值