ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinTask.java
Revision: 1.144
Committed: Wed Aug 12 18:18:12 2020 UTC (3 years, 9 months ago) by jsr166
Branch: MAIN
Changes since 1.143: +8 -4 lines
Log Message:
reduce scope of local s

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