ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinTask.java
Revision: 1.128
Committed: Sat Feb 1 20:20:17 2020 UTC (4 years, 4 months ago) by dl
Branch: MAIN
Changes since 1.127: +181 -125 lines
Log Message:
Reduce inessential FJP vs TPE differences

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