ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinTask.java
Revision: 1.124
Committed: Fri Jan 17 18:12:07 2020 UTC (4 years, 4 months ago) by dl
Branch: MAIN
Changes since 1.123: +381 -460 lines
Log Message:
FJ 1/20 refresh

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