ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinTask.java
Revision: 1.155
Committed: Fri Mar 18 16:01:42 2022 UTC (2 years, 2 months ago) by dl
Branch: MAIN
Changes since 1.154: +185 -149 lines
Log Message:
jdk17+ suppressWarnings, FJ updates

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     * @since 1.7
172     * @author Doug Lea
173     */
174     public abstract class ForkJoinTask<V> implements Future<V>, Serializable {
175    
176 dl 1.13 /*
177     * See the internal documentation of class ForkJoinPool for a
178     * general implementation overview. ForkJoinTasks are mainly
179     * responsible for maintaining their "status" field amidst relays
180 jsr166 1.51 * to methods in ForkJoinWorkerThread and ForkJoinPool.
181     *
182     * The methods of this class are more-or-less layered into
183     * (1) basic status maintenance
184     * (2) execution and awaiting completion
185     * (3) user-level methods that additionally report results.
186     * This is sometimes hard to see because this file orders exported
187     * methods in a way that flows well in javadocs.
188 dl 1.118 *
189 dl 1.155 * Revision notes: This class uses jdk-internal Unsafe for atomics
190     * and special memory modes, rather than VarHandles, to avoid
191     * initialization dependencies in other jdk components that
192     * require early parallelism. It also simplifies handling of
193     * pool-submitted tasks, among other minor improvements.
194 dl 1.118 */
195 jsr166 1.1
196     /**
197 dl 1.124 * Nodes for threads waiting for completion, or holding a thrown
198     * exception (never both). Waiting threads prepend nodes
199     * Treiber-stack-style. Signallers detach and unpark
200     * waiters. Cancelled waiters try to unsplice.
201     */
202     static final class Aux {
203     final Thread thread;
204     final Throwable ex; // null if a waiter
205     Aux next; // accessed only via memory-acquire chains
206     Aux(Thread thread, Throwable ex) {
207     this.thread = thread;
208     this.ex = ex;
209     }
210     final boolean casNext(Aux c, Aux v) { // used only in cancellation
211 dl 1.155 return U.compareAndSetReference(this, NEXT, c, v);
212 dl 1.124 }
213 dl 1.154 private static final Unsafe U;
214     private static final long NEXT;
215 dl 1.124 static {
216 dl 1.154 U = Unsafe.getUnsafe();
217     NEXT = U.objectFieldOffset(Aux.class, "next");
218 dl 1.13 }
219 jsr166 1.1 }
220    
221 dl 1.124 /*
222     * The status field holds bits packed into a single int to ensure
223     * atomicity. Status is initially zero, and takes on nonnegative
224     * values until completed, upon which it holds (sign bit) DONE,
225     * possibly with ABNORMAL (cancelled or exceptional) and THROWN
226 dl 1.128 * (in which case an exception has been stored). A value of
227     * ABNORMAL without DONE signifies an interrupted wait. These
228     * control bits occupy only (some of) the upper half (16 bits) of
229     * status field. The lower bits are used for user-defined tags.
230 jsr166 1.1 */
231 dl 1.155 static final int DONE = 1 << 31; // must be negative
232     static final int ABNORMAL = 1 << 16;
233     static final int THROWN = 1 << 17;
234     static final int SMASK = 0xffff; // short bits for tags
235     static final int UNCOMPENSATE = 1 << 16; // helpJoin return sentinel
236     static final int POOLSUBMIT = 1 << 18; // for pool.submit vs fork
237 dl 1.124
238     // Fields
239     volatile int status; // accessed directly by pool and workers
240     private transient volatile Aux aux; // either waiters or thrown Exception
241 dl 1.128
242 dl 1.124 // Support for atomic operations
243 dl 1.154 private static final Unsafe U;
244     private static final long STATUS;
245     private static final long AUX;
246 dl 1.124 private int getAndBitwiseOrStatus(int v) {
247 dl 1.154 return U.getAndBitwiseOrInt(this, STATUS, v);
248 dl 1.124 }
249     private boolean casStatus(int c, int v) {
250 dl 1.154 return U.compareAndSetInt(this, STATUS, c, v);
251 dl 1.124 }
252     private boolean casAux(Aux c, Aux v) {
253 dl 1.155 return U.compareAndSetReference(this, AUX, c, v);
254     }
255    
256     /**
257     * Marks this task as an external pool submission.
258     */
259     final void markPoolSubmission() {
260     getAndBitwiseOrStatus(POOLSUBMIT);
261 dl 1.124 }
262    
263     /** Removes and unparks waiters */
264     private void signalWaiters() {
265     for (Aux a; (a = aux) != null && a.ex == null; ) {
266     if (casAux(a, null)) { // detach entire list
267     for (Thread t; a != null; a = a.next) {
268     if ((t = a.thread) != Thread.currentThread() && t != null)
269     LockSupport.unpark(t); // don't self-signal
270     }
271     break;
272 dl 1.54 }
273 jsr166 1.1 }
274     }
275    
276     /**
277 dl 1.124 * Sets DONE status and wakes up threads waiting to join this task.
278     * @return status on exit
279 jsr166 1.1 */
280 dl 1.124 private int setDone() {
281     int s = getAndBitwiseOrStatus(DONE) | DONE;
282     signalWaiters();
283 dl 1.45 return s;
284     }
285    
286     /**
287 dl 1.124 * Sets ABNORMAL DONE status unless already done, and wakes up threads
288     * waiting to join this task.
289     * @return status on exit
290 dl 1.118 */
291 dl 1.124 private int trySetCancelled() {
292 dl 1.118 int s;
293 dl 1.124 do {} while ((s = status) >= 0 && !casStatus(s, s |= (DONE | ABNORMAL)));
294     signalWaiters();
295     return s;
296 dl 1.118 }
297    
298     /**
299 dl 1.124 * Records exception and sets ABNORMAL THROWN DONE status unless
300     * already done, and wakes up threads waiting to join this task.
301     * If losing a race with setDone or trySetCancelled, the exception
302     * may be recorded but not reported.
303 dl 1.54 *
304 dl 1.124 * @return status on exit
305 dl 1.45 */
306 dl 1.124 final int trySetThrown(Throwable ex) {
307     Aux h = new Aux(Thread.currentThread(), ex), p = null;
308     boolean installed = false;
309     int s;
310     while ((s = status) >= 0) {
311     Aux a;
312     if (!installed && ((a = aux) == null || a.ex == null) &&
313     (installed = casAux(a, h)))
314     p = a; // list of waiters replaced by h
315     if (installed && casStatus(s, s |= (DONE | ABNORMAL | THROWN)))
316     break;
317     }
318     for (; p != null; p = p.next)
319     LockSupport.unpark(p.thread);
320     return s;
321 jsr166 1.1 }
322    
323     /**
324 dl 1.124 * Records exception unless already done. Overridable in subclasses.
325 dl 1.54 *
326 dl 1.124 * @return status on exit
327 jsr166 1.1 */
328 dl 1.124 int trySetException(Throwable ex) {
329     return trySetThrown(ex);
330 dl 1.45 }
331    
332 jsr166 1.139 /**
333     * Constructor for subclasses to call.
334     */
335     public ForkJoinTask() {}
336    
337 dl 1.124 static boolean isExceptionalStatus(int s) { // needed by subclasses
338     return (s & THROWN) != 0;
339 dl 1.45 }
340    
341     /**
342 dl 1.124 * Unless done, calls exec and records status if completed, but
343     * doesn't wait for completion otherwise.
344 dl 1.45 *
345 dl 1.124 * @return status on exit from this method
346 dl 1.45 */
347 dl 1.124 final int doExec() {
348     int s; boolean completed;
349 dl 1.62 if ((s = status) >= 0) {
350     try {
351 dl 1.124 completed = exec();
352     } catch (Throwable rex) {
353     s = trySetException(rex);
354     completed = false;
355 dl 1.45 }
356 dl 1.124 if (completed)
357     s = setDone();
358 dl 1.45 }
359 dl 1.62 return s;
360     }
361    
362     /**
363 dl 1.134 * Helps and/or waits for completion from join, get, or invoke;
364     * called from either internal or external threads.
365 dl 1.63 *
366 dl 1.155 * @param s last known status
367 dl 1.128 * @param ran true if task known to have been exec'd
368 dl 1.134 * @param interruptible true if park interruptibly when external
369 dl 1.155 * @param deadline if timed, timeout deadline, else 0
370 dl 1.134 * @return ABNORMAL if interrupted, else status on exit
371     */
372 dl 1.155 private int awaitDone(int s, boolean ran, boolean interruptible,
373     long deadline) {
374     Thread t; ForkJoinWorkerThread wt;
375     ForkJoinPool p = null, cp;
376 dl 1.152 ForkJoinPool.WorkQueue q = null;
377 dl 1.155 boolean owned = false, uncompensate = false;
378 dl 1.152 if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) {
379 dl 1.155 owned = true;
380     q = (wt = (ForkJoinWorkerThread)t).workQueue;
381 dl 1.152 p = wt.pool;
382 dl 1.124 }
383 dl 1.155 else if ((s & POOLSUBMIT) == 0 && (cp = ForkJoinPool.common) != null &&
384     (q = cp.externalQueue()) != null)
385     p = cp;
386     if (q != null && p != null) { // try helping
387     boolean timed = (deadline != 0L);
388     if (this instanceof CountedCompleter)
389     s = p.helpComplete(this, q, owned, timed);
390     else if (ran || (s = q.tryRemoveAndExec(this, owned)) >= 0)
391     s = (owned) ? p.helpJoin(this, q, timed) : 0;
392     if (s < 0)
393     return s;
394     else if (s == UNCOMPENSATE)
395     uncompensate = true;
396 dl 1.128 }
397 dl 1.155 Aux node = null;
398 dl 1.152 boolean interrupted = false, queued = false;
399 dl 1.155 for (boolean parked = false, fail = false;;) {
400 dl 1.152 Aux a; long ns;
401 dl 1.155 if ((s = status) < 0)
402     break;
403     else if (fail || (fail = (p != null && p.runState < 0)))
404 dl 1.152 casStatus(s, s | (DONE | ABNORMAL)); // try to cancel
405     else if (queued) {
406 dl 1.155 if (parked && Thread.interrupted()) {
407     interrupted = true;
408     if (interruptible) {
409     s = ABNORMAL;
410 dl 1.152 break;
411 dl 1.155 }
412     }
413     parked = true;
414     if (deadline == 0L)
415     LockSupport.park();
416     else if ((ns = deadline - System.nanoTime()) > 0L)
417 dl 1.152 LockSupport.parkNanos(ns);
418     else
419 dl 1.155 break;
420 dl 1.152 }
421     else if (node != null) {
422 dl 1.155 if (((a = aux) == null || a.ex == null) &&
423     (queued = casAux(node.next = a, node)))
424 dl 1.152 LockSupport.setCurrentBlocker(this);
425     }
426     else {
427     try {
428     node = new Aux(Thread.currentThread(), null);
429     } catch (Throwable ex) { // cannot create
430     fail = true;
431     }
432     }
433     }
434 dl 1.155 if (p != null && uncompensate)
435     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     if ((s & ABNORMAL) != 0 &&
529     ((s & THROWN) == 0 || (ex = getThrowableException()) == null))
530     ex = new CancellationException();
531     return ex;
532     }
533    
534     /**
535 dl 1.124 * Throws exception associated with the given status, or
536     * CancellationException if none recorded.
537 dl 1.45 */
538 dl 1.124 private void reportException(int s) {
539     ForkJoinTask.<RuntimeException>uncheckedThrow(
540     (s & THROWN) != 0 ? getThrowableException() : null);
541 dl 1.45 }
542    
543     /**
544 dl 1.129 * Throws exception for (timed or untimed) get, wrapping if
545     * necessary in an ExecutionException.
546     */
547 dl 1.134 private void reportExecutionException(int s) {
548 dl 1.129 Throwable ex = null;
549     if (s == ABNORMAL)
550     ex = new InterruptedException();
551     else if (s >= 0)
552     ex = new TimeoutException();
553     else if ((s & THROWN) != 0 && (ex = getThrowableException()) != null)
554     ex = new ExecutionException(ex);
555     ForkJoinTask.<RuntimeException>uncheckedThrow(ex);
556     }
557    
558     /**
559 dl 1.124 * A version of "sneaky throw" to relay exceptions in other
560     * contexts.
561 dl 1.65 */
562 jsr166 1.78 static void rethrow(Throwable ex) {
563 dl 1.100 ForkJoinTask.<RuntimeException>uncheckedThrow(ex);
564 dl 1.65 }
565    
566     /**
567     * The sneaky part of sneaky throw, relying on generics
568     * limitations to evade compiler complaints about rethrowing
569 dl 1.124 * unchecked exceptions. If argument null, throws
570     * CancellationException.
571 dl 1.65 */
572     @SuppressWarnings("unchecked") static <T extends Throwable>
573 dl 1.100 void uncheckedThrow(Throwable t) throws T {
574 dl 1.124 if (t == null)
575     t = new CancellationException();
576     throw (T)t; // rely on vacuous cast
577 jsr166 1.1 }
578    
579     // public methods
580    
581     /**
582 dl 1.64 * Arranges to asynchronously execute this task in the pool the
583     * current task is running in, if applicable, or using the {@link
584 dl 1.67 * ForkJoinPool#commonPool()} if not {@link #inForkJoinPool}. While
585 dl 1.64 * it is not necessarily enforced, it is a usage error to fork a
586     * task more than once unless it has completed and been
587     * reinitialized. Subsequent modifications to the state of this
588     * task or any data it operates on are not necessarily
589     * consistently observable by any thread other than the one
590     * executing it unless preceded by a call to {@link #join} or
591     * related methods, or a call to {@link #isDone} returning {@code
592     * true}.
593 jsr166 1.2 *
594 jsr166 1.6 * @return {@code this}, to simplify usage
595 jsr166 1.1 */
596 jsr166 1.2 public final ForkJoinTask<V> fork() {
597 dl 1.155 Thread t; ForkJoinWorkerThread wt;
598     ForkJoinPool p; ForkJoinPool.WorkQueue q;
599     if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) {
600     p = (wt = (ForkJoinWorkerThread)t).pool;
601     q = wt.workQueue;
602     }
603 dl 1.64 else
604 dl 1.155 q = (p = ForkJoinPool.common).submissionQueue(false);
605     q.push(this, p, true);
606 jsr166 1.2 return this;
607 jsr166 1.1 }
608    
609     /**
610 jsr166 1.115 * Returns the result of the computation when it
611     * {@linkplain #isDone is done}.
612     * This method differs from {@link #get()} in that abnormal
613     * completion results in {@code RuntimeException} or {@code Error},
614     * not {@code ExecutionException}, and that interrupts of the
615     * calling thread do <em>not</em> cause the method to abruptly
616     * return by throwing {@code InterruptedException}.
617 jsr166 1.1 *
618     * @return the computed result
619     */
620     public final V join() {
621 dl 1.59 int s;
622 dl 1.124 if ((s = status) >= 0)
623 dl 1.155 s = awaitDone(s, false, false, 0L);
624 dl 1.124 if ((s & ABNORMAL) != 0)
625 dl 1.59 reportException(s);
626     return getRawResult();
627 jsr166 1.1 }
628    
629     /**
630     * Commences performing this task, awaits its completion if
631 jsr166 1.21 * necessary, and returns its result, or throws an (unchecked)
632 dl 1.20 * {@code RuntimeException} or {@code Error} if the underlying
633     * computation did so.
634 jsr166 1.1 *
635     * @return the computed result
636     */
637     public final V invoke() {
638 dl 1.59 int s;
639 dl 1.124 if ((s = doExec()) >= 0)
640 dl 1.155 s = awaitDone(s, true, false, 0L);
641 dl 1.124 if ((s & ABNORMAL) != 0)
642 dl 1.59 reportException(s);
643     return getRawResult();
644 jsr166 1.1 }
645    
646     /**
647 jsr166 1.8 * Forks the given tasks, returning when {@code isDone} holds for
648     * each task or an (unchecked) exception is encountered, in which
649 dl 1.20 * case the exception is rethrown. If more than one task
650     * encounters an exception, then this method throws any one of
651     * these exceptions. If any task encounters an exception, the
652     * other may be cancelled. However, the execution status of
653     * individual tasks is not guaranteed upon exceptional return. The
654     * status of each task may be obtained using {@link
655     * #getException()} and related methods to check if they have been
656     * cancelled, completed normally or exceptionally, or left
657     * unprocessed.
658 jsr166 1.6 *
659     * @param t1 the first task
660     * @param t2 the second task
661     * @throws NullPointerException if any task is null
662 jsr166 1.1 */
663 jsr166 1.6 public static void invokeAll(ForkJoinTask<?> t1, ForkJoinTask<?> t2) {
664 dl 1.59 int s1, s2;
665 dl 1.124 if (t1 == null || t2 == null)
666     throw new NullPointerException();
667 jsr166 1.1 t2.fork();
668 dl 1.124 if ((s1 = t1.doExec()) >= 0)
669 dl 1.155 s1 = t1.awaitDone(s1, true, false, 0L);
670 dl 1.128 if ((s1 & ABNORMAL) != 0) {
671     cancelIgnoringExceptions(t2);
672 dl 1.59 t1.reportException(s1);
673 dl 1.128 }
674 dl 1.155 else {
675     if ((s2 = t2.status) >= 0)
676     s2 = t2.awaitDone(s2, false, false, 0L);
677     if ((s2 & ABNORMAL) != 0)
678     t2.reportException(s2);
679     }
680 jsr166 1.1 }
681    
682     /**
683 jsr166 1.6 * Forks the given tasks, returning when {@code isDone} holds for
684 jsr166 1.8 * each task or an (unchecked) exception is encountered, in which
685 dl 1.20 * case the exception is rethrown. If more than one task
686     * encounters an exception, then this method throws any one of
687     * these exceptions. If any task encounters an exception, others
688     * may be cancelled. However, the execution status of individual
689     * tasks is not guaranteed upon exceptional return. The status of
690     * each task may be obtained using {@link #getException()} and
691     * related methods to check if they have been cancelled, completed
692     * normally or exceptionally, or left unprocessed.
693 jsr166 1.6 *
694     * @param tasks the tasks
695 jsr166 1.8 * @throws NullPointerException if any task is null
696 jsr166 1.1 */
697     public static void invokeAll(ForkJoinTask<?>... tasks) {
698     Throwable ex = null;
699     int last = tasks.length - 1;
700 jsr166 1.144 for (int i = last; i >= 0; --i) {
701 dl 1.124 ForkJoinTask<?> t;
702     if ((t = tasks[i]) == null) {
703     ex = new NullPointerException();
704     break;
705 jsr166 1.1 }
706 dl 1.124 if (i == 0) {
707 jsr166 1.144 int s;
708 dl 1.124 if ((s = t.doExec()) >= 0)
709 dl 1.155 s = t.awaitDone(s, true, false, 0L);
710 dl 1.124 if ((s & ABNORMAL) != 0)
711 dl 1.128 ex = t.getException(s);
712 dl 1.124 break;
713 jsr166 1.1 }
714 dl 1.124 t.fork();
715 jsr166 1.1 }
716 dl 1.124 if (ex == null) {
717 jsr166 1.144 for (int i = 1; i <= last; ++i) {
718 dl 1.124 ForkJoinTask<?> t;
719     if ((t = tasks[i]) != null) {
720 jsr166 1.144 int s;
721 dl 1.124 if ((s = t.status) >= 0)
722 dl 1.155 s = t.awaitDone(s, false, false, 0L);
723 dl 1.128 if ((s & ABNORMAL) != 0 && (ex = t.getException(s)) != null)
724 dl 1.124 break;
725     }
726     }
727     }
728 dl 1.128 if (ex != null) {
729 jsr166 1.143 for (int i = 1; i <= last; ++i)
730 dl 1.128 cancelIgnoringExceptions(tasks[i]);
731 dl 1.65 rethrow(ex);
732 dl 1.128 }
733 jsr166 1.1 }
734    
735     /**
736 jsr166 1.7 * Forks all tasks in the specified collection, returning when
737 jsr166 1.8 * {@code isDone} holds for each task or an (unchecked) exception
738 dl 1.20 * is encountered, in which case the exception is rethrown. If
739     * more than one task encounters an exception, then this method
740     * throws any one of these exceptions. If any task encounters an
741     * exception, others may be cancelled. However, the execution
742     * status of individual tasks is not guaranteed upon exceptional
743     * return. The status of each task may be obtained using {@link
744     * #getException()} and related methods to check if they have been
745     * cancelled, completed normally or exceptionally, or left
746     * unprocessed.
747 jsr166 1.6 *
748 jsr166 1.1 * @param tasks the collection of tasks
749 jsr166 1.82 * @param <T> the type of the values returned from the tasks
750 jsr166 1.2 * @return the tasks argument, to simplify usage
751 jsr166 1.1 * @throws NullPointerException if tasks or any element are null
752     */
753 jsr166 1.2 public static <T extends ForkJoinTask<?>> Collection<T> invokeAll(Collection<T> tasks) {
754 jsr166 1.7 if (!(tasks instanceof RandomAccess) || !(tasks instanceof List<?>)) {
755 jsr166 1.121 invokeAll(tasks.toArray(new ForkJoinTask<?>[0]));
756 jsr166 1.2 return tasks;
757 jsr166 1.1 }
758     @SuppressWarnings("unchecked")
759     List<? extends ForkJoinTask<?>> ts =
760     (List<? extends ForkJoinTask<?>>) tasks;
761     Throwable ex = null;
762 dl 1.124 int last = ts.size() - 1; // nearly same as array version
763 jsr166 1.144 for (int i = last; i >= 0; --i) {
764 dl 1.124 ForkJoinTask<?> t;
765     if ((t = ts.get(i)) == null) {
766     ex = new NullPointerException();
767     break;
768 jsr166 1.1 }
769 dl 1.124 if (i == 0) {
770 jsr166 1.144 int s;
771 dl 1.124 if ((s = t.doExec()) >= 0)
772 dl 1.155 s = t.awaitDone(s, true, false, 0L);
773 dl 1.124 if ((s & ABNORMAL) != 0)
774 dl 1.128 ex = t.getException(s);
775 dl 1.124 break;
776     }
777     t.fork();
778     }
779     if (ex == null) {
780 jsr166 1.144 for (int i = 1; i <= last; ++i) {
781 dl 1.124 ForkJoinTask<?> t;
782     if ((t = ts.get(i)) != null) {
783 jsr166 1.144 int s;
784 dl 1.124 if ((s = t.status) >= 0)
785 dl 1.155 s = t.awaitDone(s, false, false, 0L);
786 dl 1.128 if ((s & ABNORMAL) != 0 && (ex = t.getException(s)) != null)
787 dl 1.124 break;
788     }
789 jsr166 1.1 }
790     }
791 dl 1.128 if (ex != null) {
792 jsr166 1.142 for (int i = 1; i <= last; ++i)
793 dl 1.128 cancelIgnoringExceptions(ts.get(i));
794 dl 1.65 rethrow(ex);
795 dl 1.128 }
796 jsr166 1.2 return tasks;
797 jsr166 1.1 }
798 jsr166 1.135
799 jsr166 1.1 /**
800 jsr166 1.7 * Attempts to cancel execution of this task. This attempt will
801 jsr166 1.36 * fail if the task has already completed or could not be
802     * cancelled for some other reason. If successful, and this task
803     * has not started when {@code cancel} is called, execution of
804 dl 1.38 * this task is suppressed. After this method returns
805     * successfully, unless there is an intervening call to {@link
806     * #reinitialize}, subsequent calls to {@link #isCancelled},
807     * {@link #isDone}, and {@code cancel} will return {@code true}
808     * and calls to {@link #join} and related methods will result in
809     * {@code CancellationException}.
810 jsr166 1.1 *
811     * <p>This method may be overridden in subclasses, but if so, must
812 dl 1.38 * still ensure that these properties hold. In particular, the
813     * {@code cancel} method itself must not throw exceptions.
814 jsr166 1.1 *
815 jsr166 1.6 * <p>This method is designed to be invoked by <em>other</em>
816 jsr166 1.1 * tasks. To terminate the current task, you can just return or
817     * throw an unchecked exception from its computation method, or
818 jsr166 1.74 * invoke {@link #completeExceptionally(Throwable)}.
819 jsr166 1.1 *
820 dl 1.38 * @param mayInterruptIfRunning this value has no effect in the
821     * default implementation because interrupts are not used to
822     * control cancellation.
823 jsr166 1.1 *
824 jsr166 1.4 * @return {@code true} if this task is now cancelled
825 jsr166 1.1 */
826     public boolean cancel(boolean mayInterruptIfRunning) {
827 dl 1.124 return (trySetCancelled() & (ABNORMAL | THROWN)) == ABNORMAL;
828 jsr166 1.1 }
829    
830 jsr166 1.8 public final boolean isDone() {
831     return status < 0;
832     }
833    
834     public final boolean isCancelled() {
835 dl 1.118 return (status & (ABNORMAL | THROWN)) == ABNORMAL;
836 jsr166 1.8 }
837    
838     /**
839 jsr166 1.4 * Returns {@code true} if this task threw an exception or was cancelled.
840 jsr166 1.1 *
841 jsr166 1.4 * @return {@code true} if this task threw an exception or was cancelled
842 jsr166 1.1 */
843     public final boolean isCompletedAbnormally() {
844 dl 1.118 return (status & ABNORMAL) != 0;
845 jsr166 1.1 }
846    
847     /**
848 jsr166 1.8 * Returns {@code true} if this task completed without throwing an
849     * exception and was not cancelled.
850     *
851     * @return {@code true} if this task completed without throwing an
852     * exception and was not cancelled
853     */
854     public final boolean isCompletedNormally() {
855 dl 1.118 return (status & (DONE | ABNORMAL)) == DONE;
856 jsr166 1.8 }
857    
858 dl 1.155 @Override
859     public State state() {
860     int s = status;
861     return (s >= 0) ? State.RUNNING :
862     ((s & (DONE | ABNORMAL)) == DONE) ? State.SUCCESS:
863     ((s & (ABNORMAL | THROWN)) == (ABNORMAL | THROWN)) ? State.FAILED :
864     State.CANCELLED;
865     }
866    
867     @Override
868     public V resultNow() {
869     if (!isCompletedNormally())
870     throw new IllegalStateException();
871     return getRawResult();
872     }
873    
874     @Override
875     public Throwable exceptionNow() {
876     if ((status & (ABNORMAL | THROWN)) != (ABNORMAL | THROWN))
877     throw new IllegalStateException();
878     return getThrowableException();
879     }
880    
881 jsr166 1.8 /**
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.155 int s;
960     if (Thread.interrupted())
961     s = ABNORMAL;
962     else if ((s = status) >= 0)
963     s = awaitDone(s, false, true, 0L);
964 dl 1.151 if ((s & ABNORMAL) != 0)
965 dl 1.134 reportExecutionException(s);
966 dl 1.129 return getRawResult();
967 jsr166 1.1 }
968 dl 1.14
969 jsr166 1.25 /**
970 dl 1.29 * Waits if necessary for at most the given time for the computation
971     * to complete, and then retrieves its result, if available.
972     *
973     * @param timeout the maximum time to wait
974     * @param unit the time unit of the timeout argument
975     * @return the computed result
976     * @throws CancellationException if the computation was cancelled
977     * @throws ExecutionException if the computation threw an
978     * exception
979     * @throws InterruptedException if the current thread is not a
980     * member of a ForkJoinPool and was interrupted while waiting
981     * @throws TimeoutException if the wait timed out
982 jsr166 1.25 */
983 jsr166 1.1 public final V get(long timeout, TimeUnit unit)
984     throws InterruptedException, ExecutionException, TimeoutException {
985 dl 1.155 long nanos = unit.toNanos(timeout), deadline;
986     int s;
987     if (Thread.interrupted())
988     s = ABNORMAL;
989     else if ((s = status) >= 0 && nanos > 0L) {
990     if ((deadline = nanos + System.nanoTime()) == 0L)
991     deadline = 1L;
992     s = awaitDone(s, false, true, deadline);
993     }
994 dl 1.151 if (s >= 0 || (s & ABNORMAL) != 0)
995 dl 1.134 reportExecutionException(s);
996 dl 1.129 return getRawResult();
997 jsr166 1.1 }
998    
999     /**
1000 dl 1.17 * Joins this task, without returning its result or throwing its
1001 jsr166 1.1 * exception. This method may be useful when processing
1002     * collections of tasks when some have been cancelled or otherwise
1003     * known to have aborted.
1004     */
1005     public final void quietlyJoin() {
1006 dl 1.155 int s;
1007     if ((s = status) >= 0)
1008     awaitDone(s, false, false, 0L);
1009 jsr166 1.1 }
1010    
1011     /**
1012     * Commences performing this task and awaits its completion if
1013 dl 1.17 * necessary, without returning its result or throwing its
1014 dl 1.22 * exception.
1015 jsr166 1.1 */
1016     public final void quietlyInvoke() {
1017 dl 1.155 int s;
1018     if ((s = doExec()) >= 0)
1019     awaitDone(s, true, false, 0L);
1020 dl 1.151 }
1021    
1022 dl 1.155 /**
1023     * Tries to join this task, returning true if it completed
1024     * (possibly exceptionally) before the given timeout and/or the
1025     * the current thread has been interrupted, else false.
1026     *
1027     * @param timeout the maximum time to wait
1028     * @param unit the time unit of the timeout argument
1029     * @return true if this task completed
1030     * @throws InterruptedException if the current thread was
1031     * interrupted while waiting
1032     */
1033     public final boolean quietlyJoin(long timeout, TimeUnit unit)
1034     throws InterruptedException {
1035     int s;
1036     long nanos = unit.toNanos(timeout), deadline;
1037     if (Thread.interrupted())
1038     s = ABNORMAL;
1039     else if ((s = status) >= 0 && nanos > 0L) {
1040     if ((deadline = nanos + System.nanoTime()) == 0L)
1041     deadline = 1L;
1042     s = awaitDone(s, false, true, deadline);
1043     }
1044     if (s == ABNORMAL)
1045     throw new InterruptedException();
1046     else
1047     return (s < 0);
1048     }
1049 dl 1.151
1050 dl 1.155 /**
1051     * Tries to join this task, returning true if it completed
1052     * (possibly exceptionally) before the given timeout.
1053     *
1054     * @param timeout the maximum time to wait
1055     * @param unit the time unit of the timeout argument
1056     * @return true if this task completed
1057     */
1058     public final boolean quietlyJoinUninterruptibly(long timeout,
1059     TimeUnit unit) {
1060     int s;
1061     long nanos = unit.toNanos(timeout), deadline;
1062     boolean interrupted = Thread.interrupted();
1063     if ((s = status) >= 0 && nanos > 0L) {
1064     if ((deadline = nanos + System.nanoTime()) == 0L)
1065     deadline = 1L;
1066     s = awaitDone(s, false, false, deadline);
1067     }
1068     if (interrupted || s == ABNORMAL)
1069     Thread.currentThread().interrupt();
1070     return (s < 0);
1071 jsr166 1.1 }
1072    
1073     /**
1074     * Possibly executes tasks until the pool hosting the current task
1075 jsr166 1.104 * {@linkplain ForkJoinPool#isQuiescent is quiescent}. This
1076     * method may be of use in designs in which many tasks are forked,
1077     * but none are explicitly joined, instead executing them until
1078     * all are processed.
1079 jsr166 1.1 */
1080     public static void helpQuiesce() {
1081 dl 1.155 ForkJoinPool.helpQuiescePool(null, Long.MAX_VALUE, false);
1082 jsr166 1.1 }
1083    
1084     /**
1085     * Resets the internal bookkeeping state of this task, allowing a
1086     * subsequent {@code fork}. This method allows repeated reuse of
1087     * this task, but only if reuse occurs when this task has either
1088     * never been forked, or has been forked, then completed and all
1089     * outstanding joins of this task have also completed. Effects
1090 jsr166 1.6 * under any other usage conditions are not guaranteed.
1091     * This method may be useful when executing
1092 jsr166 1.1 * pre-constructed trees of subtasks in loops.
1093 jsr166 1.34 *
1094 dl 1.33 * <p>Upon completion of this method, {@code isDone()} reports
1095     * {@code false}, and {@code getException()} reports {@code
1096     * null}. However, the value returned by {@code getRawResult} is
1097     * unaffected. To clear this value, you can invoke {@code
1098     * setRawResult(null)}.
1099 jsr166 1.1 */
1100     public void reinitialize() {
1101 dl 1.124 aux = null;
1102     status = 0;
1103 jsr166 1.1 }
1104    
1105     /**
1106 jsr166 1.103 * Returns the pool hosting the current thread, or {@code null}
1107     * if the current thread is executing outside of any ForkJoinPool.
1108     *
1109     * <p>This method returns {@code null} if and only if {@link
1110     * #inForkJoinPool} returns {@code false}.
1111 jsr166 1.1 *
1112 jsr166 1.97 * @return the pool, or {@code null} if none
1113 jsr166 1.1 */
1114     public static ForkJoinPool getPool() {
1115 dl 1.124 Thread t;
1116     return (((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) ?
1117     ((ForkJoinWorkerThread) t).pool : null);
1118 jsr166 1.1 }
1119    
1120     /**
1121 dl 1.42 * Returns {@code true} if the current thread is a {@link
1122     * ForkJoinWorkerThread} executing as a ForkJoinPool computation.
1123 jsr166 1.1 *
1124 dl 1.42 * @return {@code true} if the current thread is a {@link
1125     * ForkJoinWorkerThread} executing as a ForkJoinPool computation,
1126     * or {@code false} otherwise
1127 jsr166 1.1 */
1128     public static boolean inForkJoinPool() {
1129     return Thread.currentThread() instanceof ForkJoinWorkerThread;
1130     }
1131    
1132     /**
1133     * Tries to unschedule this task for execution. This method will
1134 dl 1.64 * typically (but is not guaranteed to) succeed if this task is
1135     * the most recently forked task by the current thread, and has
1136     * not commenced executing in another thread. This method may be
1137     * useful when arranging alternative local processing of tasks
1138     * that could have been, but were not, stolen.
1139 jsr166 1.1 *
1140 jsr166 1.4 * @return {@code true} if unforked
1141 jsr166 1.1 */
1142     public boolean tryUnfork() {
1143 dl 1.155 Thread t; ForkJoinPool.WorkQueue q; boolean owned;
1144     if (owned = (t = Thread.currentThread()) instanceof ForkJoinWorkerThread)
1145     q = ((ForkJoinWorkerThread)t).workQueue;
1146     else
1147     q = ForkJoinPool.commonQueue();
1148     return (q != null && q.tryUnpush(this, owned));
1149 jsr166 1.1 }
1150    
1151     /**
1152     * Returns an estimate of the number of tasks that have been
1153     * forked by the current worker thread but not yet executed. This
1154     * value may be useful for heuristic decisions about whether to
1155     * fork other tasks.
1156     *
1157     * @return the number of tasks
1158     */
1159     public static int getQueuedTaskCount() {
1160 dl 1.66 Thread t; ForkJoinPool.WorkQueue q;
1161     if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread)
1162     q = ((ForkJoinWorkerThread)t).workQueue;
1163     else
1164 dl 1.124 q = ForkJoinPool.commonQueue();
1165 dl 1.66 return (q == null) ? 0 : q.queueSize();
1166 jsr166 1.1 }
1167    
1168     /**
1169     * Returns an estimate of how many more locally queued tasks are
1170     * held by the current worker thread than there are other worker
1171 dl 1.64 * threads that might steal them, or zero if this thread is not
1172     * operating in a ForkJoinPool. This value may be useful for
1173 jsr166 1.1 * heuristic decisions about whether to fork other tasks. In many
1174     * usages of ForkJoinTasks, at steady state, each worker should
1175     * aim to maintain a small constant surplus (for example, 3) of
1176     * tasks, and to process computations locally if this threshold is
1177     * exceeded.
1178     *
1179     * @return the surplus number of tasks, which may be negative
1180     */
1181     public static int getSurplusQueuedTaskCount() {
1182 dl 1.66 return ForkJoinPool.getSurplusQueuedTaskCount();
1183 jsr166 1.1 }
1184    
1185     // Extension methods
1186    
1187     /**
1188 jsr166 1.4 * Returns the result that would be returned by {@link #join}, even
1189     * if this task completed abnormally, or {@code null} if this task
1190     * is not known to have been completed. This method is designed
1191     * to aid debugging, as well as to support extensions. Its use in
1192     * any other context is discouraged.
1193 jsr166 1.1 *
1194 jsr166 1.4 * @return the result, or {@code null} if not completed
1195 jsr166 1.1 */
1196     public abstract V getRawResult();
1197    
1198     /**
1199     * Forces the given value to be returned as a result. This method
1200     * is designed to support extensions, and should not in general be
1201     * called otherwise.
1202     *
1203     * @param value the value
1204     */
1205     protected abstract void setRawResult(V value);
1206    
1207     /**
1208 dl 1.62 * Immediately performs the base action of this task and returns
1209     * true if, upon return from this method, this task is guaranteed
1210 dl 1.122 * to have completed. This method may return false otherwise, to
1211     * indicate that this task is not necessarily complete (or is not
1212     * known to be complete), for example in asynchronous actions that
1213     * require explicit invocations of completion methods. This method
1214     * may also throw an (unchecked) exception to indicate abnormal
1215     * exit. This method is designed to support extensions, and should
1216     * not in general be called otherwise.
1217 jsr166 1.1 *
1218 dl 1.62 * @return {@code true} if this task is known to have completed normally
1219 jsr166 1.1 */
1220     protected abstract boolean exec();
1221    
1222     /**
1223 jsr166 1.5 * Returns, but does not unschedule or execute, a task queued by
1224     * the current thread but not yet executed, if one is immediately
1225 dl 1.66 * available. There is no guarantee that this task will actually
1226     * be polled or executed next. Conversely, this method may return
1227     * null even if a task exists but cannot be accessed without
1228     * contention with other threads. This method is designed
1229 jsr166 1.5 * primarily to support extensions, and is unlikely to be useful
1230 jsr166 1.6 * otherwise.
1231     *
1232 jsr166 1.4 * @return the next task, or {@code null} if none are available
1233 jsr166 1.1 */
1234     protected static ForkJoinTask<?> peekNextLocalTask() {
1235 dl 1.66 Thread t; ForkJoinPool.WorkQueue q;
1236     if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread)
1237     q = ((ForkJoinWorkerThread)t).workQueue;
1238     else
1239 dl 1.124 q = ForkJoinPool.commonQueue();
1240 dl 1.66 return (q == null) ? null : q.peek();
1241 jsr166 1.1 }
1242    
1243     /**
1244     * Unschedules and returns, without executing, the next task
1245 dl 1.64 * queued by the current thread but not yet executed, if the
1246     * current thread is operating in a ForkJoinPool. This method is
1247     * designed primarily to support extensions, and is unlikely to be
1248     * useful otherwise.
1249 jsr166 1.1 *
1250 jsr166 1.4 * @return the next task, or {@code null} if none are available
1251 jsr166 1.1 */
1252     protected static ForkJoinTask<?> pollNextLocalTask() {
1253 dl 1.64 Thread t;
1254 dl 1.124 return (((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) ?
1255     ((ForkJoinWorkerThread)t).workQueue.nextLocalTask() : null);
1256 jsr166 1.1 }
1257    
1258     /**
1259 dl 1.64 * If the current thread is operating in a ForkJoinPool,
1260     * unschedules and returns, without executing, the next task
1261 jsr166 1.1 * queued by the current thread but not yet executed, if one is
1262     * available, or if not available, a task that was forked by some
1263     * other thread, if available. Availability may be transient, so a
1264 dl 1.64 * {@code null} result does not necessarily imply quiescence of
1265     * the pool this task is operating in. This method is designed
1266 jsr166 1.1 * primarily to support extensions, and is unlikely to be useful
1267 jsr166 1.6 * otherwise.
1268     *
1269 jsr166 1.4 * @return a task, or {@code null} if none are available
1270 jsr166 1.1 */
1271     protected static ForkJoinTask<?> pollTask() {
1272 dl 1.124 Thread t; ForkJoinWorkerThread w;
1273     return (((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) ?
1274     (w = (ForkJoinWorkerThread)t).pool.nextTaskFor(w.workQueue) :
1275     null);
1276 dl 1.54 }
1277    
1278 dl 1.94 /**
1279     * If the current thread is operating in a ForkJoinPool,
1280     * unschedules and returns, without executing, a task externally
1281     * submitted to the pool, if one is available. Availability may be
1282     * transient, so a {@code null} result does not necessarily imply
1283     * quiescence of the pool. This method is designed primarily to
1284     * support extensions, and is unlikely to be useful otherwise.
1285     *
1286     * @return a task, or {@code null} if none are available
1287 jsr166 1.107 * @since 9
1288 dl 1.94 */
1289     protected static ForkJoinTask<?> pollSubmission() {
1290 dl 1.96 Thread t;
1291 dl 1.124 return (((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) ?
1292     ((ForkJoinWorkerThread)t).pool.pollSubmission() : null);
1293 dl 1.94 }
1294    
1295 dl 1.60 // tag operations
1296 dl 1.54
1297     /**
1298 dl 1.60 * Returns the tag for this task.
1299 dl 1.54 *
1300 dl 1.60 * @return the tag for this task
1301 dl 1.54 * @since 1.8
1302     */
1303 dl 1.60 public final short getForkJoinTaskTag() {
1304     return (short)status;
1305 dl 1.54 }
1306    
1307     /**
1308 jsr166 1.102 * Atomically sets the tag value for this task and returns the old value.
1309 dl 1.54 *
1310 jsr166 1.102 * @param newValue the new tag value
1311 dl 1.60 * @return the previous value of the tag
1312 dl 1.54 * @since 1.8
1313     */
1314 jsr166 1.102 public final short setForkJoinTaskTag(short newValue) {
1315 dl 1.54 for (int s;;) {
1316 dl 1.124 if (casStatus(s = status, (s & ~SMASK) | (newValue & SMASK)))
1317 dl 1.60 return (short)s;
1318 dl 1.54 }
1319     }
1320    
1321     /**
1322 dl 1.60 * Atomically conditionally sets the tag value for this task.
1323     * Among other applications, tags can be used as visit markers
1324 dl 1.61 * in tasks operating on graphs, as in methods that check: {@code
1325 dl 1.60 * if (task.compareAndSetForkJoinTaskTag((short)0, (short)1))}
1326     * before processing, otherwise exiting because the node has
1327     * already been visited.
1328 dl 1.54 *
1329 jsr166 1.102 * @param expect the expected tag value
1330     * @param update the new tag value
1331 jsr166 1.76 * @return {@code true} if successful; i.e., the current value was
1332 jsr166 1.102 * equal to {@code expect} and was changed to {@code update}.
1333 dl 1.54 * @since 1.8
1334     */
1335 jsr166 1.102 public final boolean compareAndSetForkJoinTaskTag(short expect, short update) {
1336 dl 1.54 for (int s;;) {
1337 jsr166 1.102 if ((short)(s = status) != expect)
1338 dl 1.54 return false;
1339 dl 1.124 if (casStatus(s, (s & ~SMASK) | (update & SMASK)))
1340 dl 1.54 return true;
1341     }
1342 jsr166 1.1 }
1343    
1344 jsr166 1.5 /**
1345 jsr166 1.95 * Adapter for Runnables. This implements RunnableFuture
1346 jsr166 1.5 * to be compliant with AbstractExecutorService constraints
1347     * when used in ForkJoinPool.
1348     */
1349     static final class AdaptedRunnable<T> extends ForkJoinTask<T>
1350     implements RunnableFuture<T> {
1351 jsr166 1.123 @SuppressWarnings("serial") // Conditionally serializable
1352 jsr166 1.5 final Runnable runnable;
1353 jsr166 1.123 @SuppressWarnings("serial") // Conditionally serializable
1354 jsr166 1.5 T result;
1355     AdaptedRunnable(Runnable runnable, T result) {
1356     if (runnable == null) throw new NullPointerException();
1357     this.runnable = runnable;
1358 dl 1.59 this.result = result; // OK to set this even before completion
1359 jsr166 1.5 }
1360 dl 1.59 public final T getRawResult() { return result; }
1361     public final void setRawResult(T v) { result = v; }
1362     public final boolean exec() { runnable.run(); return true; }
1363     public final void run() { invoke(); }
1364 jsr166 1.116 public String toString() {
1365     return super.toString() + "[Wrapped task = " + runnable + "]";
1366     }
1367 dl 1.59 private static final long serialVersionUID = 5232453952276885070L;
1368     }
1369    
1370     /**
1371 jsr166 1.99 * Adapter for Runnables without results.
1372 dl 1.59 */
1373     static final class AdaptedRunnableAction extends ForkJoinTask<Void>
1374     implements RunnableFuture<Void> {
1375 jsr166 1.123 @SuppressWarnings("serial") // Conditionally serializable
1376 dl 1.59 final Runnable runnable;
1377     AdaptedRunnableAction(Runnable runnable) {
1378     if (runnable == null) throw new NullPointerException();
1379     this.runnable = runnable;
1380 jsr166 1.5 }
1381 dl 1.59 public final Void getRawResult() { return null; }
1382     public final void setRawResult(Void v) { }
1383     public final boolean exec() { runnable.run(); return true; }
1384     public final void run() { invoke(); }
1385 jsr166 1.116 public String toString() {
1386     return super.toString() + "[Wrapped task = " + runnable + "]";
1387     }
1388 jsr166 1.5 private static final long serialVersionUID = 5232453952276885070L;
1389     }
1390    
1391     /**
1392 jsr166 1.99 * Adapter for Runnables in which failure forces worker exception.
1393 dl 1.73 */
1394     static final class RunnableExecuteAction extends ForkJoinTask<Void> {
1395 jsr166 1.123 @SuppressWarnings("serial") // Conditionally serializable
1396 dl 1.73 final Runnable runnable;
1397     RunnableExecuteAction(Runnable runnable) {
1398     if (runnable == null) throw new NullPointerException();
1399     this.runnable = runnable;
1400     }
1401     public final Void getRawResult() { return null; }
1402     public final void setRawResult(Void v) { }
1403     public final boolean exec() { runnable.run(); return true; }
1404 dl 1.145 int trySetException(Throwable ex) { // if a handler, invoke it
1405     int s; Thread t; java.lang.Thread.UncaughtExceptionHandler h;
1406 dl 1.126 if (isExceptionalStatus(s = trySetThrown(ex)) &&
1407 jsr166 1.146 (h = ((t = Thread.currentThread()).
1408     getUncaughtExceptionHandler())) != null) {
1409     try {
1410     h.uncaughtException(t, ex);
1411     } catch (Throwable ignore) {
1412     }
1413     }
1414 dl 1.124 return s;
1415 dl 1.73 }
1416     private static final long serialVersionUID = 5232453952276885070L;
1417     }
1418    
1419     /**
1420 jsr166 1.99 * Adapter for Callables.
1421 jsr166 1.5 */
1422     static final class AdaptedCallable<T> extends ForkJoinTask<T>
1423     implements RunnableFuture<T> {
1424 jsr166 1.123 @SuppressWarnings("serial") // Conditionally serializable
1425 jsr166 1.6 final Callable<? extends T> callable;
1426 jsr166 1.123 @SuppressWarnings("serial") // Conditionally serializable
1427 jsr166 1.5 T result;
1428 jsr166 1.6 AdaptedCallable(Callable<? extends T> callable) {
1429 jsr166 1.5 if (callable == null) throw new NullPointerException();
1430     this.callable = callable;
1431     }
1432 dl 1.59 public final T getRawResult() { return result; }
1433     public final void setRawResult(T v) { result = v; }
1434     public final boolean exec() {
1435 jsr166 1.5 try {
1436     result = callable.call();
1437     return true;
1438     } catch (RuntimeException rex) {
1439     throw rex;
1440     } catch (Exception ex) {
1441     throw new RuntimeException(ex);
1442     }
1443     }
1444 dl 1.59 public final void run() { invoke(); }
1445 jsr166 1.116 public String toString() {
1446     return super.toString() + "[Wrapped task = " + callable + "]";
1447     }
1448 jsr166 1.117 private static final long serialVersionUID = 2838392045355241008L;
1449 jsr166 1.5 }
1450 jsr166 1.2
1451 dl 1.129 static final class AdaptedInterruptibleCallable<T> extends ForkJoinTask<T>
1452     implements RunnableFuture<T> {
1453     @SuppressWarnings("serial") // Conditionally serializable
1454     final Callable<? extends T> callable;
1455 jsr166 1.153 transient volatile Thread runner;
1456 dl 1.129 @SuppressWarnings("serial") // Conditionally serializable
1457     T result;
1458     AdaptedInterruptibleCallable(Callable<? extends T> callable) {
1459     if (callable == null) throw new NullPointerException();
1460     this.callable = callable;
1461     }
1462     public final T getRawResult() { return result; }
1463     public final void setRawResult(T v) { result = v; }
1464     public final boolean exec() {
1465     Thread.interrupted();
1466     runner = Thread.currentThread();
1467     try {
1468 dl 1.133 if (!isDone()) // recheck
1469     result = callable.call();
1470 dl 1.129 return true;
1471     } catch (RuntimeException rex) {
1472     throw rex;
1473     } catch (Exception ex) {
1474     throw new RuntimeException(ex);
1475     } finally {
1476     runner = null;
1477     Thread.interrupted();
1478     }
1479     }
1480     public final void run() { invoke(); }
1481     public final boolean cancel(boolean mayInterruptIfRunning) {
1482     Thread t;
1483     boolean stat = super.cancel(false);
1484     if (mayInterruptIfRunning && (t = runner) != null) {
1485     try {
1486     t.interrupt();
1487     } catch (Throwable ignore) {
1488     }
1489     }
1490     return stat;
1491     }
1492     public String toString() {
1493     return super.toString() + "[Wrapped task = " + callable + "]";
1494     }
1495     private static final long serialVersionUID = 2838392045355241008L;
1496     }
1497    
1498 jsr166 1.2 /**
1499 jsr166 1.6 * Returns a new {@code ForkJoinTask} that performs the {@code run}
1500     * method of the given {@code Runnable} as its action, and returns
1501     * a null result upon {@link #join}.
1502 jsr166 1.2 *
1503     * @param runnable the runnable action
1504     * @return the task
1505     */
1506 jsr166 1.6 public static ForkJoinTask<?> adapt(Runnable runnable) {
1507 dl 1.59 return new AdaptedRunnableAction(runnable);
1508 jsr166 1.2 }
1509    
1510     /**
1511 jsr166 1.6 * Returns a new {@code ForkJoinTask} that performs the {@code run}
1512     * method of the given {@code Runnable} as its action, and returns
1513     * the given result upon {@link #join}.
1514 jsr166 1.2 *
1515     * @param runnable the runnable action
1516     * @param result the result upon completion
1517 jsr166 1.82 * @param <T> the type of the result
1518 jsr166 1.2 * @return the task
1519     */
1520     public static <T> ForkJoinTask<T> adapt(Runnable runnable, T result) {
1521 jsr166 1.5 return new AdaptedRunnable<T>(runnable, result);
1522 jsr166 1.2 }
1523    
1524     /**
1525 jsr166 1.6 * Returns a new {@code ForkJoinTask} that performs the {@code call}
1526     * method of the given {@code Callable} as its action, and returns
1527     * its result upon {@link #join}, translating any checked exceptions
1528     * encountered into {@code RuntimeException}.
1529 jsr166 1.2 *
1530     * @param callable the callable action
1531 jsr166 1.82 * @param <T> the type of the callable's result
1532 jsr166 1.2 * @return the task
1533     */
1534 jsr166 1.6 public static <T> ForkJoinTask<T> adapt(Callable<? extends T> callable) {
1535 jsr166 1.5 return new AdaptedCallable<T>(callable);
1536 jsr166 1.2 }
1537    
1538 dl 1.129 /**
1539 jsr166 1.138 * Returns a new {@code ForkJoinTask} that performs the {@code call}
1540     * method of the given {@code Callable} as its action, and returns
1541     * its result upon {@link #join}, translating any checked exceptions
1542     * encountered into {@code RuntimeException}. Additionally,
1543     * invocations of {@code cancel} with {@code mayInterruptIfRunning
1544     * true} will attempt to interrupt the thread performing the task.
1545 dl 1.129 *
1546     * @param callable the callable action
1547     * @param <T> the type of the callable's result
1548     * @return the task
1549     *
1550 jsr166 1.147 * @since 17
1551 dl 1.129 */
1552 dl 1.155 public static <T> ForkJoinTask<T> adaptInterruptible(Callable<? extends T> callable) {
1553     // https://bugs.openjdk.java.net/browse/JDK-8246587
1554 dl 1.129 return new AdaptedInterruptibleCallable<T>(callable);
1555     }
1556    
1557 jsr166 1.1 // Serialization support
1558    
1559     private static final long serialVersionUID = -7721805057305804111L;
1560    
1561     /**
1562 jsr166 1.53 * Saves this task to a stream (that is, serializes it).
1563 jsr166 1.1 *
1564 jsr166 1.83 * @param s the stream
1565 jsr166 1.84 * @throws java.io.IOException if an I/O error occurs
1566 jsr166 1.1 * @serialData the current run status and the exception thrown
1567 jsr166 1.4 * during execution, or {@code null} if none
1568 jsr166 1.1 */
1569     private void writeObject(java.io.ObjectOutputStream s)
1570     throws java.io.IOException {
1571 dl 1.124 Aux a;
1572 jsr166 1.1 s.defaultWriteObject();
1573 dl 1.124 s.writeObject((a = aux) == null ? null : a.ex);
1574 jsr166 1.1 }
1575    
1576     /**
1577 jsr166 1.53 * Reconstitutes this task from a stream (that is, deserializes it).
1578 jsr166 1.83 * @param s the stream
1579 jsr166 1.84 * @throws ClassNotFoundException if the class of a serialized object
1580     * could not be found
1581     * @throws java.io.IOException if an I/O error occurs
1582 jsr166 1.1 */
1583     private void readObject(java.io.ObjectInputStream s)
1584     throws java.io.IOException, ClassNotFoundException {
1585     s.defaultReadObject();
1586     Object ex = s.readObject();
1587     if (ex != null)
1588 dl 1.124 trySetThrown((Throwable)ex);
1589 jsr166 1.1 }
1590    
1591 dl 1.45 static {
1592 dl 1.154 U = Unsafe.getUnsafe();
1593     STATUS = U.objectFieldOffset(ForkJoinTask.class, "status");
1594     AUX = U.objectFieldOffset(ForkJoinTask.class, "aux");
1595 dl 1.155 Class<?> dep1 = LockSupport.class; // ensure loaded
1596     Class<?> dep2 = Aux.class;
1597 jsr166 1.1 }
1598 dl 1.45
1599 jsr166 1.1 }