ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/CountedCompleter.java
Revision: 1.64
Committed: Wed Apr 19 23:45:51 2017 UTC (7 years, 1 month ago) by jsr166
Branch: MAIN
Changes since 1.63: +1 -2 lines
Log Message:
Redo @link and @linkplain; one @link was pointing to the wrong poll method

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