ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinTask.java
Revision: 1.125
Committed: Sat Jan 18 12:30:04 2020 UTC (4 years, 4 months ago) by dl
Branch: MAIN
Changes since 1.124: +4 -6 lines
Log Message:
more consistent parallelism-0 handling; doc touchups

File Contents

# User Rev Content
1 jsr166 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 jsr166 1.48 * http://creativecommons.org/publicdomain/zero/1.0/
5 jsr166 1.1 */
6    
7     package java.util.concurrent;
8    
9     import java.io.Serializable;
10 dl 1.109 import java.lang.invoke.MethodHandles;
11     import java.lang.invoke.VarHandle;
12 jsr166 1.90 import java.lang.ref.ReferenceQueue;
13     import java.lang.ref.WeakReference;
14     import java.lang.reflect.Constructor;
15 jsr166 1.1 import java.util.Collection;
16     import java.util.List;
17 jsr166 1.7 import java.util.RandomAccess;
18 dl 1.124 import java.util.concurrent.locks.LockSupport;
19 jsr166 1.1
20     /**
21 jsr166 1.6 * Abstract base class for tasks that run within a {@link ForkJoinPool}.
22     * A {@code ForkJoinTask} is a thread-like entity that is much
23 jsr166 1.1 * lighter weight than a normal thread. Huge numbers of tasks and
24     * subtasks may be hosted by a small number of actual threads in a
25     * ForkJoinPool, at the price of some usage limitations.
26     *
27 dl 1.64 * <p>A "main" {@code ForkJoinTask} begins execution when it is
28     * explicitly submitted to a {@link ForkJoinPool}, or, if not already
29     * engaged in a ForkJoin computation, commenced in the {@link
30 dl 1.67 * ForkJoinPool#commonPool()} via {@link #fork}, {@link #invoke}, or
31 dl 1.64 * related methods. Once started, it will usually in turn start other
32     * subtasks. As indicated by the name of this class, many programs
33     * using {@code ForkJoinTask} employ only methods {@link #fork} and
34     * {@link #join}, or derivatives such as {@link
35 jsr166 1.27 * #invokeAll(ForkJoinTask...) invokeAll}. However, this class also
36     * provides a number of other methods that can come into play in
37 dl 1.64 * advanced usages, as well as extension mechanics that allow support
38     * of new forms of fork/join processing.
39 jsr166 1.1 *
40 jsr166 1.6 * <p>A {@code ForkJoinTask} is a lightweight form of {@link Future}.
41     * The efficiency of {@code ForkJoinTask}s stems from a set of
42     * restrictions (that are only partially statically enforceable)
43 dl 1.54 * reflecting their main use as computational tasks calculating pure
44     * functions or operating on purely isolated objects. The primary
45     * coordination mechanisms are {@link #fork}, that arranges
46 jsr166 1.6 * asynchronous execution, and {@link #join}, that doesn't proceed
47     * until the task's result has been computed. Computations should
48 dl 1.54 * ideally avoid {@code synchronized} methods or blocks, and should
49     * minimize other blocking synchronization apart from joining other
50     * tasks or using synchronizers such as Phasers that are advertised to
51     * cooperate with fork/join scheduling. Subdividable tasks should also
52 jsr166 1.68 * not perform blocking I/O, and should ideally access variables that
53 dl 1.54 * are completely independent of those accessed by other running
54     * tasks. These guidelines are loosely enforced by not permitting
55     * checked exceptions such as {@code IOExceptions} to be
56     * thrown. However, computations may still encounter unchecked
57     * exceptions, that are rethrown to callers attempting to join
58     * them. These exceptions may additionally include {@link
59     * RejectedExecutionException} stemming from internal resource
60     * exhaustion, such as failure to allocate internal task
61     * queues. Rethrown exceptions behave in the same way as regular
62     * exceptions, but, when possible, contain stack traces (as displayed
63     * for example using {@code ex.printStackTrace()}) of both the thread
64     * that initiated the computation as well as the thread actually
65     * encountering the exception; minimally only the latter.
66     *
67     * <p>It is possible to define and use ForkJoinTasks that may block,
68 jsr166 1.110 * but doing so requires three further considerations: (1) Completion
69 dl 1.54 * of few if any <em>other</em> tasks should be dependent on a task
70 jsr166 1.68 * that blocks on external synchronization or I/O. Event-style async
71 dl 1.63 * tasks that are never joined (for example, those subclassing {@link
72     * CountedCompleter}) often fall into this category. (2) To minimize
73     * resource impact, tasks should be small; ideally performing only the
74     * (possibly) blocking action. (3) Unless the {@link
75 dl 1.54 * ForkJoinPool.ManagedBlocker} API is used, or the number of possibly
76     * blocked tasks is known to be less than the pool's {@link
77     * ForkJoinPool#getParallelism} level, the pool cannot guarantee that
78     * enough threads will be available to ensure progress or good
79     * performance.
80 jsr166 1.1 *
81     * <p>The primary method for awaiting completion and extracting
82     * results of a task is {@link #join}, but there are several variants:
83     * The {@link Future#get} methods support interruptible and/or timed
84     * waits for completion and report results using {@code Future}
85 dl 1.16 * conventions. Method {@link #invoke} is semantically
86 jsr166 1.8 * equivalent to {@code fork(); join()} but always attempts to begin
87     * execution in the current thread. The "<em>quiet</em>" forms of
88     * these methods do not extract results or report exceptions. These
89 jsr166 1.1 * may be useful when a set of tasks are being executed, and you need
90     * to delay processing of results or exceptions until all complete.
91     * Method {@code invokeAll} (available in multiple versions)
92     * performs the most common form of parallel invocation: forking a set
93     * of tasks and joining them all.
94     *
95 jsr166 1.57 * <p>In the most typical usages, a fork-join pair act like a call
96 dl 1.54 * (fork) and return (join) from a parallel recursive function. As is
97     * the case with other forms of recursive calls, returns (joins)
98     * should be performed innermost-first. For example, {@code a.fork();
99     * b.fork(); b.join(); a.join();} is likely to be substantially more
100     * efficient than joining {@code a} before {@code b}.
101     *
102 jsr166 1.8 * <p>The execution status of tasks may be queried at several levels
103     * of detail: {@link #isDone} is true if a task completed in any way
104     * (including the case where a task was cancelled without executing);
105     * {@link #isCompletedNormally} is true if a task completed without
106 jsr166 1.10 * cancellation or encountering an exception; {@link #isCancelled} is
107     * true if the task was cancelled (in which case {@link #getException}
108 jsr166 1.115 * returns a {@link CancellationException}); and
109 jsr166 1.10 * {@link #isCompletedAbnormally} is true if a task was either
110     * cancelled or encountered an exception, in which case {@link
111     * #getException} will return either the encountered exception or
112 jsr166 1.115 * {@link CancellationException}.
113 jsr166 1.8 *
114 jsr166 1.6 * <p>The ForkJoinTask class is not usually directly subclassed.
115 jsr166 1.1 * Instead, you subclass one of the abstract classes that support a
116 jsr166 1.6 * particular style of fork/join processing, typically {@link
117 dl 1.62 * RecursiveAction} for most computations that do not return results,
118     * {@link RecursiveTask} for those that do, and {@link
119     * CountedCompleter} for those in which completed actions trigger
120     * other actions. Normally, a concrete ForkJoinTask subclass declares
121     * fields comprising its parameters, established in a constructor, and
122     * then defines a {@code compute} method that somehow uses the control
123 dl 1.64 * methods supplied by this base class.
124 jsr166 1.1 *
125 dl 1.38 * <p>Method {@link #join} and its variants are appropriate for use
126     * only when completion dependencies are acyclic; that is, the
127     * parallel computation can be described as a directed acyclic graph
128     * (DAG). Otherwise, executions may encounter a form of deadlock as
129     * tasks cyclically wait for each other. However, this framework
130     * supports other methods and techniques (for example the use of
131     * {@link Phaser}, {@link #helpQuiesce}, and {@link #complete}) that
132     * may be of use in constructing custom subclasses for problems that
133 jsr166 1.79 * are not statically structured as DAGs. To support such usages, a
134 dl 1.63 * ForkJoinTask may be atomically <em>tagged</em> with a {@code short}
135     * value using {@link #setForkJoinTaskTag} or {@link
136 dl 1.60 * #compareAndSetForkJoinTaskTag} and checked using {@link
137 dl 1.63 * #getForkJoinTaskTag}. The ForkJoinTask implementation does not use
138     * these {@code protected} methods or tags for any purpose, but they
139     * may be of use in the construction of specialized subclasses. For
140     * example, parallel graph traversals can use the supplied methods to
141     * avoid revisiting nodes/tasks that have already been processed.
142     * (Method names for tagging are bulky in part to encourage definition
143     * of methods that reflect their usage patterns.)
144 dl 1.38 *
145 jsr166 1.7 * <p>Most base support methods are {@code final}, to prevent
146     * overriding of implementations that are intrinsically tied to the
147     * underlying lightweight task scheduling framework. Developers
148     * creating new basic styles of fork/join processing should minimally
149     * implement {@code protected} methods {@link #exec}, {@link
150     * #setRawResult}, and {@link #getRawResult}, while also introducing
151     * an abstract computational method that can be implemented in its
152     * subclasses, possibly relying on other {@code protected} methods
153     * provided by this class.
154 jsr166 1.1 *
155     * <p>ForkJoinTasks should perform relatively small amounts of
156 jsr166 1.7 * computation. Large tasks should be split into smaller subtasks,
157     * usually via recursive decomposition. As a very rough rule of thumb,
158     * a task should perform more than 100 and less than 10000 basic
159 dl 1.40 * computational steps, and should avoid indefinite looping. If tasks
160     * are too big, then parallelism cannot improve throughput. If too
161     * small, then memory and internal task maintenance overhead may
162     * overwhelm processing.
163 jsr166 1.1 *
164 jsr166 1.8 * <p>This class provides {@code adapt} methods for {@link Runnable}
165     * and {@link Callable}, that may be of use when mixing execution of
166 dl 1.16 * {@code ForkJoinTasks} with other kinds of tasks. When all tasks are
167     * of this form, consider using a pool constructed in <em>asyncMode</em>.
168 jsr166 1.6 *
169 jsr166 1.7 * <p>ForkJoinTasks are {@code Serializable}, which enables them to be
170     * used in extensions such as remote execution frameworks. It is
171     * sensible to serialize tasks only before or after, but not during,
172     * execution. Serialization is not relied on during execution itself.
173 jsr166 1.1 *
174     * @since 1.7
175     * @author Doug Lea
176     */
177     public abstract class ForkJoinTask<V> implements Future<V>, Serializable {
178    
179 dl 1.13 /*
180     * See the internal documentation of class ForkJoinPool for a
181     * general implementation overview. ForkJoinTasks are mainly
182     * responsible for maintaining their "status" field amidst relays
183 jsr166 1.51 * to methods in ForkJoinWorkerThread and ForkJoinPool.
184     *
185     * The methods of this class are more-or-less layered into
186     * (1) basic status maintenance
187     * (2) execution and awaiting completion
188     * (3) user-level methods that additionally report results.
189     * This is sometimes hard to see because this file orders exported
190     * methods in a way that flows well in javadocs.
191 dl 1.118 *
192 dl 1.124 * Revision notes: The use of "Aux" field replaces previous
193     * reliance on a table to hold exceptions and synchronized blocks
194     * and monitors to wait for completion.
195 dl 1.118 */
196 jsr166 1.1
197     /**
198 dl 1.124 * Nodes for threads waiting for completion, or holding a thrown
199     * exception (never both). Waiting threads prepend nodes
200     * Treiber-stack-style. Signallers detach and unpark
201     * waiters. Cancelled waiters try to unsplice.
202     */
203     static final class Aux {
204     final Thread thread;
205     final Throwable ex; // null if a waiter
206     Aux next; // accessed only via memory-acquire chains
207     Aux(Thread thread, Throwable ex) {
208     this.thread = thread;
209     this.ex = ex;
210     }
211     final boolean casNext(Aux c, Aux v) { // used only in cancellation
212     return NEXT.compareAndSet(this, c, v);
213     }
214     private static final VarHandle NEXT;
215     static {
216     try {
217     NEXT = MethodHandles.lookup()
218     .findVarHandle(Aux.class, "next", Aux.class);
219     } catch (ReflectiveOperationException e) {
220     throw new ExceptionInInitializerError(e);
221 dl 1.13 }
222     }
223 jsr166 1.1 }
224    
225 dl 1.124 /*
226     * The status field holds bits packed into a single int to ensure
227     * atomicity. Status is initially zero, and takes on nonnegative
228     * values until completed, upon which it holds (sign bit) DONE,
229     * possibly with ABNORMAL (cancelled or exceptional) and THROWN
230     * (in which case an exception has been stored). These control
231     * bits occupy only (some of) the upper half (16 bits) of status
232     * field. The lower bits are used for user-defined tags.
233 jsr166 1.1 */
234 dl 1.124 private static final int DONE = 1 << 31; // must be negative
235     private static final int ABNORMAL = 1 << 16; // set atomically with DONE
236     private static final int THROWN = 1 << 17; // set atomically with ABNORMAL
237     private static final int SMASK = 0xffff; // short bits for tags
238     // sentinels can be any positive upper half value:
239     private static final int INTRPT = 1 << 16; // awaitDone interrupt return
240     static final int ADJUST = 1 << 16; // uncompensate after block
241    
242     // Fields
243     volatile int status; // accessed directly by pool and workers
244     private transient volatile Aux aux; // either waiters or thrown Exception
245     // Support for atomic operations
246     private static final VarHandle STATUS;
247     private static final VarHandle AUX;
248     private int getAndBitwiseOrStatus(int v) {
249     return (int)STATUS.getAndBitwiseOr(this, v);
250     }
251     private boolean casStatus(int c, int v) {
252     return STATUS.weakCompareAndSet(this, c, v);
253     }
254     private boolean casAux(Aux c, Aux v) {
255     return AUX.compareAndSet(this, c, v);
256     }
257    
258     /** Removes and unparks waiters */
259     private void signalWaiters() {
260     for (Aux a; (a = aux) != null && a.ex == null; ) {
261     if (casAux(a, null)) { // detach entire list
262     for (Thread t; a != null; a = a.next) {
263     if ((t = a.thread) != Thread.currentThread() && t != null)
264     LockSupport.unpark(t); // don't self-signal
265     }
266     break;
267 dl 1.54 }
268 jsr166 1.1 }
269     }
270    
271     /**
272 dl 1.124 * Possibly blocks until task is done or interrupted or timed out.
273 dl 1.87 *
274 dl 1.124 * @param interruptible true if wait can be cancelled by interrupt
275     * @param deadline if non-zero use timed waits and possibly timeout
276     * @param pool if nonull, pool to uncompensate when unblocking
277     * @return status on exit, or INTRPT if interrupted while waiting
278     */
279     final int awaitDone(boolean interruptible, long deadline,
280     ForkJoinPool pool) {
281     int s; Aux node = null; boolean interrupted = false, queued = false;
282     for (;;) {
283     Aux a; long nanos;
284     if ((s = status) < 0)
285     break;
286     else if (node == null)
287     node = new Aux(Thread.currentThread(), null);
288     else if (!queued) {
289     if ((a = aux) != null && a.ex != null)
290     Thread.onSpinWait(); // exception in progress
291     else if (queued = casAux(node.next = a, node))
292     LockSupport.setCurrentBlocker(this);
293     }
294     else {
295     if (deadline == 0L)
296     LockSupport.park();
297     else if ((nanos = deadline - System.nanoTime()) > 0L)
298     LockSupport.parkNanos(nanos);
299     else {
300     s = 0; // timeout
301     break;
302     }
303     if ((interrupted |= Thread.interrupted()) && interruptible) {
304     s = INTRPT;
305     break;
306     }
307 dl 1.87 }
308     }
309 dl 1.124 if (pool != null)
310     pool.uncompensate();
311     if (s >= 0) { // try to unsplice after cancellation
312     outer: for (Aux a; (a = aux) != null && a.ex == null; ) {
313     for (Aux trail = null;;) {
314     Aux next = a.next;
315     if (a == node) {
316     if (trail != null)
317     trail.casNext(trail, next);
318     else if (casAux(a, next))
319     break outer; // cannot be re-encountered
320     break; // restart
321     } else {
322     trail = a;
323     if ((a = next) == null)
324     break outer;
325 dl 1.40 }
326 dl 1.87 }
327 dl 1.118 }
328 dl 1.124 }
329     else if (interrupted)
330     Thread.currentThread().interrupt();
331     if (queued) {
332     LockSupport.setCurrentBlocker(null);
333     signalWaiters(); // help clean or signal
334 dl 1.19 }
335 dl 1.45 return s;
336 dl 1.19 }
337    
338     /**
339 dl 1.124 * Sets DONE status and wakes up threads waiting to join this task.
340     * @return status on exit
341 jsr166 1.1 */
342 dl 1.124 private int setDone() {
343     int s = getAndBitwiseOrStatus(DONE) | DONE;
344     signalWaiters();
345 dl 1.45 return s;
346     }
347    
348     /**
349 dl 1.124 * Sets ABNORMAL DONE status unless already done, and wakes up threads
350     * waiting to join this task.
351     * @return status on exit
352 dl 1.118 */
353 dl 1.124 private int trySetCancelled() {
354 dl 1.118 int s;
355 dl 1.124 do {} while ((s = status) >= 0 && !casStatus(s, s |= (DONE | ABNORMAL)));
356     signalWaiters();
357     return s;
358 dl 1.118 }
359    
360     /**
361 dl 1.124 * Records exception and sets ABNORMAL THROWN DONE status unless
362     * already done, and wakes up threads waiting to join this task.
363     * If losing a race with setDone or trySetCancelled, the exception
364     * may be recorded but not reported.
365 dl 1.54 *
366 dl 1.124 * @return status on exit
367 dl 1.45 */
368 dl 1.124 final int trySetThrown(Throwable ex) {
369     Aux h = new Aux(Thread.currentThread(), ex), p = null;
370     boolean installed = false;
371     int s;
372     while ((s = status) >= 0) {
373     Aux a;
374     if (!installed && ((a = aux) == null || a.ex == null) &&
375     (installed = casAux(a, h)))
376     p = a; // list of waiters replaced by h
377     if (installed && casStatus(s, s |= (DONE | ABNORMAL | THROWN)))
378     break;
379     }
380     for (; p != null; p = p.next)
381     LockSupport.unpark(p.thread);
382     return s;
383 jsr166 1.1 }
384    
385     /**
386 dl 1.124 * Records exception unless already done. Overridable in subclasses.
387 dl 1.54 *
388 dl 1.124 * @return status on exit
389 jsr166 1.1 */
390 dl 1.124 int trySetException(Throwable ex) {
391     return trySetThrown(ex);
392 dl 1.45 }
393    
394 dl 1.124 static boolean isExceptionalStatus(int s) { // needed by subclasses
395     return (s & THROWN) != 0;
396 dl 1.45 }
397    
398     /**
399 dl 1.124 * Unless done, calls exec and records status if completed, but
400     * doesn't wait for completion otherwise.
401 dl 1.45 *
402 dl 1.124 * @return status on exit from this method
403 dl 1.45 */
404 dl 1.124 final int doExec() {
405     int s; boolean completed;
406 dl 1.62 if ((s = status) >= 0) {
407     try {
408 dl 1.124 completed = exec();
409     } catch (Throwable rex) {
410     s = trySetException(rex);
411     completed = false;
412 dl 1.45 }
413 dl 1.124 if (completed)
414     s = setDone();
415 dl 1.45 }
416 dl 1.62 return s;
417     }
418    
419     /**
420 dl 1.124 * Helps and/or waits for completion. Overridable in subclasses.
421 dl 1.63 *
422 dl 1.124 * @param interruptible true if wait can be cancelled by interrupt
423     * @param ran true if task known to be invoked
424     * @return status on exit, or INTRPT if interruptible and interrupted
425 dl 1.63 */
426 dl 1.124 int awaitJoin(boolean interruptible, boolean ran) {
427     Thread t; ForkJoinWorkerThread wt;
428     ForkJoinPool.WorkQueue q = null;
429     ForkJoinPool p = null;
430     boolean unforked = false;
431     if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) {
432     p = (wt = (ForkJoinWorkerThread)t).pool;
433     q = wt.workQueue;
434     if (!ran && q != null && q.tryRemove(this))
435     unforked = true;
436     }
437     else if (!ran && (q = ForkJoinPool.commonQueue()) != null &&
438     q.externalTryUnpush(this))
439     unforked = true;
440     int s;
441     if (unforked && (s = doExec()) < 0)
442     return s;
443     if (p != null) {
444     if ((s = p.helpJoin(this, q)) < 0)
445     return s;
446     if (s != ADJUST) // uncompensated
447     p = null;
448     }
449     return awaitDone(interruptible, 0L, p);
450 dl 1.45 }
451    
452     /**
453 dl 1.54 * Cancels, ignoring any exceptions thrown by cancel. Used during
454     * worker and pool shutdown. Cancel is spec'ed not to throw any
455     * exceptions, but if it does anyway, we have no recourse during
456     * shutdown, so guard against this case.
457     */
458     static final void cancelIgnoringExceptions(ForkJoinTask<?> t) {
459 dl 1.124 if (t != null) {
460 dl 1.54 try {
461     t.cancel(false);
462     } catch (Throwable ignore) {
463     }
464     }
465     }
466    
467     /**
468 jsr166 1.105 * Returns a rethrowable exception for this task, if available.
469     * To provide accurate stack traces, if the exception was not
470     * thrown by the current thread, we try to create a new exception
471     * of the same type as the one thrown, but with the recorded
472     * exception as its cause. If there is no such constructor, we
473     * instead try to use a no-arg constructor, followed by initCause,
474     * to the same effect. If none of these apply, or any fail due to
475     * other exceptions, we return the recorded exception, which is
476     * still correct, although it may contain a misleading stack
477     * trace.
478 dl 1.45 *
479     * @return the exception, or null if none
480     */
481     private Throwable getThrowableException() {
482 dl 1.124 Throwable ex; Aux a;
483     if ((a = aux) == null)
484     ex = null;
485     else if ((ex = a.ex) != null && a.thread != Thread.currentThread()) {
486 dl 1.45 try {
487 dl 1.124 Constructor<?> noArgCtor = null, oneArgCtor = null;
488 jsr166 1.106 for (Constructor<?> c : ex.getClass().getConstructors()) {
489 dl 1.45 Class<?>[] ps = c.getParameterTypes();
490     if (ps.length == 0)
491     noArgCtor = c;
492 dl 1.124 else if (ps.length == 1 && ps[0] == Throwable.class) {
493     oneArgCtor = c;
494     break;
495     }
496 dl 1.45 }
497 dl 1.124 if (oneArgCtor != null)
498     ex = (Throwable)oneArgCtor.newInstance(ex);
499     else if (noArgCtor != null) {
500     Throwable rx = (Throwable)noArgCtor.newInstance();
501     rx.initCause(ex);
502     ex = rx;
503 dl 1.45 }
504     } catch (Exception ignore) {
505     }
506     }
507     return ex;
508     }
509    
510     /**
511 dl 1.124 * Throws exception associated with the given status, or
512     * CancellationException if none recorded.
513 dl 1.45 */
514 dl 1.124 private void reportException(int s) {
515     ForkJoinTask.<RuntimeException>uncheckedThrow(
516     (s & THROWN) != 0 ? getThrowableException() : null);
517 dl 1.45 }
518    
519     /**
520 dl 1.124 * A version of "sneaky throw" to relay exceptions in other
521     * contexts.
522 dl 1.65 */
523 jsr166 1.78 static void rethrow(Throwable ex) {
524 dl 1.100 ForkJoinTask.<RuntimeException>uncheckedThrow(ex);
525 dl 1.65 }
526    
527     /**
528     * The sneaky part of sneaky throw, relying on generics
529     * limitations to evade compiler complaints about rethrowing
530 dl 1.124 * unchecked exceptions. If argument null, throws
531     * CancellationException.
532 dl 1.65 */
533     @SuppressWarnings("unchecked") static <T extends Throwable>
534 dl 1.100 void uncheckedThrow(Throwable t) throws T {
535 dl 1.124 if (t == null)
536     t = new CancellationException();
537     throw (T)t; // rely on vacuous cast
538 jsr166 1.1 }
539    
540     // public methods
541    
542     /**
543 dl 1.64 * Arranges to asynchronously execute this task in the pool the
544     * current task is running in, if applicable, or using the {@link
545 dl 1.67 * ForkJoinPool#commonPool()} if not {@link #inForkJoinPool}. While
546 dl 1.64 * it is not necessarily enforced, it is a usage error to fork a
547     * task more than once unless it has completed and been
548     * reinitialized. Subsequent modifications to the state of this
549     * task or any data it operates on are not necessarily
550     * consistently observable by any thread other than the one
551     * executing it unless preceded by a call to {@link #join} or
552     * related methods, or a call to {@link #isDone} returning {@code
553     * true}.
554 jsr166 1.2 *
555 jsr166 1.6 * @return {@code this}, to simplify usage
556 jsr166 1.1 */
557 jsr166 1.2 public final ForkJoinTask<V> fork() {
558 dl 1.124 Thread t; ForkJoinWorkerThread w;
559 dl 1.64 if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread)
560 dl 1.124 (w = (ForkJoinWorkerThread)t).workQueue.push(this, w.pool);
561 dl 1.64 else
562 dl 1.71 ForkJoinPool.common.externalPush(this);
563 jsr166 1.2 return this;
564 jsr166 1.1 }
565    
566     /**
567 jsr166 1.115 * Returns the result of the computation when it
568     * {@linkplain #isDone is done}.
569     * This method differs from {@link #get()} in that abnormal
570     * completion results in {@code RuntimeException} or {@code Error},
571     * not {@code ExecutionException}, and that interrupts of the
572     * calling thread do <em>not</em> cause the method to abruptly
573     * return by throwing {@code InterruptedException}.
574 jsr166 1.1 *
575     * @return the computed result
576     */
577     public final V join() {
578 dl 1.59 int s;
579 dl 1.124 if ((s = status) >= 0)
580     s = awaitJoin(false, false);
581     if ((s & ABNORMAL) != 0)
582 dl 1.59 reportException(s);
583     return getRawResult();
584 jsr166 1.1 }
585    
586     /**
587     * Commences performing this task, awaits its completion if
588 jsr166 1.21 * necessary, and returns its result, or throws an (unchecked)
589 dl 1.20 * {@code RuntimeException} or {@code Error} if the underlying
590     * computation did so.
591 jsr166 1.1 *
592     * @return the computed result
593     */
594     public final V invoke() {
595 dl 1.59 int s;
596 dl 1.124 if ((s = doExec()) >= 0)
597     s = awaitJoin(false, true);
598     if ((s & ABNORMAL) != 0)
599 dl 1.59 reportException(s);
600     return getRawResult();
601 jsr166 1.1 }
602    
603     /**
604 jsr166 1.8 * Forks the given tasks, returning when {@code isDone} holds for
605     * each task or an (unchecked) exception is encountered, in which
606 dl 1.20 * case the exception is rethrown. If more than one task
607     * encounters an exception, then this method throws any one of
608     * these exceptions. If any task encounters an exception, the
609     * other may be cancelled. However, the execution status of
610     * individual tasks is not guaranteed upon exceptional return. The
611     * status of each task may be obtained using {@link
612     * #getException()} and related methods to check if they have been
613     * cancelled, completed normally or exceptionally, or left
614     * unprocessed.
615 jsr166 1.6 *
616     * @param t1 the first task
617     * @param t2 the second task
618     * @throws NullPointerException if any task is null
619 jsr166 1.1 */
620 jsr166 1.6 public static void invokeAll(ForkJoinTask<?> t1, ForkJoinTask<?> t2) {
621 dl 1.59 int s1, s2;
622 dl 1.124 if (t1 == null || t2 == null)
623     throw new NullPointerException();
624 jsr166 1.1 t2.fork();
625 dl 1.124 if ((s1 = t1.doExec()) >= 0)
626     s1 = t1.awaitJoin(false, true);
627     if ((s1 & ABNORMAL) != 0) {
628     t2.cancel(false);
629 dl 1.59 t1.reportException(s1);
630 dl 1.124 }
631     else {
632     if ((s2 = t2.status) >= 0)
633     s2 = t2.awaitJoin(false, false);
634     if ((s2 & ABNORMAL) != 0)
635     t2.reportException(s2);
636     }
637 jsr166 1.1 }
638    
639     /**
640 jsr166 1.6 * Forks the given tasks, returning when {@code isDone} holds for
641 jsr166 1.8 * each task or an (unchecked) exception is encountered, in which
642 dl 1.20 * case the exception is rethrown. If more than one task
643     * encounters an exception, then this method throws any one of
644     * these exceptions. If any task encounters an exception, others
645     * may be cancelled. However, the execution status of individual
646     * tasks is not guaranteed upon exceptional return. The status of
647     * each task may be obtained using {@link #getException()} and
648     * related methods to check if they have been cancelled, completed
649     * normally or exceptionally, or left unprocessed.
650 jsr166 1.6 *
651     * @param tasks the tasks
652 jsr166 1.8 * @throws NullPointerException if any task is null
653 jsr166 1.1 */
654     public static void invokeAll(ForkJoinTask<?>... tasks) {
655     Throwable ex = null;
656     int last = tasks.length - 1;
657 dl 1.124 for (int i = last, s; i >= 0; --i) {
658     ForkJoinTask<?> t;
659     if ((t = tasks[i]) == null) {
660     ex = new NullPointerException();
661     break;
662 jsr166 1.1 }
663 dl 1.124 if (i == 0) {
664     if ((s = t.doExec()) >= 0)
665     s = t.awaitJoin(false, true);
666     if ((s & ABNORMAL) != 0)
667 dl 1.45 ex = t.getException();
668 dl 1.124 break;
669 jsr166 1.1 }
670 dl 1.124 t.fork();
671 jsr166 1.1 }
672 dl 1.124 if (ex == null) {
673     for (int i = 1, s; i <= last; ++i) {
674     ForkJoinTask<?> t;
675     if ((t = tasks[i]) != null) {
676     if ((s = t.status) >= 0)
677     s = t.awaitJoin(false, false);
678     if ((s & ABNORMAL) != 0) {
679     ex = t.getException();
680     break;
681     }
682     }
683     }
684     }
685     if (ex != null) { // try to cancel others
686     for (int i = 0, s; i <= last; ++i) {
687     ForkJoinTask<?> t;
688     if ((t = tasks[i]) != null)
689     t.cancel(false);
690     }
691 dl 1.65 rethrow(ex);
692 dl 1.124 }
693 jsr166 1.1 }
694    
695     /**
696 jsr166 1.7 * Forks all tasks in the specified collection, returning when
697 jsr166 1.8 * {@code isDone} holds for each task or an (unchecked) exception
698 dl 1.20 * is encountered, in which case the exception is rethrown. If
699     * more than one task encounters an exception, then this method
700     * throws any one of these exceptions. If any task encounters an
701     * exception, others may be cancelled. However, the execution
702     * status of individual tasks is not guaranteed upon exceptional
703     * return. The status of each task may be obtained using {@link
704     * #getException()} and related methods to check if they have been
705     * cancelled, completed normally or exceptionally, or left
706     * unprocessed.
707 jsr166 1.6 *
708 jsr166 1.1 * @param tasks the collection of tasks
709 jsr166 1.82 * @param <T> the type of the values returned from the tasks
710 jsr166 1.2 * @return the tasks argument, to simplify usage
711 jsr166 1.1 * @throws NullPointerException if tasks or any element are null
712     */
713 jsr166 1.2 public static <T extends ForkJoinTask<?>> Collection<T> invokeAll(Collection<T> tasks) {
714 jsr166 1.7 if (!(tasks instanceof RandomAccess) || !(tasks instanceof List<?>)) {
715 jsr166 1.121 invokeAll(tasks.toArray(new ForkJoinTask<?>[0]));
716 jsr166 1.2 return tasks;
717 jsr166 1.1 }
718     @SuppressWarnings("unchecked")
719     List<? extends ForkJoinTask<?>> ts =
720     (List<? extends ForkJoinTask<?>>) tasks;
721     Throwable ex = null;
722 dl 1.124 int last = ts.size() - 1; // nearly same as array version
723     for (int i = last, s; i >= 0; --i) {
724     ForkJoinTask<?> t;
725     if ((t = ts.get(i)) == null) {
726     ex = new NullPointerException();
727     break;
728 jsr166 1.1 }
729 dl 1.124 if (i == 0) {
730     if ((s = t.doExec()) >= 0)
731     s = t.awaitJoin(false, true);
732     if ((s & ABNORMAL) != 0)
733 dl 1.45 ex = t.getException();
734 dl 1.124 break;
735     }
736     t.fork();
737     }
738     if (ex == null) {
739     for (int i = 1, s; i <= last; ++i) {
740     ForkJoinTask<?> t;
741     if ((t = ts.get(i)) != null) {
742     if ((s = t.status) >= 0)
743     s = t.awaitJoin(false, false);
744     if ((s & ABNORMAL) != 0) {
745     ex = t.getException();
746     break;
747     }
748     }
749 jsr166 1.1 }
750     }
751 dl 1.124 if (ex != null) {
752     for (int i = 0, s; i <= last; ++i) {
753     ForkJoinTask<?> t;
754     if ((t = ts.get(i)) != null)
755     t.cancel(false);
756     }
757 dl 1.65 rethrow(ex);
758 dl 1.124 }
759 jsr166 1.2 return tasks;
760 jsr166 1.1 }
761    
762     /**
763 jsr166 1.7 * Attempts to cancel execution of this task. This attempt will
764 jsr166 1.36 * fail if the task has already completed or could not be
765     * cancelled for some other reason. If successful, and this task
766     * has not started when {@code cancel} is called, execution of
767 dl 1.38 * this task is suppressed. After this method returns
768     * successfully, unless there is an intervening call to {@link
769     * #reinitialize}, subsequent calls to {@link #isCancelled},
770     * {@link #isDone}, and {@code cancel} will return {@code true}
771     * and calls to {@link #join} and related methods will result in
772     * {@code CancellationException}.
773 jsr166 1.1 *
774     * <p>This method may be overridden in subclasses, but if so, must
775 dl 1.38 * still ensure that these properties hold. In particular, the
776     * {@code cancel} method itself must not throw exceptions.
777 jsr166 1.1 *
778 jsr166 1.6 * <p>This method is designed to be invoked by <em>other</em>
779 jsr166 1.1 * tasks. To terminate the current task, you can just return or
780     * throw an unchecked exception from its computation method, or
781 jsr166 1.74 * invoke {@link #completeExceptionally(Throwable)}.
782 jsr166 1.1 *
783 dl 1.38 * @param mayInterruptIfRunning this value has no effect in the
784     * default implementation because interrupts are not used to
785     * control cancellation.
786 jsr166 1.1 *
787 jsr166 1.4 * @return {@code true} if this task is now cancelled
788 jsr166 1.1 */
789     public boolean cancel(boolean mayInterruptIfRunning) {
790 dl 1.124 return (trySetCancelled() & (ABNORMAL | THROWN)) == ABNORMAL;
791 jsr166 1.1 }
792    
793 jsr166 1.8 public final boolean isDone() {
794     return status < 0;
795     }
796    
797     public final boolean isCancelled() {
798 dl 1.118 return (status & (ABNORMAL | THROWN)) == ABNORMAL;
799 jsr166 1.8 }
800    
801     /**
802 jsr166 1.4 * Returns {@code true} if this task threw an exception or was cancelled.
803 jsr166 1.1 *
804 jsr166 1.4 * @return {@code true} if this task threw an exception or was cancelled
805 jsr166 1.1 */
806     public final boolean isCompletedAbnormally() {
807 dl 1.118 return (status & ABNORMAL) != 0;
808 jsr166 1.1 }
809    
810     /**
811 jsr166 1.8 * Returns {@code true} if this task completed without throwing an
812     * exception and was not cancelled.
813     *
814     * @return {@code true} if this task completed without throwing an
815     * exception and was not cancelled
816     */
817     public final boolean isCompletedNormally() {
818 dl 1.118 return (status & (DONE | ABNORMAL)) == DONE;
819 jsr166 1.8 }
820    
821     /**
822 jsr166 1.1 * Returns the exception thrown by the base computation, or a
823 jsr166 1.6 * {@code CancellationException} if cancelled, or {@code null} if
824     * none or if the method has not yet completed.
825 jsr166 1.1 *
826 jsr166 1.4 * @return the exception, or {@code null} if none
827 jsr166 1.1 */
828     public final Throwable getException() {
829 dl 1.118 int s = status;
830     return ((s & ABNORMAL) == 0 ? null :
831     (s & THROWN) == 0 ? new CancellationException() :
832 dl 1.45 getThrowableException());
833 jsr166 1.1 }
834    
835     /**
836     * Completes this task abnormally, and if not already aborted or
837     * cancelled, causes it to throw the given exception upon
838     * {@code join} and related operations. This method may be used
839     * to induce exceptions in asynchronous tasks, or to force
840     * completion of tasks that would not otherwise complete. Its use
841 jsr166 1.6 * in other situations is discouraged. This method is
842 jsr166 1.1 * overridable, but overridden versions must invoke {@code super}
843     * implementation to maintain guarantees.
844     *
845 jsr166 1.11 * @param ex the exception to throw. If this exception is not a
846     * {@code RuntimeException} or {@code Error}, the actual exception
847     * thrown will be a {@code RuntimeException} with cause {@code ex}.
848 jsr166 1.1 */
849     public void completeExceptionally(Throwable ex) {
850 dl 1.124 trySetException((ex instanceof RuntimeException) ||
851     (ex instanceof Error) ? ex :
852     new RuntimeException(ex));
853 jsr166 1.1 }
854    
855     /**
856     * Completes this task, and if not already aborted or cancelled,
857 dl 1.22 * returning the given value as the result of subsequent
858     * invocations of {@code join} and related operations. This method
859     * may be used to provide results for asynchronous tasks, or to
860     * provide alternative handling for tasks that would not otherwise
861     * complete normally. Its use in other situations is
862     * discouraged. This method is overridable, but overridden
863     * versions must invoke {@code super} implementation to maintain
864     * guarantees.
865 jsr166 1.1 *
866     * @param value the result value for this task
867     */
868     public void complete(V value) {
869     try {
870     setRawResult(value);
871     } catch (Throwable rex) {
872 dl 1.124 trySetException(rex);
873 jsr166 1.1 return;
874     }
875 dl 1.118 setDone();
876 jsr166 1.1 }
877    
878 jsr166 1.25 /**
879 dl 1.62 * Completes this task normally without setting a value. The most
880     * recent value established by {@link #setRawResult} (or {@code
881     * null} by default) will be returned as the result of subsequent
882     * invocations of {@code join} and related operations.
883     *
884     * @since 1.8
885 dl 1.60 */
886     public final void quietlyComplete() {
887 dl 1.118 setDone();
888 dl 1.60 }
889    
890     /**
891 dl 1.29 * Waits if necessary for the computation to complete, and then
892     * retrieves its result.
893     *
894     * @return the computed result
895     * @throws CancellationException if the computation was cancelled
896     * @throws ExecutionException if the computation threw an
897     * exception
898     * @throws InterruptedException if the current thread is not a
899     * member of a ForkJoinPool and was interrupted while waiting
900 jsr166 1.25 */
901 jsr166 1.1 public final V get() throws InterruptedException, ExecutionException {
902 dl 1.124 int s;
903     if (Thread.interrupted())
904     s = INTRPT;
905     else if ((s = status) >= 0)
906     s = awaitJoin(true, false);
907     if (s == INTRPT)
908     throw new InterruptedException();
909     else if ((s & THROWN) != 0)
910 dl 1.118 throw new ExecutionException(getThrowableException());
911     else if ((s & ABNORMAL) != 0)
912 dl 1.45 throw new CancellationException();
913 dl 1.118 else
914     return getRawResult();
915 jsr166 1.1 }
916 dl 1.14
917 jsr166 1.25 /**
918 dl 1.29 * Waits if necessary for at most the given time for the computation
919     * to complete, and then retrieves its result, if available.
920     *
921     * @param timeout the maximum time to wait
922     * @param unit the time unit of the timeout argument
923     * @return the computed result
924     * @throws CancellationException if the computation was cancelled
925     * @throws ExecutionException if the computation threw an
926     * exception
927     * @throws InterruptedException if the current thread is not a
928     * member of a ForkJoinPool and was interrupted while waiting
929     * @throws TimeoutException if the wait timed out
930 jsr166 1.25 */
931 jsr166 1.1 public final V get(long timeout, TimeUnit unit)
932     throws InterruptedException, ExecutionException, TimeoutException {
933 dl 1.124 long nanos = unit.toNanos(timeout);
934 dl 1.87 int s;
935 dl 1.59 if (Thread.interrupted())
936 dl 1.124 s = INTRPT;
937     else if ((s = status) >= 0 && nanos > 0L) {
938     long d = nanos + System.nanoTime();
939 jsr166 1.88 long deadline = (d == 0L) ? 1L : d; // avoid 0
940 dl 1.125 Thread t = Thread.currentThread();
941     ForkJoinPool p = (t instanceof ForkJoinWorkerThread) ?
942     ((ForkJoinWorkerThread)t).pool : ForkJoinPool.common;
943     if (p != null && p.preCompensate() == 0)
944 dl 1.124 p = null;
945     s = awaitDone(true, deadline, p);
946 dl 1.45 }
947 dl 1.124
948     if (s == INTRPT)
949     throw new InterruptedException();
950     else if (s >= 0)
951 dl 1.118 throw new TimeoutException();
952     else if ((s & THROWN) != 0)
953 dl 1.100 throw new ExecutionException(getThrowableException());
954 dl 1.118 else if ((s & ABNORMAL) != 0)
955     throw new CancellationException();
956     else
957     return getRawResult();
958 jsr166 1.1 }
959    
960     /**
961 dl 1.17 * Joins this task, without returning its result or throwing its
962 jsr166 1.1 * exception. This method may be useful when processing
963     * collections of tasks when some have been cancelled or otherwise
964     * known to have aborted.
965     */
966     public final void quietlyJoin() {
967 dl 1.124 if (status >= 0)
968     awaitJoin(false, false);
969 jsr166 1.1 }
970    
971     /**
972     * Commences performing this task and awaits its completion if
973 dl 1.17 * necessary, without returning its result or throwing its
974 dl 1.22 * exception.
975 jsr166 1.1 */
976     public final void quietlyInvoke() {
977 dl 1.124 if (doExec() >= 0)
978     awaitJoin(false, true);
979 jsr166 1.1 }
980    
981     /**
982     * Possibly executes tasks until the pool hosting the current task
983 jsr166 1.104 * {@linkplain ForkJoinPool#isQuiescent is quiescent}. This
984     * method may be of use in designs in which many tasks are forked,
985     * but none are explicitly joined, instead executing them until
986     * all are processed.
987 jsr166 1.1 */
988     public static void helpQuiesce() {
989 dl 1.124 Thread t; ForkJoinWorkerThread w; ForkJoinPool p;
990     if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread &&
991     (p = (w = (ForkJoinWorkerThread)t).pool) != null)
992     p.helpQuiescePool(w.workQueue);
993 dl 1.64 else
994 dl 1.71 ForkJoinPool.quiesceCommonPool();
995 jsr166 1.1 }
996    
997     /**
998     * Resets the internal bookkeeping state of this task, allowing a
999     * subsequent {@code fork}. This method allows repeated reuse of
1000     * this task, but only if reuse occurs when this task has either
1001     * never been forked, or has been forked, then completed and all
1002     * outstanding joins of this task have also completed. Effects
1003 jsr166 1.6 * under any other usage conditions are not guaranteed.
1004     * This method may be useful when executing
1005 jsr166 1.1 * pre-constructed trees of subtasks in loops.
1006 jsr166 1.34 *
1007 dl 1.33 * <p>Upon completion of this method, {@code isDone()} reports
1008     * {@code false}, and {@code getException()} reports {@code
1009     * null}. However, the value returned by {@code getRawResult} is
1010     * unaffected. To clear this value, you can invoke {@code
1011     * setRawResult(null)}.
1012 jsr166 1.1 */
1013     public void reinitialize() {
1014 dl 1.124 aux = null;
1015     status = 0;
1016 jsr166 1.1 }
1017    
1018     /**
1019 jsr166 1.103 * Returns the pool hosting the current thread, or {@code null}
1020     * if the current thread is executing outside of any ForkJoinPool.
1021     *
1022     * <p>This method returns {@code null} if and only if {@link
1023     * #inForkJoinPool} returns {@code false}.
1024 jsr166 1.1 *
1025 jsr166 1.97 * @return the pool, or {@code null} if none
1026 jsr166 1.1 */
1027     public static ForkJoinPool getPool() {
1028 dl 1.124 Thread t;
1029     return (((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) ?
1030     ((ForkJoinWorkerThread) t).pool : null);
1031 jsr166 1.1 }
1032    
1033     /**
1034 dl 1.42 * Returns {@code true} if the current thread is a {@link
1035     * ForkJoinWorkerThread} executing as a ForkJoinPool computation.
1036 jsr166 1.1 *
1037 dl 1.42 * @return {@code true} if the current thread is a {@link
1038     * ForkJoinWorkerThread} executing as a ForkJoinPool computation,
1039     * or {@code false} otherwise
1040 jsr166 1.1 */
1041     public static boolean inForkJoinPool() {
1042     return Thread.currentThread() instanceof ForkJoinWorkerThread;
1043     }
1044    
1045     /**
1046     * Tries to unschedule this task for execution. This method will
1047 dl 1.64 * typically (but is not guaranteed to) succeed if this task is
1048     * the most recently forked task by the current thread, and has
1049     * not commenced executing in another thread. This method may be
1050     * useful when arranging alternative local processing of tasks
1051     * that could have been, but were not, stolen.
1052 jsr166 1.1 *
1053 jsr166 1.4 * @return {@code true} if unforked
1054 jsr166 1.1 */
1055     public boolean tryUnfork() {
1056 dl 1.124 Thread t; ForkJoinPool.WorkQueue q;
1057 dl 1.66 return (((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) ?
1058 dl 1.124 (q = ((ForkJoinWorkerThread)t).workQueue) != null &&
1059     q.tryUnpush(this) :
1060     (q = ForkJoinPool.commonQueue()) != null &&
1061     q.externalTryUnpush(this));
1062 jsr166 1.1 }
1063    
1064     /**
1065     * Returns an estimate of the number of tasks that have been
1066     * forked by the current worker thread but not yet executed. This
1067     * value may be useful for heuristic decisions about whether to
1068     * fork other tasks.
1069     *
1070     * @return the number of tasks
1071     */
1072     public static int getQueuedTaskCount() {
1073 dl 1.66 Thread t; ForkJoinPool.WorkQueue q;
1074     if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread)
1075     q = ((ForkJoinWorkerThread)t).workQueue;
1076     else
1077 dl 1.124 q = ForkJoinPool.commonQueue();
1078 dl 1.66 return (q == null) ? 0 : q.queueSize();
1079 jsr166 1.1 }
1080    
1081     /**
1082     * Returns an estimate of how many more locally queued tasks are
1083     * held by the current worker thread than there are other worker
1084 dl 1.64 * threads that might steal them, or zero if this thread is not
1085     * operating in a ForkJoinPool. This value may be useful for
1086 jsr166 1.1 * heuristic decisions about whether to fork other tasks. In many
1087     * usages of ForkJoinTasks, at steady state, each worker should
1088     * aim to maintain a small constant surplus (for example, 3) of
1089     * tasks, and to process computations locally if this threshold is
1090     * exceeded.
1091     *
1092     * @return the surplus number of tasks, which may be negative
1093     */
1094     public static int getSurplusQueuedTaskCount() {
1095 dl 1.66 return ForkJoinPool.getSurplusQueuedTaskCount();
1096 jsr166 1.1 }
1097    
1098     // Extension methods
1099    
1100     /**
1101 jsr166 1.4 * Returns the result that would be returned by {@link #join}, even
1102     * if this task completed abnormally, or {@code null} if this task
1103     * is not known to have been completed. This method is designed
1104     * to aid debugging, as well as to support extensions. Its use in
1105     * any other context is discouraged.
1106 jsr166 1.1 *
1107 jsr166 1.4 * @return the result, or {@code null} if not completed
1108 jsr166 1.1 */
1109     public abstract V getRawResult();
1110    
1111     /**
1112     * Forces the given value to be returned as a result. This method
1113     * is designed to support extensions, and should not in general be
1114     * called otherwise.
1115     *
1116     * @param value the value
1117     */
1118     protected abstract void setRawResult(V value);
1119    
1120     /**
1121 dl 1.62 * Immediately performs the base action of this task and returns
1122     * true if, upon return from this method, this task is guaranteed
1123 dl 1.122 * to have completed. This method may return false otherwise, to
1124     * indicate that this task is not necessarily complete (or is not
1125     * known to be complete), for example in asynchronous actions that
1126     * require explicit invocations of completion methods. This method
1127     * may also throw an (unchecked) exception to indicate abnormal
1128     * exit. This method is designed to support extensions, and should
1129     * not in general be called otherwise.
1130 jsr166 1.1 *
1131 dl 1.62 * @return {@code true} if this task is known to have completed normally
1132 jsr166 1.1 */
1133     protected abstract boolean exec();
1134    
1135     /**
1136 jsr166 1.5 * Returns, but does not unschedule or execute, a task queued by
1137     * the current thread but not yet executed, if one is immediately
1138 dl 1.66 * available. There is no guarantee that this task will actually
1139     * be polled or executed next. Conversely, this method may return
1140     * null even if a task exists but cannot be accessed without
1141     * contention with other threads. This method is designed
1142 jsr166 1.5 * primarily to support extensions, and is unlikely to be useful
1143 jsr166 1.6 * otherwise.
1144     *
1145 jsr166 1.4 * @return the next task, or {@code null} if none are available
1146 jsr166 1.1 */
1147     protected static ForkJoinTask<?> peekNextLocalTask() {
1148 dl 1.66 Thread t; ForkJoinPool.WorkQueue q;
1149     if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread)
1150     q = ((ForkJoinWorkerThread)t).workQueue;
1151     else
1152 dl 1.124 q = ForkJoinPool.commonQueue();
1153 dl 1.66 return (q == null) ? null : q.peek();
1154 jsr166 1.1 }
1155    
1156     /**
1157     * Unschedules and returns, without executing, the next task
1158 dl 1.64 * queued by the current thread but not yet executed, if the
1159     * current thread is operating in a ForkJoinPool. This method is
1160     * designed primarily to support extensions, and is unlikely to be
1161     * useful otherwise.
1162 jsr166 1.1 *
1163 jsr166 1.4 * @return the next task, or {@code null} if none are available
1164 jsr166 1.1 */
1165     protected static ForkJoinTask<?> pollNextLocalTask() {
1166 dl 1.64 Thread t;
1167 dl 1.124 return (((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) ?
1168     ((ForkJoinWorkerThread)t).workQueue.nextLocalTask() : null);
1169 jsr166 1.1 }
1170    
1171     /**
1172 dl 1.64 * If the current thread is operating in a ForkJoinPool,
1173     * unschedules and returns, without executing, the next task
1174 jsr166 1.1 * queued by the current thread but not yet executed, if one is
1175     * available, or if not available, a task that was forked by some
1176     * other thread, if available. Availability may be transient, so a
1177 dl 1.64 * {@code null} result does not necessarily imply quiescence of
1178     * the pool this task is operating in. This method is designed
1179 jsr166 1.1 * primarily to support extensions, and is unlikely to be useful
1180 jsr166 1.6 * otherwise.
1181     *
1182 jsr166 1.4 * @return a task, or {@code null} if none are available
1183 jsr166 1.1 */
1184     protected static ForkJoinTask<?> pollTask() {
1185 dl 1.124 Thread t; ForkJoinWorkerThread w;
1186     return (((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) ?
1187     (w = (ForkJoinWorkerThread)t).pool.nextTaskFor(w.workQueue) :
1188     null);
1189 dl 1.54 }
1190    
1191 dl 1.94 /**
1192     * If the current thread is operating in a ForkJoinPool,
1193     * unschedules and returns, without executing, a task externally
1194     * submitted to the pool, if one is available. Availability may be
1195     * transient, so a {@code null} result does not necessarily imply
1196     * quiescence of the pool. This method is designed primarily to
1197     * support extensions, and is unlikely to be useful otherwise.
1198     *
1199     * @return a task, or {@code null} if none are available
1200 jsr166 1.107 * @since 9
1201 dl 1.94 */
1202     protected static ForkJoinTask<?> pollSubmission() {
1203 dl 1.96 Thread t;
1204 dl 1.124 return (((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) ?
1205     ((ForkJoinWorkerThread)t).pool.pollSubmission() : null);
1206 dl 1.94 }
1207    
1208 dl 1.60 // tag operations
1209 dl 1.54
1210     /**
1211 dl 1.60 * Returns the tag for this task.
1212 dl 1.54 *
1213 dl 1.60 * @return the tag for this task
1214 dl 1.54 * @since 1.8
1215     */
1216 dl 1.60 public final short getForkJoinTaskTag() {
1217     return (short)status;
1218 dl 1.54 }
1219    
1220     /**
1221 jsr166 1.102 * Atomically sets the tag value for this task and returns the old value.
1222 dl 1.54 *
1223 jsr166 1.102 * @param newValue the new tag value
1224 dl 1.60 * @return the previous value of the tag
1225 dl 1.54 * @since 1.8
1226     */
1227 jsr166 1.102 public final short setForkJoinTaskTag(short newValue) {
1228 dl 1.54 for (int s;;) {
1229 dl 1.124 if (casStatus(s = status, (s & ~SMASK) | (newValue & SMASK)))
1230 dl 1.60 return (short)s;
1231 dl 1.54 }
1232     }
1233    
1234     /**
1235 dl 1.60 * Atomically conditionally sets the tag value for this task.
1236     * Among other applications, tags can be used as visit markers
1237 dl 1.61 * in tasks operating on graphs, as in methods that check: {@code
1238 dl 1.60 * if (task.compareAndSetForkJoinTaskTag((short)0, (short)1))}
1239     * before processing, otherwise exiting because the node has
1240     * already been visited.
1241 dl 1.54 *
1242 jsr166 1.102 * @param expect the expected tag value
1243     * @param update the new tag value
1244 jsr166 1.76 * @return {@code true} if successful; i.e., the current value was
1245 jsr166 1.102 * equal to {@code expect} and was changed to {@code update}.
1246 dl 1.54 * @since 1.8
1247     */
1248 jsr166 1.102 public final boolean compareAndSetForkJoinTaskTag(short expect, short update) {
1249 dl 1.54 for (int s;;) {
1250 jsr166 1.102 if ((short)(s = status) != expect)
1251 dl 1.54 return false;
1252 dl 1.124 if (casStatus(s, (s & ~SMASK) | (update & SMASK)))
1253 dl 1.54 return true;
1254     }
1255 jsr166 1.1 }
1256    
1257 jsr166 1.5 /**
1258 jsr166 1.95 * Adapter for Runnables. This implements RunnableFuture
1259 jsr166 1.5 * to be compliant with AbstractExecutorService constraints
1260     * when used in ForkJoinPool.
1261     */
1262     static final class AdaptedRunnable<T> extends ForkJoinTask<T>
1263     implements RunnableFuture<T> {
1264 jsr166 1.123 @SuppressWarnings("serial") // Conditionally serializable
1265 jsr166 1.5 final Runnable runnable;
1266 jsr166 1.123 @SuppressWarnings("serial") // Conditionally serializable
1267 jsr166 1.5 T result;
1268     AdaptedRunnable(Runnable runnable, T result) {
1269     if (runnable == null) throw new NullPointerException();
1270     this.runnable = runnable;
1271 dl 1.59 this.result = result; // OK to set this even before completion
1272 jsr166 1.5 }
1273 dl 1.59 public final T getRawResult() { return result; }
1274     public final void setRawResult(T v) { result = v; }
1275     public final boolean exec() { runnable.run(); return true; }
1276     public final void run() { invoke(); }
1277 jsr166 1.116 public String toString() {
1278     return super.toString() + "[Wrapped task = " + runnable + "]";
1279     }
1280 dl 1.59 private static final long serialVersionUID = 5232453952276885070L;
1281     }
1282    
1283     /**
1284 jsr166 1.99 * Adapter for Runnables without results.
1285 dl 1.59 */
1286     static final class AdaptedRunnableAction extends ForkJoinTask<Void>
1287     implements RunnableFuture<Void> {
1288 jsr166 1.123 @SuppressWarnings("serial") // Conditionally serializable
1289 dl 1.59 final Runnable runnable;
1290     AdaptedRunnableAction(Runnable runnable) {
1291     if (runnable == null) throw new NullPointerException();
1292     this.runnable = runnable;
1293 jsr166 1.5 }
1294 dl 1.59 public final Void getRawResult() { return null; }
1295     public final void setRawResult(Void v) { }
1296     public final boolean exec() { runnable.run(); return true; }
1297     public final void run() { invoke(); }
1298 jsr166 1.116 public String toString() {
1299     return super.toString() + "[Wrapped task = " + runnable + "]";
1300     }
1301 jsr166 1.5 private static final long serialVersionUID = 5232453952276885070L;
1302     }
1303    
1304     /**
1305 jsr166 1.99 * Adapter for Runnables in which failure forces worker exception.
1306 dl 1.73 */
1307     static final class RunnableExecuteAction extends ForkJoinTask<Void> {
1308 jsr166 1.123 @SuppressWarnings("serial") // Conditionally serializable
1309 dl 1.73 final Runnable runnable;
1310     RunnableExecuteAction(Runnable runnable) {
1311     if (runnable == null) throw new NullPointerException();
1312     this.runnable = runnable;
1313     }
1314     public final Void getRawResult() { return null; }
1315     public final void setRawResult(Void v) { }
1316     public final boolean exec() { runnable.run(); return true; }
1317 dl 1.124 int trySetException(Throwable ex) {
1318     int s;
1319     if (isExceptionalStatus(s = trySetThrown(ex)))
1320     rethrow(ex); // rethrow outside exec() catches.
1321     return s;
1322 dl 1.73 }
1323     private static final long serialVersionUID = 5232453952276885070L;
1324     }
1325    
1326     /**
1327 jsr166 1.99 * Adapter for Callables.
1328 jsr166 1.5 */
1329     static final class AdaptedCallable<T> extends ForkJoinTask<T>
1330     implements RunnableFuture<T> {
1331 jsr166 1.123 @SuppressWarnings("serial") // Conditionally serializable
1332 jsr166 1.6 final Callable<? extends T> callable;
1333 jsr166 1.123 @SuppressWarnings("serial") // Conditionally serializable
1334 jsr166 1.5 T result;
1335 jsr166 1.6 AdaptedCallable(Callable<? extends T> callable) {
1336 jsr166 1.5 if (callable == null) throw new NullPointerException();
1337     this.callable = callable;
1338     }
1339 dl 1.59 public final T getRawResult() { return result; }
1340     public final void setRawResult(T v) { result = v; }
1341     public final boolean exec() {
1342 jsr166 1.5 try {
1343     result = callable.call();
1344     return true;
1345     } catch (RuntimeException rex) {
1346     throw rex;
1347     } catch (Exception ex) {
1348     throw new RuntimeException(ex);
1349     }
1350     }
1351 dl 1.59 public final void run() { invoke(); }
1352 jsr166 1.116 public String toString() {
1353     return super.toString() + "[Wrapped task = " + callable + "]";
1354     }
1355 jsr166 1.117 private static final long serialVersionUID = 2838392045355241008L;
1356 jsr166 1.5 }
1357 jsr166 1.2
1358     /**
1359 jsr166 1.6 * Returns a new {@code ForkJoinTask} that performs the {@code run}
1360     * method of the given {@code Runnable} as its action, and returns
1361     * a null result upon {@link #join}.
1362 jsr166 1.2 *
1363     * @param runnable the runnable action
1364     * @return the task
1365     */
1366 jsr166 1.6 public static ForkJoinTask<?> adapt(Runnable runnable) {
1367 dl 1.59 return new AdaptedRunnableAction(runnable);
1368 jsr166 1.2 }
1369    
1370     /**
1371 jsr166 1.6 * Returns a new {@code ForkJoinTask} that performs the {@code run}
1372     * method of the given {@code Runnable} as its action, and returns
1373     * the given result upon {@link #join}.
1374 jsr166 1.2 *
1375     * @param runnable the runnable action
1376     * @param result the result upon completion
1377 jsr166 1.82 * @param <T> the type of the result
1378 jsr166 1.2 * @return the task
1379     */
1380     public static <T> ForkJoinTask<T> adapt(Runnable runnable, T result) {
1381 jsr166 1.5 return new AdaptedRunnable<T>(runnable, result);
1382 jsr166 1.2 }
1383    
1384     /**
1385 jsr166 1.6 * Returns a new {@code ForkJoinTask} that performs the {@code call}
1386     * method of the given {@code Callable} as its action, and returns
1387     * its result upon {@link #join}, translating any checked exceptions
1388     * encountered into {@code RuntimeException}.
1389 jsr166 1.2 *
1390     * @param callable the callable action
1391 jsr166 1.82 * @param <T> the type of the callable's result
1392 jsr166 1.2 * @return the task
1393     */
1394 jsr166 1.6 public static <T> ForkJoinTask<T> adapt(Callable<? extends T> callable) {
1395 jsr166 1.5 return new AdaptedCallable<T>(callable);
1396 jsr166 1.2 }
1397    
1398 jsr166 1.1 // Serialization support
1399    
1400     private static final long serialVersionUID = -7721805057305804111L;
1401    
1402     /**
1403 jsr166 1.53 * Saves this task to a stream (that is, serializes it).
1404 jsr166 1.1 *
1405 jsr166 1.83 * @param s the stream
1406 jsr166 1.84 * @throws java.io.IOException if an I/O error occurs
1407 jsr166 1.1 * @serialData the current run status and the exception thrown
1408 jsr166 1.4 * during execution, or {@code null} if none
1409 jsr166 1.1 */
1410     private void writeObject(java.io.ObjectOutputStream s)
1411     throws java.io.IOException {
1412 dl 1.124 Aux a;
1413 jsr166 1.1 s.defaultWriteObject();
1414 dl 1.124 s.writeObject((a = aux) == null ? null : a.ex);
1415 jsr166 1.1 }
1416    
1417     /**
1418 jsr166 1.53 * Reconstitutes this task from a stream (that is, deserializes it).
1419 jsr166 1.83 * @param s the stream
1420 jsr166 1.84 * @throws ClassNotFoundException if the class of a serialized object
1421     * could not be found
1422     * @throws java.io.IOException if an I/O error occurs
1423 jsr166 1.1 */
1424     private void readObject(java.io.ObjectInputStream s)
1425     throws java.io.IOException, ClassNotFoundException {
1426     s.defaultReadObject();
1427     Object ex = s.readObject();
1428     if (ex != null)
1429 dl 1.124 trySetThrown((Throwable)ex);
1430 jsr166 1.1 }
1431    
1432 dl 1.45 static {
1433 jsr166 1.1 try {
1434 dl 1.109 MethodHandles.Lookup l = MethodHandles.lookup();
1435     STATUS = l.findVarHandle(ForkJoinTask.class, "status", int.class);
1436 dl 1.124 AUX = l.findVarHandle(ForkJoinTask.class, "aux", Aux.class);
1437 jsr166 1.91 } catch (ReflectiveOperationException e) {
1438 jsr166 1.120 throw new ExceptionInInitializerError(e);
1439 jsr166 1.1 }
1440     }
1441 dl 1.45
1442 jsr166 1.1 }