ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/CountedCompleter.java
Revision: 1.72
Committed: Fri May 6 16:03:04 2022 UTC (2 years ago) by dl
Branch: MAIN
CVS Tags: HEAD
Changes since 1.71: +2 -0 lines
Log Message:
sync with openjdk

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