ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/CountedCompleter.java
Revision: 1.60
Committed: Mon Aug 29 20:08:08 2016 UTC (7 years, 9 months ago) by jsr166
Branch: MAIN
Changes since 1.59: +1 -1 lines
Log Message:
tiny wordsmithing

File Contents

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