ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinTask.java
Revision: 1.141
Committed: Wed Aug 12 00:06:59 2020 UTC (3 years, 9 months ago) by jsr166
Branch: MAIN
Changes since 1.140: +0 -1 lines
Log Message:
fix errorprone [RemoveUnusedImports]

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