ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinTask.java
Revision: 1.156
Committed: Fri Mar 25 12:29:55 2022 UTC (2 years, 2 months ago) by dl
Branch: MAIN
Changes since 1.155: +4 -1 lines
Log Message:
Compatibility; @since tags

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 dl 1.156 U.storeFence(); // ensure safely publishable
600 dl 1.155 if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) {
601     p = (wt = (ForkJoinWorkerThread)t).pool;
602     q = wt.workQueue;
603     }
604 dl 1.64 else
605 dl 1.155 q = (p = ForkJoinPool.common).submissionQueue(false);
606     q.push(this, p, true);
607 jsr166 1.2 return this;
608 jsr166 1.1 }
609    
610     /**
611 jsr166 1.115 * Returns the result of the computation when it
612     * {@linkplain #isDone is done}.
613     * This method differs from {@link #get()} in that abnormal
614     * completion results in {@code RuntimeException} or {@code Error},
615     * not {@code ExecutionException}, and that interrupts of the
616     * calling thread do <em>not</em> cause the method to abruptly
617     * return by throwing {@code InterruptedException}.
618 jsr166 1.1 *
619     * @return the computed result
620     */
621     public final V join() {
622 dl 1.59 int s;
623 dl 1.124 if ((s = status) >= 0)
624 dl 1.155 s = awaitDone(s, false, false, 0L);
625 dl 1.124 if ((s & ABNORMAL) != 0)
626 dl 1.59 reportException(s);
627     return getRawResult();
628 jsr166 1.1 }
629    
630     /**
631     * Commences performing this task, awaits its completion if
632 jsr166 1.21 * necessary, and returns its result, or throws an (unchecked)
633 dl 1.20 * {@code RuntimeException} or {@code Error} if the underlying
634     * computation did so.
635 jsr166 1.1 *
636     * @return the computed result
637     */
638     public final V invoke() {
639 dl 1.59 int s;
640 dl 1.124 if ((s = doExec()) >= 0)
641 dl 1.155 s = awaitDone(s, true, false, 0L);
642 dl 1.124 if ((s & ABNORMAL) != 0)
643 dl 1.59 reportException(s);
644     return getRawResult();
645 jsr166 1.1 }
646    
647     /**
648 jsr166 1.8 * Forks the given tasks, returning when {@code isDone} holds for
649     * each task or an (unchecked) exception is encountered, in which
650 dl 1.20 * case the exception is rethrown. If more than one task
651     * encounters an exception, then this method throws any one of
652     * these exceptions. If any task encounters an exception, the
653     * other may be cancelled. However, the execution status of
654     * individual tasks is not guaranteed upon exceptional return. The
655     * status of each task may be obtained using {@link
656     * #getException()} and related methods to check if they have been
657     * cancelled, completed normally or exceptionally, or left
658     * unprocessed.
659 jsr166 1.6 *
660     * @param t1 the first task
661     * @param t2 the second task
662     * @throws NullPointerException if any task is null
663 jsr166 1.1 */
664 jsr166 1.6 public static void invokeAll(ForkJoinTask<?> t1, ForkJoinTask<?> t2) {
665 dl 1.59 int s1, s2;
666 dl 1.124 if (t1 == null || t2 == null)
667     throw new NullPointerException();
668 jsr166 1.1 t2.fork();
669 dl 1.124 if ((s1 = t1.doExec()) >= 0)
670 dl 1.155 s1 = t1.awaitDone(s1, true, false, 0L);
671 dl 1.128 if ((s1 & ABNORMAL) != 0) {
672     cancelIgnoringExceptions(t2);
673 dl 1.59 t1.reportException(s1);
674 dl 1.128 }
675 dl 1.155 else {
676     if ((s2 = t2.status) >= 0)
677     s2 = t2.awaitDone(s2, false, false, 0L);
678     if ((s2 & ABNORMAL) != 0)
679     t2.reportException(s2);
680     }
681 jsr166 1.1 }
682    
683     /**
684 jsr166 1.6 * Forks the given tasks, returning when {@code isDone} holds for
685 jsr166 1.8 * each task or an (unchecked) exception is encountered, in which
686 dl 1.20 * case the exception is rethrown. If more than one task
687     * encounters an exception, then this method throws any one of
688     * these exceptions. If any task encounters an exception, others
689     * may be cancelled. However, the execution status of individual
690     * tasks is not guaranteed upon exceptional return. The status of
691     * each task may be obtained using {@link #getException()} and
692     * related methods to check if they have been cancelled, completed
693     * normally or exceptionally, or left unprocessed.
694 jsr166 1.6 *
695     * @param tasks the tasks
696 jsr166 1.8 * @throws NullPointerException if any task is null
697 jsr166 1.1 */
698     public static void invokeAll(ForkJoinTask<?>... tasks) {
699     Throwable ex = null;
700     int last = tasks.length - 1;
701 jsr166 1.144 for (int i = last; i >= 0; --i) {
702 dl 1.124 ForkJoinTask<?> t;
703     if ((t = tasks[i]) == null) {
704     ex = new NullPointerException();
705     break;
706 jsr166 1.1 }
707 dl 1.124 if (i == 0) {
708 jsr166 1.144 int s;
709 dl 1.124 if ((s = t.doExec()) >= 0)
710 dl 1.155 s = t.awaitDone(s, true, false, 0L);
711 dl 1.124 if ((s & ABNORMAL) != 0)
712 dl 1.128 ex = t.getException(s);
713 dl 1.124 break;
714 jsr166 1.1 }
715 dl 1.124 t.fork();
716 jsr166 1.1 }
717 dl 1.124 if (ex == null) {
718 jsr166 1.144 for (int i = 1; i <= last; ++i) {
719 dl 1.124 ForkJoinTask<?> t;
720     if ((t = tasks[i]) != null) {
721 jsr166 1.144 int s;
722 dl 1.124 if ((s = t.status) >= 0)
723 dl 1.155 s = t.awaitDone(s, false, false, 0L);
724 dl 1.128 if ((s & ABNORMAL) != 0 && (ex = t.getException(s)) != null)
725 dl 1.124 break;
726     }
727     }
728     }
729 dl 1.128 if (ex != null) {
730 jsr166 1.143 for (int i = 1; i <= last; ++i)
731 dl 1.128 cancelIgnoringExceptions(tasks[i]);
732 dl 1.65 rethrow(ex);
733 dl 1.128 }
734 jsr166 1.1 }
735    
736     /**
737 jsr166 1.7 * Forks all tasks in the specified collection, returning when
738 jsr166 1.8 * {@code isDone} holds for each task or an (unchecked) exception
739 dl 1.20 * is encountered, in which case the exception is rethrown. If
740     * more than one task encounters an exception, then this method
741     * throws any one of these exceptions. If any task encounters an
742     * exception, others may be cancelled. However, the execution
743     * status of individual tasks is not guaranteed upon exceptional
744     * return. The status of each task may be obtained using {@link
745     * #getException()} and related methods to check if they have been
746     * cancelled, completed normally or exceptionally, or left
747     * unprocessed.
748 jsr166 1.6 *
749 jsr166 1.1 * @param tasks the collection of tasks
750 jsr166 1.82 * @param <T> the type of the values returned from the tasks
751 jsr166 1.2 * @return the tasks argument, to simplify usage
752 jsr166 1.1 * @throws NullPointerException if tasks or any element are null
753     */
754 jsr166 1.2 public static <T extends ForkJoinTask<?>> Collection<T> invokeAll(Collection<T> tasks) {
755 jsr166 1.7 if (!(tasks instanceof RandomAccess) || !(tasks instanceof List<?>)) {
756 jsr166 1.121 invokeAll(tasks.toArray(new ForkJoinTask<?>[0]));
757 jsr166 1.2 return tasks;
758 jsr166 1.1 }
759     @SuppressWarnings("unchecked")
760     List<? extends ForkJoinTask<?>> ts =
761     (List<? extends ForkJoinTask<?>>) tasks;
762     Throwable ex = null;
763 dl 1.124 int last = ts.size() - 1; // nearly same as array version
764 jsr166 1.144 for (int i = last; i >= 0; --i) {
765 dl 1.124 ForkJoinTask<?> t;
766     if ((t = ts.get(i)) == null) {
767     ex = new NullPointerException();
768     break;
769 jsr166 1.1 }
770 dl 1.124 if (i == 0) {
771 jsr166 1.144 int s;
772 dl 1.124 if ((s = t.doExec()) >= 0)
773 dl 1.155 s = t.awaitDone(s, true, false, 0L);
774 dl 1.124 if ((s & ABNORMAL) != 0)
775 dl 1.128 ex = t.getException(s);
776 dl 1.124 break;
777     }
778     t.fork();
779     }
780     if (ex == null) {
781 jsr166 1.144 for (int i = 1; i <= last; ++i) {
782 dl 1.124 ForkJoinTask<?> t;
783     if ((t = ts.get(i)) != null) {
784 jsr166 1.144 int s;
785 dl 1.124 if ((s = t.status) >= 0)
786 dl 1.155 s = t.awaitDone(s, false, false, 0L);
787 dl 1.128 if ((s & ABNORMAL) != 0 && (ex = t.getException(s)) != null)
788 dl 1.124 break;
789     }
790 jsr166 1.1 }
791     }
792 dl 1.128 if (ex != null) {
793 jsr166 1.142 for (int i = 1; i <= last; ++i)
794 dl 1.128 cancelIgnoringExceptions(ts.get(i));
795 dl 1.65 rethrow(ex);
796 dl 1.128 }
797 jsr166 1.2 return tasks;
798 jsr166 1.1 }
799 jsr166 1.135
800 jsr166 1.1 /**
801 jsr166 1.7 * Attempts to cancel execution of this task. This attempt will
802 jsr166 1.36 * fail if the task has already completed or could not be
803     * cancelled for some other reason. If successful, and this task
804     * has not started when {@code cancel} is called, execution of
805 dl 1.38 * this task is suppressed. After this method returns
806     * successfully, unless there is an intervening call to {@link
807     * #reinitialize}, subsequent calls to {@link #isCancelled},
808     * {@link #isDone}, and {@code cancel} will return {@code true}
809     * and calls to {@link #join} and related methods will result in
810     * {@code CancellationException}.
811 jsr166 1.1 *
812     * <p>This method may be overridden in subclasses, but if so, must
813 dl 1.38 * still ensure that these properties hold. In particular, the
814     * {@code cancel} method itself must not throw exceptions.
815 jsr166 1.1 *
816 jsr166 1.6 * <p>This method is designed to be invoked by <em>other</em>
817 jsr166 1.1 * tasks. To terminate the current task, you can just return or
818     * throw an unchecked exception from its computation method, or
819 jsr166 1.74 * invoke {@link #completeExceptionally(Throwable)}.
820 jsr166 1.1 *
821 dl 1.38 * @param mayInterruptIfRunning this value has no effect in the
822     * default implementation because interrupts are not used to
823     * control cancellation.
824 jsr166 1.1 *
825 jsr166 1.4 * @return {@code true} if this task is now cancelled
826 jsr166 1.1 */
827     public boolean cancel(boolean mayInterruptIfRunning) {
828 dl 1.124 return (trySetCancelled() & (ABNORMAL | THROWN)) == ABNORMAL;
829 jsr166 1.1 }
830    
831 jsr166 1.8 public final boolean isDone() {
832     return status < 0;
833     }
834    
835     public final boolean isCancelled() {
836 dl 1.118 return (status & (ABNORMAL | THROWN)) == ABNORMAL;
837 jsr166 1.8 }
838    
839     /**
840 jsr166 1.4 * Returns {@code true} if this task threw an exception or was cancelled.
841 jsr166 1.1 *
842 jsr166 1.4 * @return {@code true} if this task threw an exception or was cancelled
843 jsr166 1.1 */
844     public final boolean isCompletedAbnormally() {
845 dl 1.118 return (status & ABNORMAL) != 0;
846 jsr166 1.1 }
847    
848     /**
849 jsr166 1.8 * Returns {@code true} if this task completed without throwing an
850     * exception and was not cancelled.
851     *
852     * @return {@code true} if this task completed without throwing an
853     * exception and was not cancelled
854     */
855     public final boolean isCompletedNormally() {
856 dl 1.118 return (status & (DONE | ABNORMAL)) == DONE;
857 jsr166 1.8 }
858    
859 dl 1.155 @Override
860     public State state() {
861     int s = status;
862     return (s >= 0) ? State.RUNNING :
863     ((s & (DONE | ABNORMAL)) == DONE) ? State.SUCCESS:
864     ((s & (ABNORMAL | THROWN)) == (ABNORMAL | THROWN)) ? State.FAILED :
865     State.CANCELLED;
866     }
867    
868     @Override
869     public V resultNow() {
870     if (!isCompletedNormally())
871     throw new IllegalStateException();
872     return getRawResult();
873     }
874    
875     @Override
876     public Throwable exceptionNow() {
877     if ((status & (ABNORMAL | THROWN)) != (ABNORMAL | THROWN))
878     throw new IllegalStateException();
879     return getThrowableException();
880     }
881    
882 jsr166 1.8 /**
883 jsr166 1.1 * Returns the exception thrown by the base computation, or a
884 jsr166 1.6 * {@code CancellationException} if cancelled, or {@code null} if
885     * none or if the method has not yet completed.
886 jsr166 1.1 *
887 jsr166 1.4 * @return the exception, or {@code null} if none
888 jsr166 1.1 */
889     public final Throwable getException() {
890 dl 1.128 return getException(status);
891 jsr166 1.1 }
892    
893     /**
894     * Completes this task abnormally, and if not already aborted or
895     * cancelled, causes it to throw the given exception upon
896     * {@code join} and related operations. This method may be used
897     * to induce exceptions in asynchronous tasks, or to force
898     * completion of tasks that would not otherwise complete. Its use
899 jsr166 1.6 * in other situations is discouraged. This method is
900 jsr166 1.1 * overridable, but overridden versions must invoke {@code super}
901     * implementation to maintain guarantees.
902     *
903 jsr166 1.11 * @param ex the exception to throw. If this exception is not a
904     * {@code RuntimeException} or {@code Error}, the actual exception
905     * thrown will be a {@code RuntimeException} with cause {@code ex}.
906 jsr166 1.1 */
907     public void completeExceptionally(Throwable ex) {
908 dl 1.124 trySetException((ex instanceof RuntimeException) ||
909     (ex instanceof Error) ? ex :
910     new RuntimeException(ex));
911 jsr166 1.1 }
912    
913     /**
914     * Completes this task, and if not already aborted or cancelled,
915 dl 1.22 * returning the given value as the result of subsequent
916     * invocations of {@code join} and related operations. This method
917     * may be used to provide results for asynchronous tasks, or to
918     * provide alternative handling for tasks that would not otherwise
919     * complete normally. Its use in other situations is
920     * discouraged. This method is overridable, but overridden
921     * versions must invoke {@code super} implementation to maintain
922     * guarantees.
923 jsr166 1.1 *
924     * @param value the result value for this task
925     */
926     public void complete(V value) {
927     try {
928     setRawResult(value);
929     } catch (Throwable rex) {
930 dl 1.124 trySetException(rex);
931 jsr166 1.1 return;
932     }
933 dl 1.118 setDone();
934 jsr166 1.1 }
935    
936 jsr166 1.25 /**
937 dl 1.62 * Completes this task normally without setting a value. The most
938     * recent value established by {@link #setRawResult} (or {@code
939     * null} by default) will be returned as the result of subsequent
940     * invocations of {@code join} and related operations.
941     *
942     * @since 1.8
943 dl 1.60 */
944     public final void quietlyComplete() {
945 dl 1.118 setDone();
946 dl 1.60 }
947    
948     /**
949 dl 1.29 * Waits if necessary for the computation to complete, and then
950     * retrieves its result.
951     *
952     * @return the computed result
953     * @throws CancellationException if the computation was cancelled
954     * @throws ExecutionException if the computation threw an
955     * exception
956     * @throws InterruptedException if the current thread is not a
957     * member of a ForkJoinPool and was interrupted while waiting
958 jsr166 1.25 */
959 jsr166 1.1 public final V get() throws InterruptedException, ExecutionException {
960 dl 1.155 int s;
961     if (Thread.interrupted())
962     s = ABNORMAL;
963     else if ((s = status) >= 0)
964     s = awaitDone(s, false, true, 0L);
965 dl 1.151 if ((s & ABNORMAL) != 0)
966 dl 1.134 reportExecutionException(s);
967 dl 1.129 return getRawResult();
968 jsr166 1.1 }
969 dl 1.14
970 jsr166 1.25 /**
971 dl 1.29 * Waits if necessary for at most the given time for the computation
972     * to complete, and then retrieves its result, if available.
973     *
974     * @param timeout the maximum time to wait
975     * @param unit the time unit of the timeout argument
976     * @return the computed result
977     * @throws CancellationException if the computation was cancelled
978     * @throws ExecutionException if the computation threw an
979     * exception
980     * @throws InterruptedException if the current thread is not a
981     * member of a ForkJoinPool and was interrupted while waiting
982     * @throws TimeoutException if the wait timed out
983 jsr166 1.25 */
984 jsr166 1.1 public final V get(long timeout, TimeUnit unit)
985     throws InterruptedException, ExecutionException, TimeoutException {
986 dl 1.155 long nanos = unit.toNanos(timeout), deadline;
987     int s;
988     if (Thread.interrupted())
989     s = ABNORMAL;
990     else if ((s = status) >= 0 && nanos > 0L) {
991     if ((deadline = nanos + System.nanoTime()) == 0L)
992     deadline = 1L;
993     s = awaitDone(s, false, true, deadline);
994     }
995 dl 1.151 if (s >= 0 || (s & ABNORMAL) != 0)
996 dl 1.134 reportExecutionException(s);
997 dl 1.129 return getRawResult();
998 jsr166 1.1 }
999    
1000     /**
1001 dl 1.17 * Joins this task, without returning its result or throwing its
1002 jsr166 1.1 * exception. This method may be useful when processing
1003     * collections of tasks when some have been cancelled or otherwise
1004     * known to have aborted.
1005     */
1006     public final void quietlyJoin() {
1007 dl 1.155 int s;
1008     if ((s = status) >= 0)
1009     awaitDone(s, false, false, 0L);
1010 jsr166 1.1 }
1011    
1012     /**
1013     * Commences performing this task and awaits its completion if
1014 dl 1.17 * necessary, without returning its result or throwing its
1015 dl 1.22 * exception.
1016 jsr166 1.1 */
1017     public final void quietlyInvoke() {
1018 dl 1.155 int s;
1019     if ((s = doExec()) >= 0)
1020     awaitDone(s, true, false, 0L);
1021 dl 1.151 }
1022    
1023 dl 1.155 /**
1024     * Tries to join this task, returning true if it completed
1025     * (possibly exceptionally) before the given timeout and/or the
1026     * the current thread has been interrupted, else false.
1027     *
1028     * @param timeout the maximum time to wait
1029     * @param unit the time unit of the timeout argument
1030     * @return true if this task completed
1031     * @throws InterruptedException if the current thread was
1032     * interrupted while waiting
1033 dl 1.156 * @since 19
1034 dl 1.155 */
1035     public final boolean quietlyJoin(long timeout, TimeUnit unit)
1036     throws InterruptedException {
1037     int s;
1038     long nanos = unit.toNanos(timeout), deadline;
1039     if (Thread.interrupted())
1040     s = ABNORMAL;
1041     else if ((s = status) >= 0 && nanos > 0L) {
1042     if ((deadline = nanos + System.nanoTime()) == 0L)
1043     deadline = 1L;
1044     s = awaitDone(s, false, true, deadline);
1045     }
1046     if (s == ABNORMAL)
1047     throw new InterruptedException();
1048     else
1049     return (s < 0);
1050     }
1051 dl 1.151
1052 dl 1.155 /**
1053     * Tries to join this task, returning true if it completed
1054     * (possibly exceptionally) before the given timeout.
1055     *
1056     * @param timeout the maximum time to wait
1057     * @param unit the time unit of the timeout argument
1058     * @return true if this task completed
1059 dl 1.156 * @since 19
1060 dl 1.155 */
1061     public final boolean quietlyJoinUninterruptibly(long timeout,
1062     TimeUnit unit) {
1063     int s;
1064     long nanos = unit.toNanos(timeout), deadline;
1065     boolean interrupted = Thread.interrupted();
1066     if ((s = status) >= 0 && nanos > 0L) {
1067     if ((deadline = nanos + System.nanoTime()) == 0L)
1068     deadline = 1L;
1069     s = awaitDone(s, false, false, deadline);
1070     }
1071     if (interrupted || s == ABNORMAL)
1072     Thread.currentThread().interrupt();
1073     return (s < 0);
1074 jsr166 1.1 }
1075    
1076     /**
1077     * Possibly executes tasks until the pool hosting the current task
1078 jsr166 1.104 * {@linkplain ForkJoinPool#isQuiescent is quiescent}. This
1079     * method may be of use in designs in which many tasks are forked,
1080     * but none are explicitly joined, instead executing them until
1081     * all are processed.
1082 jsr166 1.1 */
1083     public static void helpQuiesce() {
1084 dl 1.155 ForkJoinPool.helpQuiescePool(null, Long.MAX_VALUE, false);
1085 jsr166 1.1 }
1086    
1087     /**
1088     * Resets the internal bookkeeping state of this task, allowing a
1089     * subsequent {@code fork}. This method allows repeated reuse of
1090     * this task, but only if reuse occurs when this task has either
1091     * never been forked, or has been forked, then completed and all
1092     * outstanding joins of this task have also completed. Effects
1093 jsr166 1.6 * under any other usage conditions are not guaranteed.
1094     * This method may be useful when executing
1095 jsr166 1.1 * pre-constructed trees of subtasks in loops.
1096 jsr166 1.34 *
1097 dl 1.33 * <p>Upon completion of this method, {@code isDone()} reports
1098     * {@code false}, and {@code getException()} reports {@code
1099     * null}. However, the value returned by {@code getRawResult} is
1100     * unaffected. To clear this value, you can invoke {@code
1101     * setRawResult(null)}.
1102 jsr166 1.1 */
1103     public void reinitialize() {
1104 dl 1.124 aux = null;
1105     status = 0;
1106 jsr166 1.1 }
1107    
1108     /**
1109 jsr166 1.103 * Returns the pool hosting the current thread, or {@code null}
1110     * if the current thread is executing outside of any ForkJoinPool.
1111     *
1112     * <p>This method returns {@code null} if and only if {@link
1113     * #inForkJoinPool} returns {@code false}.
1114 jsr166 1.1 *
1115 jsr166 1.97 * @return the pool, or {@code null} if none
1116 jsr166 1.1 */
1117     public static ForkJoinPool getPool() {
1118 dl 1.124 Thread t;
1119     return (((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) ?
1120     ((ForkJoinWorkerThread) t).pool : null);
1121 jsr166 1.1 }
1122    
1123     /**
1124 dl 1.42 * Returns {@code true} if the current thread is a {@link
1125     * ForkJoinWorkerThread} executing as a ForkJoinPool computation.
1126 jsr166 1.1 *
1127 dl 1.42 * @return {@code true} if the current thread is a {@link
1128     * ForkJoinWorkerThread} executing as a ForkJoinPool computation,
1129     * or {@code false} otherwise
1130 jsr166 1.1 */
1131     public static boolean inForkJoinPool() {
1132     return Thread.currentThread() instanceof ForkJoinWorkerThread;
1133     }
1134    
1135     /**
1136     * Tries to unschedule this task for execution. This method will
1137 dl 1.64 * typically (but is not guaranteed to) succeed if this task is
1138     * the most recently forked task by the current thread, and has
1139     * not commenced executing in another thread. This method may be
1140     * useful when arranging alternative local processing of tasks
1141     * that could have been, but were not, stolen.
1142 jsr166 1.1 *
1143 jsr166 1.4 * @return {@code true} if unforked
1144 jsr166 1.1 */
1145     public boolean tryUnfork() {
1146 dl 1.155 Thread t; ForkJoinPool.WorkQueue q; boolean owned;
1147     if (owned = (t = Thread.currentThread()) instanceof ForkJoinWorkerThread)
1148     q = ((ForkJoinWorkerThread)t).workQueue;
1149     else
1150     q = ForkJoinPool.commonQueue();
1151     return (q != null && q.tryUnpush(this, owned));
1152 jsr166 1.1 }
1153    
1154     /**
1155     * Returns an estimate of the number of tasks that have been
1156     * forked by the current worker thread but not yet executed. This
1157     * value may be useful for heuristic decisions about whether to
1158     * fork other tasks.
1159     *
1160     * @return the number of tasks
1161     */
1162     public static int getQueuedTaskCount() {
1163 dl 1.66 Thread t; ForkJoinPool.WorkQueue q;
1164     if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread)
1165     q = ((ForkJoinWorkerThread)t).workQueue;
1166     else
1167 dl 1.124 q = ForkJoinPool.commonQueue();
1168 dl 1.66 return (q == null) ? 0 : q.queueSize();
1169 jsr166 1.1 }
1170    
1171     /**
1172     * Returns an estimate of how many more locally queued tasks are
1173     * held by the current worker thread than there are other worker
1174 dl 1.64 * threads that might steal them, or zero if this thread is not
1175     * operating in a ForkJoinPool. This value may be useful for
1176 jsr166 1.1 * heuristic decisions about whether to fork other tasks. In many
1177     * usages of ForkJoinTasks, at steady state, each worker should
1178     * aim to maintain a small constant surplus (for example, 3) of
1179     * tasks, and to process computations locally if this threshold is
1180     * exceeded.
1181     *
1182     * @return the surplus number of tasks, which may be negative
1183     */
1184     public static int getSurplusQueuedTaskCount() {
1185 dl 1.66 return ForkJoinPool.getSurplusQueuedTaskCount();
1186 jsr166 1.1 }
1187    
1188     // Extension methods
1189    
1190     /**
1191 jsr166 1.4 * Returns the result that would be returned by {@link #join}, even
1192     * if this task completed abnormally, or {@code null} if this task
1193     * is not known to have been completed. This method is designed
1194     * to aid debugging, as well as to support extensions. Its use in
1195     * any other context is discouraged.
1196 jsr166 1.1 *
1197 jsr166 1.4 * @return the result, or {@code null} if not completed
1198 jsr166 1.1 */
1199     public abstract V getRawResult();
1200    
1201     /**
1202     * Forces the given value to be returned as a result. This method
1203     * is designed to support extensions, and should not in general be
1204     * called otherwise.
1205     *
1206     * @param value the value
1207     */
1208     protected abstract void setRawResult(V value);
1209    
1210     /**
1211 dl 1.62 * Immediately performs the base action of this task and returns
1212     * true if, upon return from this method, this task is guaranteed
1213 dl 1.122 * to have completed. This method may return false otherwise, to
1214     * indicate that this task is not necessarily complete (or is not
1215     * known to be complete), for example in asynchronous actions that
1216     * require explicit invocations of completion methods. This method
1217     * may also throw an (unchecked) exception to indicate abnormal
1218     * exit. This method is designed to support extensions, and should
1219     * not in general be called otherwise.
1220 jsr166 1.1 *
1221 dl 1.62 * @return {@code true} if this task is known to have completed normally
1222 jsr166 1.1 */
1223     protected abstract boolean exec();
1224    
1225     /**
1226 jsr166 1.5 * Returns, but does not unschedule or execute, a task queued by
1227     * the current thread but not yet executed, if one is immediately
1228 dl 1.66 * available. There is no guarantee that this task will actually
1229     * be polled or executed next. Conversely, this method may return
1230     * null even if a task exists but cannot be accessed without
1231     * contention with other threads. This method is designed
1232 jsr166 1.5 * primarily to support extensions, and is unlikely to be useful
1233 jsr166 1.6 * otherwise.
1234     *
1235 jsr166 1.4 * @return the next task, or {@code null} if none are available
1236 jsr166 1.1 */
1237     protected static ForkJoinTask<?> peekNextLocalTask() {
1238 dl 1.66 Thread t; ForkJoinPool.WorkQueue q;
1239     if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread)
1240     q = ((ForkJoinWorkerThread)t).workQueue;
1241     else
1242 dl 1.124 q = ForkJoinPool.commonQueue();
1243 dl 1.66 return (q == null) ? null : q.peek();
1244 jsr166 1.1 }
1245    
1246     /**
1247     * Unschedules and returns, without executing, the next task
1248 dl 1.64 * queued by the current thread but not yet executed, if the
1249     * current thread is operating in a ForkJoinPool. This method is
1250     * designed primarily to support extensions, and is unlikely to be
1251     * useful otherwise.
1252 jsr166 1.1 *
1253 jsr166 1.4 * @return the next task, or {@code null} if none are available
1254 jsr166 1.1 */
1255     protected static ForkJoinTask<?> pollNextLocalTask() {
1256 dl 1.64 Thread t;
1257 dl 1.124 return (((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) ?
1258     ((ForkJoinWorkerThread)t).workQueue.nextLocalTask() : null);
1259 jsr166 1.1 }
1260    
1261     /**
1262 dl 1.64 * If the current thread is operating in a ForkJoinPool,
1263     * unschedules and returns, without executing, the next task
1264 jsr166 1.1 * queued by the current thread but not yet executed, if one is
1265     * available, or if not available, a task that was forked by some
1266     * other thread, if available. Availability may be transient, so a
1267 dl 1.64 * {@code null} result does not necessarily imply quiescence of
1268     * the pool this task is operating in. This method is designed
1269 jsr166 1.1 * primarily to support extensions, and is unlikely to be useful
1270 jsr166 1.6 * otherwise.
1271     *
1272 jsr166 1.4 * @return a task, or {@code null} if none are available
1273 jsr166 1.1 */
1274     protected static ForkJoinTask<?> pollTask() {
1275 dl 1.124 Thread t; ForkJoinWorkerThread w;
1276     return (((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) ?
1277     (w = (ForkJoinWorkerThread)t).pool.nextTaskFor(w.workQueue) :
1278     null);
1279 dl 1.54 }
1280    
1281 dl 1.94 /**
1282     * If the current thread is operating in a ForkJoinPool,
1283     * unschedules and returns, without executing, a task externally
1284     * submitted to the pool, if one is available. Availability may be
1285     * transient, so a {@code null} result does not necessarily imply
1286     * quiescence of the pool. This method is designed primarily to
1287     * support extensions, and is unlikely to be useful otherwise.
1288     *
1289     * @return a task, or {@code null} if none are available
1290 jsr166 1.107 * @since 9
1291 dl 1.94 */
1292     protected static ForkJoinTask<?> pollSubmission() {
1293 dl 1.96 Thread t;
1294 dl 1.124 return (((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) ?
1295     ((ForkJoinWorkerThread)t).pool.pollSubmission() : null);
1296 dl 1.94 }
1297    
1298 dl 1.60 // tag operations
1299 dl 1.54
1300     /**
1301 dl 1.60 * Returns the tag for this task.
1302 dl 1.54 *
1303 dl 1.60 * @return the tag for this task
1304 dl 1.54 * @since 1.8
1305     */
1306 dl 1.60 public final short getForkJoinTaskTag() {
1307     return (short)status;
1308 dl 1.54 }
1309    
1310     /**
1311 jsr166 1.102 * Atomically sets the tag value for this task and returns the old value.
1312 dl 1.54 *
1313 jsr166 1.102 * @param newValue the new tag value
1314 dl 1.60 * @return the previous value of the tag
1315 dl 1.54 * @since 1.8
1316     */
1317 jsr166 1.102 public final short setForkJoinTaskTag(short newValue) {
1318 dl 1.54 for (int s;;) {
1319 dl 1.124 if (casStatus(s = status, (s & ~SMASK) | (newValue & SMASK)))
1320 dl 1.60 return (short)s;
1321 dl 1.54 }
1322     }
1323    
1324     /**
1325 dl 1.60 * Atomically conditionally sets the tag value for this task.
1326     * Among other applications, tags can be used as visit markers
1327 dl 1.61 * in tasks operating on graphs, as in methods that check: {@code
1328 dl 1.60 * if (task.compareAndSetForkJoinTaskTag((short)0, (short)1))}
1329     * before processing, otherwise exiting because the node has
1330     * already been visited.
1331 dl 1.54 *
1332 jsr166 1.102 * @param expect the expected tag value
1333     * @param update the new tag value
1334 jsr166 1.76 * @return {@code true} if successful; i.e., the current value was
1335 jsr166 1.102 * equal to {@code expect} and was changed to {@code update}.
1336 dl 1.54 * @since 1.8
1337     */
1338 jsr166 1.102 public final boolean compareAndSetForkJoinTaskTag(short expect, short update) {
1339 dl 1.54 for (int s;;) {
1340 jsr166 1.102 if ((short)(s = status) != expect)
1341 dl 1.54 return false;
1342 dl 1.124 if (casStatus(s, (s & ~SMASK) | (update & SMASK)))
1343 dl 1.54 return true;
1344     }
1345 jsr166 1.1 }
1346    
1347 jsr166 1.5 /**
1348 jsr166 1.95 * Adapter for Runnables. This implements RunnableFuture
1349 jsr166 1.5 * to be compliant with AbstractExecutorService constraints
1350     * when used in ForkJoinPool.
1351     */
1352     static final class AdaptedRunnable<T> extends ForkJoinTask<T>
1353     implements RunnableFuture<T> {
1354 jsr166 1.123 @SuppressWarnings("serial") // Conditionally serializable
1355 jsr166 1.5 final Runnable runnable;
1356 jsr166 1.123 @SuppressWarnings("serial") // Conditionally serializable
1357 jsr166 1.5 T result;
1358     AdaptedRunnable(Runnable runnable, T result) {
1359     if (runnable == null) throw new NullPointerException();
1360     this.runnable = runnable;
1361 dl 1.59 this.result = result; // OK to set this even before completion
1362 jsr166 1.5 }
1363 dl 1.59 public final T getRawResult() { return result; }
1364     public final void setRawResult(T v) { result = v; }
1365     public final boolean exec() { runnable.run(); return true; }
1366     public final void run() { invoke(); }
1367 jsr166 1.116 public String toString() {
1368     return super.toString() + "[Wrapped task = " + runnable + "]";
1369     }
1370 dl 1.59 private static final long serialVersionUID = 5232453952276885070L;
1371     }
1372    
1373     /**
1374 jsr166 1.99 * Adapter for Runnables without results.
1375 dl 1.59 */
1376     static final class AdaptedRunnableAction extends ForkJoinTask<Void>
1377     implements RunnableFuture<Void> {
1378 jsr166 1.123 @SuppressWarnings("serial") // Conditionally serializable
1379 dl 1.59 final Runnable runnable;
1380     AdaptedRunnableAction(Runnable runnable) {
1381     if (runnable == null) throw new NullPointerException();
1382     this.runnable = runnable;
1383 jsr166 1.5 }
1384 dl 1.59 public final Void getRawResult() { return null; }
1385     public final void setRawResult(Void v) { }
1386     public final boolean exec() { runnable.run(); return true; }
1387     public final void run() { invoke(); }
1388 jsr166 1.116 public String toString() {
1389     return super.toString() + "[Wrapped task = " + runnable + "]";
1390     }
1391 jsr166 1.5 private static final long serialVersionUID = 5232453952276885070L;
1392     }
1393    
1394     /**
1395 jsr166 1.99 * Adapter for Runnables in which failure forces worker exception.
1396 dl 1.73 */
1397     static final class RunnableExecuteAction extends ForkJoinTask<Void> {
1398 jsr166 1.123 @SuppressWarnings("serial") // Conditionally serializable
1399 dl 1.73 final Runnable runnable;
1400     RunnableExecuteAction(Runnable runnable) {
1401     if (runnable == null) throw new NullPointerException();
1402     this.runnable = runnable;
1403     }
1404     public final Void getRawResult() { return null; }
1405     public final void setRawResult(Void v) { }
1406     public final boolean exec() { runnable.run(); return true; }
1407 dl 1.145 int trySetException(Throwable ex) { // if a handler, invoke it
1408     int s; Thread t; java.lang.Thread.UncaughtExceptionHandler h;
1409 dl 1.126 if (isExceptionalStatus(s = trySetThrown(ex)) &&
1410 jsr166 1.146 (h = ((t = Thread.currentThread()).
1411     getUncaughtExceptionHandler())) != null) {
1412     try {
1413     h.uncaughtException(t, ex);
1414     } catch (Throwable ignore) {
1415     }
1416     }
1417 dl 1.124 return s;
1418 dl 1.73 }
1419     private static final long serialVersionUID = 5232453952276885070L;
1420     }
1421    
1422     /**
1423 jsr166 1.99 * Adapter for Callables.
1424 jsr166 1.5 */
1425     static final class AdaptedCallable<T> extends ForkJoinTask<T>
1426     implements RunnableFuture<T> {
1427 jsr166 1.123 @SuppressWarnings("serial") // Conditionally serializable
1428 jsr166 1.6 final Callable<? extends T> callable;
1429 jsr166 1.123 @SuppressWarnings("serial") // Conditionally serializable
1430 jsr166 1.5 T result;
1431 jsr166 1.6 AdaptedCallable(Callable<? extends T> callable) {
1432 jsr166 1.5 if (callable == null) throw new NullPointerException();
1433     this.callable = callable;
1434     }
1435 dl 1.59 public final T getRawResult() { return result; }
1436     public final void setRawResult(T v) { result = v; }
1437     public final boolean exec() {
1438 jsr166 1.5 try {
1439     result = callable.call();
1440     return true;
1441     } catch (RuntimeException rex) {
1442     throw rex;
1443     } catch (Exception ex) {
1444     throw new RuntimeException(ex);
1445     }
1446     }
1447 dl 1.59 public final void run() { invoke(); }
1448 jsr166 1.116 public String toString() {
1449     return super.toString() + "[Wrapped task = " + callable + "]";
1450     }
1451 jsr166 1.117 private static final long serialVersionUID = 2838392045355241008L;
1452 jsr166 1.5 }
1453 jsr166 1.2
1454 dl 1.129 static final class AdaptedInterruptibleCallable<T> extends ForkJoinTask<T>
1455     implements RunnableFuture<T> {
1456     @SuppressWarnings("serial") // Conditionally serializable
1457     final Callable<? extends T> callable;
1458 jsr166 1.153 transient volatile Thread runner;
1459 dl 1.129 @SuppressWarnings("serial") // Conditionally serializable
1460     T result;
1461     AdaptedInterruptibleCallable(Callable<? extends T> callable) {
1462     if (callable == null) throw new NullPointerException();
1463     this.callable = callable;
1464     }
1465     public final T getRawResult() { return result; }
1466     public final void setRawResult(T v) { result = v; }
1467     public final boolean exec() {
1468     Thread.interrupted();
1469     runner = Thread.currentThread();
1470     try {
1471 dl 1.133 if (!isDone()) // recheck
1472     result = callable.call();
1473 dl 1.129 return true;
1474     } catch (RuntimeException rex) {
1475     throw rex;
1476     } catch (Exception ex) {
1477     throw new RuntimeException(ex);
1478     } finally {
1479     runner = null;
1480     Thread.interrupted();
1481     }
1482     }
1483     public final void run() { invoke(); }
1484     public final boolean cancel(boolean mayInterruptIfRunning) {
1485     Thread t;
1486     boolean stat = super.cancel(false);
1487     if (mayInterruptIfRunning && (t = runner) != null) {
1488     try {
1489     t.interrupt();
1490     } catch (Throwable ignore) {
1491     }
1492     }
1493     return stat;
1494     }
1495     public String toString() {
1496     return super.toString() + "[Wrapped task = " + callable + "]";
1497     }
1498     private static final long serialVersionUID = 2838392045355241008L;
1499     }
1500    
1501 jsr166 1.2 /**
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     * a null result upon {@link #join}.
1505 jsr166 1.2 *
1506     * @param runnable the runnable action
1507     * @return the task
1508     */
1509 jsr166 1.6 public static ForkJoinTask<?> adapt(Runnable runnable) {
1510 dl 1.59 return new AdaptedRunnableAction(runnable);
1511 jsr166 1.2 }
1512    
1513     /**
1514 jsr166 1.6 * Returns a new {@code ForkJoinTask} that performs the {@code run}
1515     * method of the given {@code Runnable} as its action, and returns
1516     * the given result upon {@link #join}.
1517 jsr166 1.2 *
1518     * @param runnable the runnable action
1519     * @param result the result upon completion
1520 jsr166 1.82 * @param <T> the type of the result
1521 jsr166 1.2 * @return the task
1522     */
1523     public static <T> ForkJoinTask<T> adapt(Runnable runnable, T result) {
1524 jsr166 1.5 return new AdaptedRunnable<T>(runnable, result);
1525 jsr166 1.2 }
1526    
1527     /**
1528 jsr166 1.6 * Returns a new {@code ForkJoinTask} that performs the {@code call}
1529     * method of the given {@code Callable} as its action, and returns
1530     * its result upon {@link #join}, translating any checked exceptions
1531     * encountered into {@code RuntimeException}.
1532 jsr166 1.2 *
1533     * @param callable the callable action
1534 jsr166 1.82 * @param <T> the type of the callable's result
1535 jsr166 1.2 * @return the task
1536     */
1537 jsr166 1.6 public static <T> ForkJoinTask<T> adapt(Callable<? extends T> callable) {
1538 jsr166 1.5 return new AdaptedCallable<T>(callable);
1539 jsr166 1.2 }
1540    
1541 dl 1.129 /**
1542 jsr166 1.138 * Returns a new {@code ForkJoinTask} that performs the {@code call}
1543     * method of the given {@code Callable} as its action, and returns
1544     * its result upon {@link #join}, translating any checked exceptions
1545     * encountered into {@code RuntimeException}. Additionally,
1546     * invocations of {@code cancel} with {@code mayInterruptIfRunning
1547     * true} will attempt to interrupt the thread performing the task.
1548 dl 1.129 *
1549     * @param callable the callable action
1550     * @param <T> the type of the callable's result
1551     * @return the task
1552     *
1553 dl 1.156 * @since 19
1554 dl 1.129 */
1555 dl 1.155 public static <T> ForkJoinTask<T> adaptInterruptible(Callable<? extends T> callable) {
1556     // https://bugs.openjdk.java.net/browse/JDK-8246587
1557 dl 1.129 return new AdaptedInterruptibleCallable<T>(callable);
1558     }
1559    
1560 jsr166 1.1 // Serialization support
1561    
1562     private static final long serialVersionUID = -7721805057305804111L;
1563    
1564     /**
1565 jsr166 1.53 * Saves this task to a stream (that is, serializes it).
1566 jsr166 1.1 *
1567 jsr166 1.83 * @param s the stream
1568 jsr166 1.84 * @throws java.io.IOException if an I/O error occurs
1569 jsr166 1.1 * @serialData the current run status and the exception thrown
1570 jsr166 1.4 * during execution, or {@code null} if none
1571 jsr166 1.1 */
1572     private void writeObject(java.io.ObjectOutputStream s)
1573     throws java.io.IOException {
1574 dl 1.124 Aux a;
1575 jsr166 1.1 s.defaultWriteObject();
1576 dl 1.124 s.writeObject((a = aux) == null ? null : a.ex);
1577 jsr166 1.1 }
1578    
1579     /**
1580 jsr166 1.53 * Reconstitutes this task from a stream (that is, deserializes it).
1581 jsr166 1.83 * @param s the stream
1582 jsr166 1.84 * @throws ClassNotFoundException if the class of a serialized object
1583     * could not be found
1584     * @throws java.io.IOException if an I/O error occurs
1585 jsr166 1.1 */
1586     private void readObject(java.io.ObjectInputStream s)
1587     throws java.io.IOException, ClassNotFoundException {
1588     s.defaultReadObject();
1589     Object ex = s.readObject();
1590     if (ex != null)
1591 dl 1.124 trySetThrown((Throwable)ex);
1592 jsr166 1.1 }
1593    
1594 dl 1.45 static {
1595 dl 1.154 U = Unsafe.getUnsafe();
1596     STATUS = U.objectFieldOffset(ForkJoinTask.class, "status");
1597     AUX = U.objectFieldOffset(ForkJoinTask.class, "aux");
1598 dl 1.155 Class<?> dep1 = LockSupport.class; // ensure loaded
1599     Class<?> dep2 = Aux.class;
1600 jsr166 1.1 }
1601 dl 1.45
1602 jsr166 1.1 }