ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/CountedCompleter.java
Revision: 1.55
Committed: Thu Jun 2 13:16:27 2016 UTC (8 years ago) by dl
Branch: MAIN
Changes since 1.54: +14 -11 lines
Log Message:
VarHandles conversion; pass 1

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