1 /*
2  * Written by Doug Lea with assistance from members of JCP JSR-166
3  * Expert Group and released to the public domain, as explained at
4  * http://creativecommons.org/publicdomain/zero/1.0/
5  */
6 
7 package java.util.concurrent;
8 
9 /**
10  * A {@link ForkJoinTask} with a completion action performed when
11  * triggered and there are no remaining pending actions.
12  * CountedCompleters are in general more robust in the
13  * presence of subtask stalls and blockage than are other forms of
14  * ForkJoinTasks, but are less intuitive to program.  Uses of
15  * CountedCompleter are similar to those of other completion based
16  * components
17  * except that multiple <em>pending</em> completions may be necessary
18  * to trigger the completion action {@link #onCompletion(CountedCompleter)},
19  * not just one.
20  * Unless initialized otherwise, the {@linkplain #getPendingCount pending
21  * count} starts at zero, but may be (atomically) changed using
22  * methods {@link #setPendingCount}, {@link #addToPendingCount}, and
23  * {@link #compareAndSetPendingCount}. Upon invocation of {@link
24  * #tryComplete}, if the pending action count is nonzero, it is
25  * decremented; otherwise, the completion action is performed, and if
26  * this completer itself has a completer, the process is continued
27  * with its completer.  As is the case with related synchronization
28  * components such as {@link java.util.concurrent.Phaser Phaser} and
29  * {@link java.util.concurrent.Semaphore Semaphore}, these methods
30  * affect only internal counts; they do not establish any further
31  * internal bookkeeping. In particular, the identities of pending
32  * tasks are not maintained. As illustrated below, you can create
33  * subclasses that do record some or all pending tasks or their
34  * results when needed.  As illustrated below, utility methods
35  * supporting customization of completion traversals are also
36  * provided. However, because CountedCompleters provide only basic
37  * synchronization mechanisms, it may be useful to create further
38  * abstract subclasses that maintain linkages, fields, and additional
39  * support methods appropriate for a set of related usages.
40  *
41  * <p>A concrete CountedCompleter class must define method {@link
42  * #compute}, that should in most cases (as illustrated below), invoke
43  * {@code tryComplete()} once before returning. The class may also
44  * optionally override method {@link #onCompletion(CountedCompleter)}
45  * to perform an action upon normal completion, and method
46  * {@link #onExceptionalCompletion(Throwable, CountedCompleter)} to
47  * perform an action upon any exception.
48  *
49  * <p>CountedCompleters most often do not bear results, in which case
50  * they are normally declared as {@code CountedCompleter<Void>}, and
51  * will always return {@code null} as a result value.  In other cases,
52  * you should override method {@link #getRawResult} to provide a
53  * result from {@code join(), invoke()}, and related methods.  In
54  * general, this method should return the value of a field (or a
55  * function of one or more fields) of the CountedCompleter object that
56  * holds the result upon completion. Method {@link #setRawResult} by
57  * default plays no role in CountedCompleters.  It is possible, but
58  * rarely applicable, to override this method to maintain other
59  * objects or fields holding result data.
60  *
61  * <p>A CountedCompleter that does not itself have a completer (i.e.,
62  * one for which {@link #getCompleter} returns {@code null}) can be
63  * used as a regular ForkJoinTask with this added functionality.
64  * However, any completer that in turn has another completer serves
65  * only as an internal helper for other computations, so its own task
66  * status (as reported in methods such as {@link ForkJoinTask#isDone})
67  * is arbitrary; this status changes only upon explicit invocations of
68  * {@link #complete}, {@link ForkJoinTask#cancel},
69  * {@link ForkJoinTask#completeExceptionally(Throwable)} or upon
70  * exceptional completion of method {@code compute}. Upon any
71  * exceptional completion, the exception may be relayed to a task's
72  * completer (and its completer, and so on), if one exists and it has
73  * not otherwise already completed. Similarly, cancelling an internal
74  * CountedCompleter has only a local effect on that completer, so is
75  * not often useful.
76  *
77  * <p><b>Sample Usages.</b>
78  *
79  * <p><b>Parallel recursive decomposition.</b> CountedCompleters may
80  * be arranged in trees similar to those often used with {@link
81  * RecursiveAction}s, although the constructions involved in setting
82  * them up typically vary. Here, the completer of each task is its
83  * parent in the computation tree. Even though they entail a bit more
84  * bookkeeping, CountedCompleters may be better choices when applying
85  * a possibly time-consuming operation (that cannot be further
86  * subdivided) to each element of an array or collection; especially
87  * when the operation takes a significantly different amount of time
88  * to complete for some elements than others, either because of
89  * intrinsic variation (for example I/O) or auxiliary effects such as
90  * garbage collection.  Because CountedCompleters provide their own
91  * continuations, other threads need not block waiting to perform
92  * them.
93  *
94  * <p>For example, here is an initial version of a class that uses
95  * divide-by-two recursive decomposition to divide work into single
96  * pieces (leaf tasks). Even when work is split into individual calls,
97  * tree-based techniques are usually preferable to directly forking
98  * leaf tasks, because they reduce inter-thread communication and
99  * improve load balancing. In the recursive case, the second of each
100  * pair of subtasks to finish triggers completion of its parent
101  * (because no result combination is performed, the default no-op
102  * implementation of method {@code onCompletion} is not overridden).
103  * A static utility method sets up the base task and invokes it
104  * (here, implicitly using the {@link ForkJoinPool#commonPool()}).
105  *
106  * <pre> {@code
107  * class MyOperation<E> { void apply(E e) { ... }  }
108  *
109  * class ForEach<E> extends CountedCompleter<Void> {
110  *
111  *   public static <E> void forEach(E[] array, MyOperation<E> op) {
112  *     new ForEach<E>(null, array, op, 0, array.length).invoke();
113  *   }
114  *
115  *   final E[] array; final MyOperation<E> op; final int lo, hi;
116  *   ForEach(CountedCompleter<?> p, E[] array, MyOperation<E> op, int lo, int hi) {
117  *     super(p);
118  *     this.array = array; this.op = op; this.lo = lo; this.hi = hi;
119  *   }
120  *
121  *   public void compute() { // version 1
122  *     if (hi - lo >= 2) {
123  *       int mid = (lo + hi) >>> 1;
124  *       setPendingCount(2); // must set pending count before fork
125  *       new ForEach(this, array, op, mid, hi).fork(); // right child
126  *       new ForEach(this, array, op, lo, mid).fork(); // left child
127  *     }
128  *     else if (hi > lo)
129  *       op.apply(array[lo]);
130  *     tryComplete();
131  *   }
132  * }}</pre>
133  *
134  * This design can be improved by noticing that in the recursive case,
135  * the task has nothing to do after forking its right task, so can
136  * directly invoke its left task before returning. (This is an analog
137  * of tail recursion removal.)  Also, because the task returns upon
138  * executing its left task (rather than falling through to invoke
139  * {@code tryComplete}) the pending count is set to one:
140  *
141  * <pre> {@code
142  * class ForEach<E> ... {
143  *   ...
144  *   public void compute() { // version 2
145  *     if (hi - lo >= 2) {
146  *       int mid = (lo + hi) >>> 1;
147  *       setPendingCount(1); // only one pending
148  *       new ForEach(this, array, op, mid, hi).fork(); // right child
149  *       new ForEach(this, array, op, lo, mid).compute(); // direct invoke
150  *     }
151  *     else {
152  *       if (hi > lo)
153  *         op.apply(array[lo]);
154  *       tryComplete();
155  *     }
156  *   }
157  * }}</pre>
158  *
159  * As a further optimization, notice that the left task need not even exist.
160  * Instead of creating a new one, we can iterate using the original task,
161  * and add a pending count for each fork.  Additionally, because no task
162  * in this tree implements an {@link #onCompletion(CountedCompleter)} method,
163  * {@code tryComplete()} can be replaced with {@link #propagateCompletion}.
164  *
165  * <pre> {@code
166  * class ForEach<E> ... {
167  *   ...
168  *   public void compute() { // version 3
169  *     int l = lo, h = hi;
170  *     while (h - l >= 2) {
171  *       int mid = (l + h) >>> 1;
172  *       addToPendingCount(1);
173  *       new ForEach(this, array, op, mid, h).fork(); // right child
174  *       h = mid;
175  *     }
176  *     if (h > l)
177  *       op.apply(array[l]);
178  *     propagateCompletion();
179  *   }
180  * }}</pre>
181  *
182  * Additional optimizations of such classes might entail precomputing
183  * pending counts so that they can be established in constructors,
184  * specializing classes for leaf steps, subdividing by say, four,
185  * instead of two per iteration, and using an adaptive threshold
186  * instead of always subdividing down to single elements.
187  *
188  * <p><b>Searching.</b> A tree of CountedCompleters can search for a
189  * value or property in different parts of a data structure, and
190  * report a result in an {@link
191  * java.util.concurrent.atomic.AtomicReference AtomicReference} as
192  * soon as one is found. The others can poll the result to avoid
193  * unnecessary work. (You could additionally {@linkplain #cancel
194  * cancel} other tasks, but it is usually simpler and more efficient
195  * to just let them notice that the result is set and if so skip
196  * further processing.)  Illustrating again with an array using full
197  * partitioning (again, in practice, leaf tasks will almost always
198  * process more than one element):
199  *
200  * <pre> {@code
201  * class Searcher<E> extends CountedCompleter<E> {
202  *   final E[] array; final AtomicReference<E> result; final int lo, hi;
203  *   Searcher(CountedCompleter<?> p, E[] array, AtomicReference<E> result, int lo, int hi) {
204  *     super(p);
205  *     this.array = array; this.result = result; this.lo = lo; this.hi = hi;
206  *   }
207  *   public E getRawResult() { return result.get(); }
208  *   public void compute() { // similar to ForEach version 3
209  *     int l = lo, h = hi;
210  *     while (result.get() == null && h >= l) {
211  *       if (h - l >= 2) {
212  *         int mid = (l + h) >>> 1;
213  *         addToPendingCount(1);
214  *         new Searcher(this, array, result, mid, h).fork();
215  *         h = mid;
216  *       }
217  *       else {
218  *         E x = array[l];
219  *         if (matches(x) && result.compareAndSet(null, x))
220  *           quietlyCompleteRoot(); // root task is now joinable
221  *         break;
222  *       }
223  *     }
224  *     tryComplete(); // normally complete whether or not found
225  *   }
226  *   boolean matches(E e) { ... } // return true if found
227  *
228  *   public static <E> E search(E[] array) {
229  *       return new Searcher<E>(null, array, new AtomicReference<E>(), 0, array.length).invoke();
230  *   }
231  * }}</pre>
232  *
233  * In this example, as well as others in which tasks have no other
234  * effects except to {@code compareAndSet} a common result, the
235  * trailing unconditional invocation of {@code tryComplete} could be
236  * made conditional ({@code if (result.get() == null) tryComplete();})
237  * because no further bookkeeping is required to manage completions
238  * once the root task completes.
239  *
240  * <p><b>Recording subtasks.</b> CountedCompleter tasks that combine
241  * results of multiple subtasks usually need to access these results
242  * in method {@link #onCompletion(CountedCompleter)}. As illustrated in the following
243  * class (that performs a simplified form of map-reduce where mappings
244  * and reductions are all of type {@code E}), one way to do this in
245  * divide and conquer designs is to have each subtask record its
246  * sibling, so that it can be accessed in method {@code onCompletion}.
247  * This technique applies to reductions in which the order of
248  * combining left and right results does not matter; ordered
249  * reductions require explicit left/right designations.  Variants of
250  * other streamlinings seen in the above examples may also apply.
251  *
252  * <pre> {@code
253  * class MyMapper<E> { E apply(E v) {  ...  } }
254  * class MyReducer<E> { E apply(E x, E y) {  ...  } }
255  * class MapReducer<E> extends CountedCompleter<E> {
256  *   final E[] array; final MyMapper<E> mapper;
257  *   final MyReducer<E> reducer; final int lo, hi;
258  *   MapReducer<E> sibling;
259  *   E result;
260  *   MapReducer(CountedCompleter<?> p, E[] array, MyMapper<E> mapper,
261  *              MyReducer<E> reducer, int lo, int hi) {
262  *     super(p);
263  *     this.array = array; this.mapper = mapper;
264  *     this.reducer = reducer; this.lo = lo; this.hi = hi;
265  *   }
266  *   public void compute() {
267  *     if (hi - lo >= 2) {
268  *       int mid = (lo + hi) >>> 1;
269  *       MapReducer<E> left = new MapReducer(this, array, mapper, reducer, lo, mid);
270  *       MapReducer<E> right = new MapReducer(this, array, mapper, reducer, mid, hi);
271  *       left.sibling = right;
272  *       right.sibling = left;
273  *       setPendingCount(1); // only right is pending
274  *       right.fork();
275  *       left.compute();     // directly execute left
276  *     }
277  *     else {
278  *       if (hi > lo)
279  *           result = mapper.apply(array[lo]);
280  *       tryComplete();
281  *     }
282  *   }
283  *   public void onCompletion(CountedCompleter<?> caller) {
284  *     if (caller != this) {
285  *       MapReducer<E> child = (MapReducer<E>)caller;
286  *       MapReducer<E> sib = child.sibling;
287  *       if (sib == null || sib.result == null)
288  *         result = child.result;
289  *       else
290  *         result = reducer.apply(child.result, sib.result);
291  *     }
292  *   }
293  *   public E getRawResult() { return result; }
294  *
295  *   public static <E> E mapReduce(E[] array, MyMapper<E> mapper, MyReducer<E> reducer) {
296  *     return new MapReducer<E>(null, array, mapper, reducer,
297  *                              0, array.length).invoke();
298  *   }
299  * }}</pre>
300  *
301  * Here, method {@code onCompletion} takes a form common to many
302  * completion designs that combine results. This callback-style method
303  * is triggered once per task, in either of the two different contexts
304  * in which the pending count is, or becomes, zero: (1) by a task
305  * itself, if its pending count is zero upon invocation of {@code
306  * tryComplete}, or (2) by any of its subtasks when they complete and
307  * decrement the pending count to zero. The {@code caller} argument
308  * distinguishes cases.  Most often, when the caller is {@code this},
309  * no action is necessary. Otherwise the caller argument can be used
310  * (usually via a cast) to supply a value (and/or links to other
311  * values) to be combined.  Assuming proper use of pending counts, the
312  * actions inside {@code onCompletion} occur (once) upon completion of
313  * a task and its subtasks. No additional synchronization is required
314  * within this method to ensure thread safety of accesses to fields of
315  * this task or other completed tasks.
316  *
317  * <p><b>Completion Traversals</b>. If using {@code onCompletion} to
318  * process completions is inapplicable or inconvenient, you can use
319  * methods {@link #firstComplete} and {@link #nextComplete} to create
320  * custom traversals.  For example, to define a MapReducer that only
321  * splits out right-hand tasks in the form of the third ForEach
322  * example, the completions must cooperatively reduce along
323  * unexhausted subtask links, which can be done as follows:
324  *
325  * <pre> {@code
326  * class MapReducer<E> extends CountedCompleter<E> { // version 2
327  *   final E[] array; final MyMapper<E> mapper;
328  *   final MyReducer<E> reducer; final int lo, hi;
329  *   MapReducer<E> forks, next; // record subtask forks in list
330  *   E result;
331  *   MapReducer(CountedCompleter<?> p, E[] array, MyMapper<E> mapper,
332  *              MyReducer<E> reducer, int lo, int hi, MapReducer<E> next) {
333  *     super(p);
334  *     this.array = array; this.mapper = mapper;
335  *     this.reducer = reducer; this.lo = lo; this.hi = hi;
336  *     this.next = next;
337  *   }
338  *   public void compute() {
339  *     int l = lo, h = hi;
340  *     while (h - l >= 2) {
341  *       int mid = (l + h) >>> 1;
342  *       addToPendingCount(1);
343  *       (forks = new MapReducer(this, array, mapper, reducer, mid, h, forks)).fork();
344  *       h = mid;
345  *     }
346  *     if (h > l)
347  *       result = mapper.apply(array[l]);
348  *     // process completions by reducing along and advancing subtask links
349  *     for (CountedCompleter<?> c = firstComplete(); c != null; c = c.nextComplete()) {
350  *       for (MapReducer t = (MapReducer)c, s = t.forks; s != null; s = t.forks = s.next)
351  *         t.result = reducer.apply(t.result, s.result);
352  *     }
353  *   }
354  *   public E getRawResult() { return result; }
355  *
356  *   public static <E> E mapReduce(E[] array, MyMapper<E> mapper, MyReducer<E> reducer) {
357  *     return new MapReducer<E>(null, array, mapper, reducer,
358  *                              0, array.length, null).invoke();
359  *   }
360  * }}</pre>
361  *
362  * <p><b>Triggers.</b> Some CountedCompleters are themselves never
363  * forked, but instead serve as bits of plumbing in other designs;
364  * including those in which the completion of one or more async tasks
365  * triggers another async task. For example:
366  *
367  * <pre> {@code
368  * class HeaderBuilder extends CountedCompleter<...> { ... }
369  * class BodyBuilder extends CountedCompleter<...> { ... }
370  * class PacketSender extends CountedCompleter<...> {
371  *   PacketSender(...) { super(null, 1); ... } // trigger on second completion
372  *   public void compute() { } // never called
373  *   public void onCompletion(CountedCompleter<?> caller) { sendPacket(); }
374  * }
375  * // sample use:
376  * PacketSender p = new PacketSender();
377  * new HeaderBuilder(p, ...).fork();
378  * new BodyBuilder(p, ...).fork();}</pre>
379  *
380  * @since 1.8
381  * @author Doug Lea
382  */
383 public abstract class CountedCompleter<T> extends ForkJoinTask<T> {
384     private static final long serialVersionUID = 5232453752276485070L;
385 
386     /** This task's completer, or null if none */
387     final CountedCompleter<?> completer;
388     /** The number of pending tasks until completion */
389     volatile int pending;
390 
391     /**
392      * Creates a new CountedCompleter with the given completer
393      * and initial pending count.
394      *
395      * @param completer this task's completer, or {@code null} if none
396      * @param initialPendingCount the initial pending count
397      */
CountedCompleter(CountedCompleter<?> completer, int initialPendingCount)398     protected CountedCompleter(CountedCompleter<?> completer,
399                                int initialPendingCount) {
400         this.completer = completer;
401         this.pending = initialPendingCount;
402     }
403 
404     /**
405      * Creates a new CountedCompleter with the given completer
406      * and an initial pending count of zero.
407      *
408      * @param completer this task's completer, or {@code null} if none
409      */
CountedCompleter(CountedCompleter<?> completer)410     protected CountedCompleter(CountedCompleter<?> completer) {
411         this.completer = completer;
412     }
413 
414     /**
415      * Creates a new CountedCompleter with no completer
416      * and an initial pending count of zero.
417      */
CountedCompleter()418     protected CountedCompleter() {
419         this.completer = null;
420     }
421 
422     /**
423      * The main computation performed by this task.
424      */
compute()425     public abstract void compute();
426 
427     /**
428      * Performs an action when method {@link #tryComplete} is invoked
429      * and the pending count is zero, or when the unconditional
430      * method {@link #complete} is invoked.  By default, this method
431      * does nothing. You can distinguish cases by checking the
432      * identity of the given caller argument. If not equal to {@code
433      * this}, then it is typically a subtask that may contain results
434      * (and/or links to other results) to combine.
435      *
436      * @param caller the task invoking this method (which may
437      * be this task itself)
438      */
onCompletion(CountedCompleter<?> caller)439     public void onCompletion(CountedCompleter<?> caller) {
440     }
441 
442     /**
443      * Performs an action when method {@link
444      * #completeExceptionally(Throwable)} is invoked or method {@link
445      * #compute} throws an exception, and this task has not already
446      * otherwise completed normally. On entry to this method, this task
447      * {@link ForkJoinTask#isCompletedAbnormally}.  The return value
448      * of this method controls further propagation: If {@code true}
449      * and this task has a completer that has not completed, then that
450      * completer is also completed exceptionally, with the same
451      * exception as this completer.  The default implementation of
452      * this method does nothing except return {@code true}.
453      *
454      * @param ex the exception
455      * @param caller the task invoking this method (which may
456      * be this task itself)
457      * @return {@code true} if this exception should be propagated to this
458      * task's completer, if one exists
459      */
onExceptionalCompletion(Throwable ex, CountedCompleter<?> caller)460     public boolean onExceptionalCompletion(Throwable ex, CountedCompleter<?> caller) {
461         return true;
462     }
463 
464     /**
465      * Returns the completer established in this task's constructor,
466      * or {@code null} if none.
467      *
468      * @return the completer
469      */
getCompleter()470     public final CountedCompleter<?> getCompleter() {
471         return completer;
472     }
473 
474     /**
475      * Returns the current pending count.
476      *
477      * @return the current pending count
478      */
getPendingCount()479     public final int getPendingCount() {
480         return pending;
481     }
482 
483     /**
484      * Sets the pending count to the given value.
485      *
486      * @param count the count
487      */
setPendingCount(int count)488     public final void setPendingCount(int count) {
489         pending = count;
490     }
491 
492     /**
493      * Adds (atomically) the given value to the pending count.
494      *
495      * @param delta the value to add
496      */
addToPendingCount(int delta)497     public final void addToPendingCount(int delta) {
498         U.getAndAddInt(this, PENDING, delta);
499     }
500 
501     /**
502      * Sets (atomically) the pending count to the given count only if
503      * it currently holds the given expected value.
504      *
505      * @param expected the expected value
506      * @param count the new value
507      * @return {@code true} if successful
508      */
compareAndSetPendingCount(int expected, int count)509     public final boolean compareAndSetPendingCount(int expected, int count) {
510         return U.compareAndSwapInt(this, PENDING, expected, count);
511     }
512 
513     /**
514      * If the pending count is nonzero, (atomically) decrements it.
515      *
516      * @return the initial (undecremented) pending count holding on entry
517      * to this method
518      */
decrementPendingCountUnlessZero()519     public final int decrementPendingCountUnlessZero() {
520         int c;
521         do {} while ((c = pending) != 0 &&
522                      !U.compareAndSwapInt(this, PENDING, c, c - 1));
523         return c;
524     }
525 
526     /**
527      * Returns the root of the current computation; i.e., this
528      * task if it has no completer, else its completer's root.
529      *
530      * @return the root of the current computation
531      */
getRoot()532     public final CountedCompleter<?> getRoot() {
533         CountedCompleter<?> a = this, p;
534         while ((p = a.completer) != null)
535             a = p;
536         return a;
537     }
538 
539     /**
540      * If the pending count is nonzero, decrements the count;
541      * otherwise invokes {@link #onCompletion(CountedCompleter)}
542      * and then similarly tries to complete this task's completer,
543      * if one exists, else marks this task as complete.
544      */
tryComplete()545     public final void tryComplete() {
546         CountedCompleter<?> a = this, s = a;
547         for (int c;;) {
548             if ((c = a.pending) == 0) {
549                 a.onCompletion(s);
550                 if ((a = (s = a).completer) == null) {
551                     s.quietlyComplete();
552                     return;
553                 }
554             }
555             else if (U.compareAndSwapInt(a, PENDING, c, c - 1))
556                 return;
557         }
558     }
559 
560     /**
561      * Equivalent to {@link #tryComplete} but does not invoke {@link
562      * #onCompletion(CountedCompleter)} along the completion path:
563      * If the pending count is nonzero, decrements the count;
564      * otherwise, similarly tries to complete this task's completer, if
565      * one exists, else marks this task as complete. This method may be
566      * useful in cases where {@code onCompletion} should not, or need
567      * not, be invoked for each completer in a computation.
568      */
propagateCompletion()569     public final void propagateCompletion() {
570         CountedCompleter<?> a = this, s = a;
571         for (int c;;) {
572             if ((c = a.pending) == 0) {
573                 if ((a = (s = a).completer) == null) {
574                     s.quietlyComplete();
575                     return;
576                 }
577             }
578             else if (U.compareAndSwapInt(a, PENDING, c, c - 1))
579                 return;
580         }
581     }
582 
583     /**
584      * Regardless of pending count, invokes
585      * {@link #onCompletion(CountedCompleter)}, marks this task as
586      * complete and further triggers {@link #tryComplete} on this
587      * task's completer, if one exists.  The given rawResult is
588      * used as an argument to {@link #setRawResult} before invoking
589      * {@link #onCompletion(CountedCompleter)} or marking this task
590      * as complete; its value is meaningful only for classes
591      * overriding {@code setRawResult}.  This method does not modify
592      * the pending count.
593      *
594      * <p>This method may be useful when forcing completion as soon as
595      * any one (versus all) of several subtask results are obtained.
596      * However, in the common (and recommended) case in which {@code
597      * setRawResult} is not overridden, this effect can be obtained
598      * more simply using {@link #quietlyCompleteRoot()}.
599      *
600      * @param rawResult the raw result
601      */
complete(T rawResult)602     public void complete(T rawResult) {
603         CountedCompleter<?> p;
604         setRawResult(rawResult);
605         onCompletion(this);
606         quietlyComplete();
607         if ((p = completer) != null)
608             p.tryComplete();
609     }
610 
611     /**
612      * If this task's pending count is zero, returns this task;
613      * otherwise decrements its pending count and returns {@code null}.
614      * This method is designed to be used with {@link #nextComplete} in
615      * completion traversal loops.
616      *
617      * @return this task, if pending count was zero, else {@code null}
618      */
firstComplete()619     public final CountedCompleter<?> firstComplete() {
620         for (int c;;) {
621             if ((c = pending) == 0)
622                 return this;
623             else if (U.compareAndSwapInt(this, PENDING, c, c - 1))
624                 return null;
625         }
626     }
627 
628     /**
629      * If this task does not have a completer, invokes {@link
630      * ForkJoinTask#quietlyComplete} and returns {@code null}.  Or, if
631      * the completer's pending count is non-zero, decrements that
632      * pending count and returns {@code null}.  Otherwise, returns the
633      * completer.  This method can be used as part of a completion
634      * traversal loop for homogeneous task hierarchies:
635      *
636      * <pre> {@code
637      * for (CountedCompleter<?> c = firstComplete();
638      *      c != null;
639      *      c = c.nextComplete()) {
640      *   // ... process c ...
641      * }}</pre>
642      *
643      * @return the completer, or {@code null} if none
644      */
nextComplete()645     public final CountedCompleter<?> nextComplete() {
646         CountedCompleter<?> p;
647         if ((p = completer) != null)
648             return p.firstComplete();
649         else {
650             quietlyComplete();
651             return null;
652         }
653     }
654 
655     /**
656      * Equivalent to {@code getRoot().quietlyComplete()}.
657      */
quietlyCompleteRoot()658     public final void quietlyCompleteRoot() {
659         for (CountedCompleter<?> a = this, p;;) {
660             if ((p = a.completer) == null) {
661                 a.quietlyComplete();
662                 return;
663             }
664             a = p;
665         }
666     }
667 
668     /**
669      * If this task has not completed, attempts to process at most the
670      * given number of other unprocessed tasks for which this task is
671      * on the completion path, if any are known to exist.
672      *
673      * @param maxTasks the maximum number of tasks to process.  If
674      *                 less than or equal to zero, then no tasks are
675      *                 processed.
676      */
helpComplete(int maxTasks)677     public final void helpComplete(int maxTasks) {
678         Thread t; ForkJoinWorkerThread wt;
679         if (maxTasks > 0 && status >= 0) {
680             if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread)
681                 (wt = (ForkJoinWorkerThread)t).pool.
682                     helpComplete(wt.workQueue, this, maxTasks);
683             else
684                 ForkJoinPool.common.externalHelpComplete(this, maxTasks);
685         }
686     }
687 
688     /**
689      * Supports ForkJoinTask exception propagation.
690      */
internalPropagateException(Throwable ex)691     void internalPropagateException(Throwable ex) {
692         CountedCompleter<?> a = this, s = a;
693         while (a.onExceptionalCompletion(ex, s) &&
694                (a = (s = a).completer) != null && a.status >= 0 &&
695                a.recordExceptionalCompletion(ex) == EXCEPTIONAL)
696             ;
697     }
698 
699     /**
700      * Implements execution conventions for CountedCompleters.
701      */
exec()702     protected final boolean exec() {
703         compute();
704         return false;
705     }
706 
707     /**
708      * Returns the result of the computation.  By default,
709      * returns {@code null}, which is appropriate for {@code Void}
710      * actions, but in other cases should be overridden, almost
711      * always to return a field or function of a field that
712      * holds the result upon completion.
713      *
714      * @return the result of the computation
715      */
getRawResult()716     public T getRawResult() { return null; }
717 
718     /**
719      * A method that result-bearing CountedCompleters may optionally
720      * use to help maintain result data.  By default, does nothing.
721      * Overrides are not recommended. However, if this method is
722      * overridden to update existing objects or fields, then it must
723      * in general be defined to be thread-safe.
724      */
setRawResult(T t)725     protected void setRawResult(T t) { }
726 
727     // Unsafe mechanics
728     private static final sun.misc.Unsafe U = sun.misc.Unsafe.getUnsafe();
729     private static final long PENDING;
730     static {
731         try {
732             PENDING = U.objectFieldOffset
733                 (CountedCompleter.class.getDeclaredField("pending"));
734         } catch (ReflectiveOperationException e) {
735             throw new Error(e);
736         }
737     }
738 }
739