ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/CountedCompleter.java
Revision: 1.68
Committed: Mon Jan 20 15:51:54 2020 UTC (4 years, 4 months ago) by dl
Branch: MAIN
Changes since 1.67: +0 -19 lines
Log Message:
improve compatibilty for timeouts etc; increase common code paths

File Contents

# Content
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 import java.lang.invoke.MethodHandles;
10 import java.lang.invoke.VarHandle;
11
12 /**
13 * A {@link ForkJoinTask} with a completion action performed when
14 * triggered and there are no remaining pending actions.
15 * CountedCompleters are in general more robust in the
16 * 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 * components (such as {@link java.nio.channels.CompletionHandler})
20 * except that multiple <em>pending</em> completions may be necessary
21 * to trigger the completion action {@link #onCompletion(CountedCompleter)},
22 * not just one.
23 * 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 * #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 * with its completer. As is the case with related synchronization
31 * components such as {@link Phaser} and {@link Semaphore}, these methods
32 * 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 * subclasses that do record some or all pending tasks or their
36 * 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 * synchronization mechanisms, it may be useful to create further
40 * abstract subclasses that maintain linkages, fields, and additional
41 * support methods appropriate for a set of related usages.
42 *
43 * <p>A concrete CountedCompleter class must define method {@link
44 * #compute}, that should in most cases (as illustrated below), invoke
45 * {@code tryComplete()} once before returning. The class may also
46 * 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 *
51 * <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 * 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 * rarely applicable, to override this method to maintain other
61 * objects or fields holding result data.
62 *
63 * <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 * {@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 *
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 * 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 * 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 * intrinsic variation (for example I/O) or auxiliary effects such as
92 * garbage collection. Because CountedCompleters provide their own
93 * continuations, other tasks need not block waiting to perform them.
94 *
95 * <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 * (because no result combination is performed, the default no-op
103 * implementation of method {@code onCompletion} is not overridden).
104 * 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 *
110 * <pre> {@code
111 * 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 *
118 * 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 * }
131 * new Task(null, 0, array.length).invoke();
132 * }}</pre>
133 *
134 * This design can be improved by noticing that in the recursive case,
135 * the task has nothing to do after forking its right task, so can
136 * directly invoke its left task before returning. (This is an analog
137 * of tail recursion removal.) Also, 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 *
142 * <pre> {@code
143 * public void compute() {
144 * if (hi - lo >= 2) {
145 * int mid = (lo + hi) >>> 1;
146 * setPendingCount(1); // looks off by one, but correct!
147 * 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 * }}</pre>
155 *
156 * As a further optimization, notice that the left task need not even exist.
157 * Instead of creating a new one, we can continue using the original task,
158 * and add a pending count for each fork. Additionally, because no task
159 * in this tree implements an {@link #onCompletion(CountedCompleter)} method,
160 * {@code tryComplete} can be replaced with {@link #propagateCompletion}.
161 *
162 * <pre> {@code
163 * 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 * }}</pre>
173 *
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 *
186 * 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 * }
192 * }
193 * if (array.length > 0)
194 * new Task(null, 0, array.length).invoke();
195 * }}</pre>
196 *
197 * 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 *
202 * <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 * 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 * 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 * int l = lo, h = hi;
224 * 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 * }}</pre>
246 *
247 * In this example, as well as others in which tasks have no other
248 * 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 * because no further bookkeeping is required to manage completions
252 * once the root task completes.
253 *
254 * <p><b>Recording subtasks.</b> CountedCompleter tasks that combine
255 * results of multiple subtasks usually need to access these results
256 * in method {@link #onCompletion(CountedCompleter)}. As illustrated in the following
257 * 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 * 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 *
266 * <pre> {@code
267 * class MyMapper<E> { E apply(E v) { ... } }
268 * class MyReducer<E> { E apply(E x, E y) { ... } }
269 * class MapReducer<E> extends CountedCompleter<E> {
270 * 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 * 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 * }
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 * }}</pre>
314 *
315 * 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 * values) to be combined. Assuming proper use of pending counts, the
326 * 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 * <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 *
339 * <pre> {@code
340 * 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 * int l = lo, h = hi;
354 * while (h - l >= 2) {
355 * int mid = (l + h) >>> 1;
356 * addToPendingCount(1);
357 * (forks = new MapReducer(this, array, mapper, reducer, mid, h, forks)).fork();
358 * 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 * for (MapReducer t = (MapReducer)c, s = t.forks; s != null; s = t.forks = s.next)
365 * 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 *
376 * <p><b>Triggers.</b> Some CountedCompleters are themselves never
377 * forked, but instead serve as bits of plumbing in other designs;
378 * including those in which the completion of one or more async tasks
379 * triggers another async task. For example:
380 *
381 * <pre> {@code
382 * class HeaderBuilder extends CountedCompleter<...> { ... }
383 * class BodyBuilder extends CountedCompleter<...> { ... }
384 * class PacketSender extends CountedCompleter<...> {
385 * PacketSender(...) { super(null, 1); ... } // trigger on second completion
386 * public void compute() { } // never called
387 * public void onCompletion(CountedCompleter<?> caller) { sendPacket(); }
388 * }
389 * // sample use:
390 * PacketSender p = new PacketSender();
391 * new HeaderBuilder(p, ...).fork();
392 * new BodyBuilder(p, ...).fork();}</pre>
393 *
394 * @since 1.8
395 * @author Doug Lea
396 */
397 public abstract class CountedCompleter<T> extends ForkJoinTask<T> {
398 private static final long serialVersionUID = 5232453752276485070L;
399
400 /** This task's completer, or null if none */
401 final CountedCompleter<?> completer;
402 /** 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 * @param completer this task's completer, or {@code null} if none
410 * @param initialPendingCount the initial pending count
411 */
412 protected CountedCompleter(CountedCompleter<?> completer,
413 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 * @param completer this task's completer, or {@code null} if none
423 */
424 protected CountedCompleter(CountedCompleter<?> completer) {
425 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 * Performs an action when method {@link #tryComplete} is invoked
443 * and the pending count is zero, or when the unconditional
444 * method {@link #complete} is invoked. By default, this method
445 * 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 *
450 * @param caller the task invoking this method (which may
451 * be this task itself)
452 */
453 public void onCompletion(CountedCompleter<?> caller) {
454 }
455
456 /**
457 * Performs an action when method {@link
458 * #completeExceptionally(Throwable)} is invoked or method {@link
459 * #compute} throws an exception, and this task has not already
460 * otherwise completed normally. On entry to this method, this task
461 * {@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 *
468 * @param ex the exception
469 * @param caller the task invoking this method (which may
470 * be this task itself)
471 * @return {@code true} if this exception should be propagated to this
472 * task's completer, if one exists
473 */
474 public boolean onExceptionalCompletion(Throwable ex, CountedCompleter<?> caller) {
475 return true;
476 }
477
478 /**
479 * Returns the completer established in this task's constructor,
480 * or {@code null} if none.
481 *
482 * @return the completer
483 */
484 public final CountedCompleter<?> getCompleter() {
485 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 PENDING.getAndAdd(this, delta);
513 }
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 * @return {@code true} if successful
522 */
523 public final boolean compareAndSetPendingCount(int expected, int count) {
524 return PENDING.compareAndSet(this, expected, count);
525 }
526
527 // internal-only weak version
528 final boolean weakCompareAndSetPendingCount(int expected, int count) {
529 return PENDING.weakCompareAndSet(this, expected, count);
530 }
531
532 /**
533 * If the pending count is nonzero, (atomically) decrements it.
534 *
535 * @return the initial (undecremented) pending count holding on entry
536 * to this method
537 */
538 public final int decrementPendingCountUnlessZero() {
539 int c;
540 do {} while ((c = pending) != 0 &&
541 !weakCompareAndSetPendingCount(c, c - 1));
542 return c;
543 }
544
545 /**
546 * Returns the root of the current computation; i.e., this
547 * task if it has no completer, else its completer's root.
548 *
549 * @return the root of the current computation
550 */
551 public final CountedCompleter<?> getRoot() {
552 CountedCompleter<?> a = this, p;
553 while ((p = a.completer) != null)
554 a = p;
555 return a;
556 }
557
558 /**
559 * If the pending count is nonzero, decrements the count;
560 * otherwise invokes {@link #onCompletion(CountedCompleter)}
561 * and then similarly tries to complete this task's completer,
562 * if one exists, else marks this task as complete.
563 */
564 public final void tryComplete() {
565 CountedCompleter<?> a = this, s = a;
566 for (int c;;) {
567 if ((c = a.pending) == 0) {
568 a.onCompletion(s);
569 if ((a = (s = a).completer) == null) {
570 s.quietlyComplete();
571 return;
572 }
573 }
574 else if (a.weakCompareAndSetPendingCount(c, c - 1))
575 return;
576 }
577 }
578
579 /**
580 * Equivalent to {@link #tryComplete} but does not invoke {@link
581 * #onCompletion(CountedCompleter)} along the completion path:
582 * If the pending count is nonzero, decrements the count;
583 * otherwise, similarly tries to complete this task's completer, if
584 * one exists, else marks this task as complete. This method may be
585 * useful in cases where {@code onCompletion} should not, or need
586 * not, be invoked for each completer in a computation.
587 */
588 public final void propagateCompletion() {
589 CountedCompleter<?> a = this, s;
590 for (int c;;) {
591 if ((c = a.pending) == 0) {
592 if ((a = (s = a).completer) == null) {
593 s.quietlyComplete();
594 return;
595 }
596 }
597 else if (a.weakCompareAndSetPendingCount(c, c - 1))
598 return;
599 }
600 }
601
602 /**
603 * Regardless of pending count, invokes
604 * {@link #onCompletion(CountedCompleter)}, marks this task as
605 * complete and further triggers {@link #tryComplete} on this
606 * task's completer, if one exists. The given rawResult is
607 * used as an argument to {@link #setRawResult} before invoking
608 * {@link #onCompletion(CountedCompleter)} or marking this task
609 * as complete; its value is meaningful only for classes
610 * overriding {@code setRawResult}. This method does not modify
611 * the pending count.
612 *
613 * <p>This method may be useful when forcing completion as soon as
614 * any one (versus all) of several subtask results are obtained.
615 * However, in the common (and recommended) case in which {@code
616 * setRawResult} is not overridden, this effect can be obtained
617 * more simply using {@link #quietlyCompleteRoot()}.
618 *
619 * @param rawResult the raw result
620 */
621 public void complete(T rawResult) {
622 CountedCompleter<?> p;
623 setRawResult(rawResult);
624 onCompletion(this);
625 quietlyComplete();
626 if ((p = completer) != null)
627 p.tryComplete();
628 }
629
630 /**
631 * If this task's pending count is zero, returns this task;
632 * otherwise decrements its pending count and returns {@code null}.
633 * This method is designed to be used with {@link #nextComplete} in
634 * completion traversal loops.
635 *
636 * @return this task, if pending count was zero, else {@code null}
637 */
638 public final CountedCompleter<?> firstComplete() {
639 for (int c;;) {
640 if ((c = pending) == 0)
641 return this;
642 else if (weakCompareAndSetPendingCount(c, c - 1))
643 return null;
644 }
645 }
646
647 /**
648 * If this task does not have a completer, invokes {@link
649 * ForkJoinTask#quietlyComplete} and returns {@code null}. Or, if
650 * the completer's pending count is non-zero, decrements that
651 * pending count and returns {@code null}. Otherwise, returns the
652 * completer. This method can be used as part of a completion
653 * traversal loop for homogeneous task hierarchies:
654 *
655 * <pre> {@code
656 * for (CountedCompleter<?> c = firstComplete();
657 * c != null;
658 * c = c.nextComplete()) {
659 * // ... process c ...
660 * }}</pre>
661 *
662 * @return the completer, or {@code null} if none
663 */
664 public final CountedCompleter<?> nextComplete() {
665 CountedCompleter<?> p;
666 if ((p = completer) != null)
667 return p.firstComplete();
668 else {
669 quietlyComplete();
670 return null;
671 }
672 }
673
674 /**
675 * Equivalent to {@code getRoot().quietlyComplete()}.
676 */
677 public final void quietlyCompleteRoot() {
678 for (CountedCompleter<?> a = this, p;;) {
679 if ((p = a.completer) == null) {
680 a.quietlyComplete();
681 return;
682 }
683 a = p;
684 }
685 }
686
687 /**
688 * If this task has not completed, attempts to process at most the
689 * given number of other unprocessed tasks for which this task is
690 * on the completion path, if any are known to exist.
691 *
692 * @param maxTasks the maximum number of tasks to process. If
693 * less than or equal to zero, then no tasks are
694 * processed.
695 */
696 public final void helpComplete(int maxTasks) {
697 ForkJoinPool.WorkQueue q; Thread t; boolean owned;
698 if (owned = (t = Thread.currentThread()) instanceof ForkJoinWorkerThread)
699 q = ((ForkJoinWorkerThread)t).workQueue;
700 else
701 q = ForkJoinPool.commonQueue();
702 if (q != null && maxTasks > 0)
703 q.helpComplete(this, owned, maxTasks);
704 }
705
706 // ForkJoinTask overrides
707
708 /**
709 * Supports ForkJoinTask exception propagation.
710 */
711 @Override
712 final int trySetException(Throwable ex) {
713 CountedCompleter<?> a = this, p = a;
714 do {} while (isExceptionalStatus(a.trySetThrown(ex)) &&
715 a.onExceptionalCompletion(ex, p) &&
716 (a = (p = a).completer) != null && a.status >= 0);
717 return status;
718 }
719
720 /**
721 * Implements execution conventions for CountedCompleters.
722 */
723 @Override
724 protected final boolean exec() {
725 compute();
726 return false;
727 }
728
729 /**
730 * Returns the result of the computation. By default,
731 * returns {@code null}, which is appropriate for {@code Void}
732 * actions, but in other cases should be overridden, almost
733 * always to return a field or function of a field that
734 * holds the result upon completion.
735 *
736 * @return the result of the computation
737 */
738 @Override
739 public T getRawResult() { return null; }
740
741 /**
742 * A method that result-bearing CountedCompleters may optionally
743 * use to help maintain result data. By default, does nothing.
744 * Overrides are not recommended. However, if this method is
745 * overridden to update existing objects or fields, then it must
746 * in general be defined to be thread-safe.
747 */
748 @Override
749 protected void setRawResult(T t) { }
750
751 // VarHandle mechanics
752 private static final VarHandle PENDING;
753 static {
754 try {
755 MethodHandles.Lookup l = MethodHandles.lookup();
756 PENDING = l.findVarHandle(CountedCompleter.class, "pending", int.class);
757
758 } catch (ReflectiveOperationException e) {
759 throw new ExceptionInInitializerError(e);
760 }
761 }
762 }