ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jsr166y/CountedCompleter.java
Revision: 1.20
Committed: Sun Nov 25 18:45:48 2012 UTC (11 years, 5 months ago) by jsr166
Branch: MAIN
Changes since 1.19: +1 -1 lines
Log Message:
javadoc style

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