ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinTask.java
Revision: 1.157
Committed: Mon Apr 4 12:02:42 2022 UTC (2 years, 1 month ago) by dl
Branch: MAIN
Changes since 1.156: +67 -81 lines
Log Message:
Cancellation compatibility with previous versions; other misc improvements

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