ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinTask.java
Revision: 1.130
Committed: Mon Feb 3 21:07:49 2020 UTC (4 years, 3 months ago) by dl
Branch: MAIN
Changes since 1.129: +11 -0 lines
Log Message:
fix termination; add documentation

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