ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/CountedCompleter.java
Revision: 1.61
Committed: Tue Aug 30 18:09:45 2016 UTC (7 years, 9 months ago) by jsr166
Branch: MAIN
Changes since 1.60: +2 -4 lines
Log Message:
balance braces in code samples

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