ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinTask.java
Revision: 1.126
Committed: Mon Jan 20 15:51:54 2020 UTC (4 years, 4 months ago) by dl
Branch: MAIN
Changes since 1.125: +106 -118 lines
Log Message:
improve compatibilty for timeouts etc; increase common code paths

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