ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinTask.java
Revision: 1.147
Committed: Fri Dec 4 20:29:22 2020 UTC (3 years, 6 months ago) by jsr166
Branch: MAIN
Changes since 1.146: +4 -18 lines
Log Message:
JDK-8246587: adaptInterruptible deferred to its own independent change

File Contents

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