ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinTask.java
Revision: 1.140
Committed: Tue Aug 11 20:56:30 2020 UTC (3 years, 9 months ago) by jsr166
Branch: MAIN
Changes since 1.139: +0 -1 lines
Log Message:
fix errorprone [RemoveUnusedImports]

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