ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinTask.java
Revision: 1.158
Committed: Fri May 6 16:03:05 2022 UTC (2 years ago) by dl
Branch: MAIN
CVS Tags: HEAD
Changes since 1.157: +4 -2 lines
Log Message:
sync with openjdk

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