ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinTask.java
Revision: 1.42
Committed: Tue Nov 23 10:51:04 2010 UTC (13 years, 6 months ago) by dl
Branch: MAIN
Changes since 1.41: +5 -4 lines
Log Message:
Improve inForkJoinPool javadoc

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     * http://creativecommons.org/licenses/publicdomain
5     */
6    
7     package java.util.concurrent;
8    
9     import java.io.Serializable;
10     import java.util.Collection;
11     import java.util.Collections;
12     import java.util.List;
13 jsr166 1.7 import java.util.RandomAccess;
14 jsr166 1.1 import java.util.Map;
15     import java.util.WeakHashMap;
16 dl 1.32 import java.util.concurrent.Callable;
17     import java.util.concurrent.CancellationException;
18     import java.util.concurrent.ExecutionException;
19     import java.util.concurrent.Executor;
20     import java.util.concurrent.ExecutorService;
21     import java.util.concurrent.Future;
22     import java.util.concurrent.RejectedExecutionException;
23     import java.util.concurrent.RunnableFuture;
24     import java.util.concurrent.TimeUnit;
25     import java.util.concurrent.TimeoutException;
26 jsr166 1.1
27     /**
28 jsr166 1.6 * Abstract base class for tasks that run within a {@link ForkJoinPool}.
29     * A {@code ForkJoinTask} is a thread-like entity that is much
30 jsr166 1.1 * lighter weight than a normal thread. Huge numbers of tasks and
31     * subtasks may be hosted by a small number of actual threads in a
32     * ForkJoinPool, at the price of some usage limitations.
33     *
34 jsr166 1.6 * <p>A "main" {@code ForkJoinTask} begins execution when submitted
35     * to a {@link ForkJoinPool}. Once started, it will usually in turn
36     * start other subtasks. As indicated by the name of this class,
37     * many programs using {@code ForkJoinTask} employ only methods
38     * {@link #fork} and {@link #join}, or derivatives such as {@link
39 jsr166 1.27 * #invokeAll(ForkJoinTask...) invokeAll}. However, this class also
40     * provides a number of other methods that can come into play in
41     * advanced usages, as well as extension mechanics that allow
42     * support of new forms of fork/join processing.
43 jsr166 1.1 *
44 jsr166 1.6 * <p>A {@code ForkJoinTask} is a lightweight form of {@link Future}.
45     * The efficiency of {@code ForkJoinTask}s stems from a set of
46     * restrictions (that are only partially statically enforceable)
47     * reflecting their intended use as computational tasks calculating
48     * pure functions or operating on purely isolated objects. The
49     * primary coordination mechanisms are {@link #fork}, that arranges
50     * asynchronous execution, and {@link #join}, that doesn't proceed
51     * until the task's result has been computed. Computations should
52     * avoid {@code synchronized} methods or blocks, and should minimize
53     * other blocking synchronization apart from joining other tasks or
54     * using synchronizers such as Phasers that are advertised to
55     * cooperate with fork/join scheduling. Tasks should also not perform
56     * blocking IO, and should ideally access variables that are
57     * completely independent of those accessed by other running
58     * tasks. Minor breaches of these restrictions, for example using
59     * shared output streams, may be tolerable in practice, but frequent
60     * use may result in poor performance, and the potential to
61     * indefinitely stall if the number of threads not waiting for IO or
62     * other external synchronization becomes exhausted. This usage
63     * restriction is in part enforced by not permitting checked
64     * exceptions such as {@code IOExceptions} to be thrown. However,
65     * computations may still encounter unchecked exceptions, that are
66 jsr166 1.7 * rethrown to callers attempting to join them. These exceptions may
67 jsr166 1.11 * additionally include {@link RejectedExecutionException} stemming
68     * from internal resource exhaustion, such as failure to allocate
69     * internal task queues.
70 jsr166 1.1 *
71     * <p>The primary method for awaiting completion and extracting
72     * results of a task is {@link #join}, but there are several variants:
73     * The {@link Future#get} methods support interruptible and/or timed
74     * waits for completion and report results using {@code Future}
75 dl 1.16 * conventions. Method {@link #invoke} is semantically
76 jsr166 1.8 * equivalent to {@code fork(); join()} but always attempts to begin
77     * execution in the current thread. The "<em>quiet</em>" forms of
78     * these methods do not extract results or report exceptions. These
79 jsr166 1.1 * may be useful when a set of tasks are being executed, and you need
80     * to delay processing of results or exceptions until all complete.
81     * Method {@code invokeAll} (available in multiple versions)
82     * performs the most common form of parallel invocation: forking a set
83     * of tasks and joining them all.
84     *
85 jsr166 1.8 * <p>The execution status of tasks may be queried at several levels
86     * of detail: {@link #isDone} is true if a task completed in any way
87     * (including the case where a task was cancelled without executing);
88     * {@link #isCompletedNormally} is true if a task completed without
89 jsr166 1.10 * cancellation or encountering an exception; {@link #isCancelled} is
90     * true if the task was cancelled (in which case {@link #getException}
91     * returns a {@link java.util.concurrent.CancellationException}); and
92     * {@link #isCompletedAbnormally} is true if a task was either
93     * cancelled or encountered an exception, in which case {@link
94     * #getException} will return either the encountered exception or
95     * {@link java.util.concurrent.CancellationException}.
96 jsr166 1.8 *
97 jsr166 1.6 * <p>The ForkJoinTask class is not usually directly subclassed.
98 jsr166 1.1 * Instead, you subclass one of the abstract classes that support a
99 jsr166 1.6 * particular style of fork/join processing, typically {@link
100     * RecursiveAction} for computations that do not return results, or
101     * {@link RecursiveTask} for those that do. Normally, a concrete
102 jsr166 1.1 * ForkJoinTask subclass declares fields comprising its parameters,
103     * established in a constructor, and then defines a {@code compute}
104     * method that somehow uses the control methods supplied by this base
105     * class. While these methods have {@code public} access (to allow
106 jsr166 1.7 * instances of different task subclasses to call each other's
107 jsr166 1.1 * methods), some of them may only be called from within other
108     * ForkJoinTasks (as may be determined using method {@link
109     * #inForkJoinPool}). Attempts to invoke them in other contexts
110     * result in exceptions or errors, possibly including
111 dl 1.20 * {@code ClassCastException}.
112 jsr166 1.1 *
113 dl 1.38 * <p>Method {@link #join} and its variants are appropriate for use
114     * only when completion dependencies are acyclic; that is, the
115     * parallel computation can be described as a directed acyclic graph
116     * (DAG). Otherwise, executions may encounter a form of deadlock as
117     * tasks cyclically wait for each other. However, this framework
118     * supports other methods and techniques (for example the use of
119     * {@link Phaser}, {@link #helpQuiesce}, and {@link #complete}) that
120     * may be of use in constructing custom subclasses for problems that
121     * are not statically structured as DAGs.
122     *
123 jsr166 1.7 * <p>Most base support methods are {@code final}, to prevent
124     * overriding of implementations that are intrinsically tied to the
125     * underlying lightweight task scheduling framework. Developers
126     * creating new basic styles of fork/join processing should minimally
127     * implement {@code protected} methods {@link #exec}, {@link
128     * #setRawResult}, and {@link #getRawResult}, while also introducing
129     * an abstract computational method that can be implemented in its
130     * subclasses, possibly relying on other {@code protected} methods
131     * provided by this class.
132 jsr166 1.1 *
133     * <p>ForkJoinTasks should perform relatively small amounts of
134 jsr166 1.7 * computation. Large tasks should be split into smaller subtasks,
135     * usually via recursive decomposition. As a very rough rule of thumb,
136     * a task should perform more than 100 and less than 10000 basic
137 dl 1.40 * computational steps, and should avoid indefinite looping. If tasks
138     * are too big, then parallelism cannot improve throughput. If too
139     * small, then memory and internal task maintenance overhead may
140     * overwhelm processing.
141 jsr166 1.1 *
142 jsr166 1.8 * <p>This class provides {@code adapt} methods for {@link Runnable}
143     * and {@link Callable}, that may be of use when mixing execution of
144 dl 1.16 * {@code ForkJoinTasks} with other kinds of tasks. When all tasks are
145     * of this form, consider using a pool constructed in <em>asyncMode</em>.
146 jsr166 1.6 *
147 jsr166 1.7 * <p>ForkJoinTasks are {@code Serializable}, which enables them to be
148     * used in extensions such as remote execution frameworks. It is
149     * sensible to serialize tasks only before or after, but not during,
150     * execution. Serialization is not relied on during execution itself.
151 jsr166 1.1 *
152     * @since 1.7
153     * @author Doug Lea
154     */
155     public abstract class ForkJoinTask<V> implements Future<V>, Serializable {
156    
157 dl 1.13 /*
158     * See the internal documentation of class ForkJoinPool for a
159     * general implementation overview. ForkJoinTasks are mainly
160     * responsible for maintaining their "status" field amidst relays
161     * to methods in ForkJoinWorkerThread and ForkJoinPool. The
162     * methods of this class are more-or-less layered into (1) basic
163     * status maintenance (2) execution and awaiting completion (3)
164     * user-level methods that additionally report results. This is
165     * sometimes hard to see because this file orders exported methods
166 dl 1.17 * in a way that flows well in javadocs. In particular, most
167     * join mechanics are in method quietlyJoin, below.
168 dl 1.13 */
169    
170 dl 1.17 /*
171     * The status field holds run control status bits packed into a
172     * single int to minimize footprint and to ensure atomicity (via
173     * CAS). Status is initially zero, and takes on nonnegative
174     * values until completed, upon which status holds value
175 jsr166 1.23 * NORMAL, CANCELLED, or EXCEPTIONAL. Tasks undergoing blocking
176 dl 1.17 * waits by other threads have the SIGNAL bit set. Completion of
177     * a stolen task with SIGNAL set awakens any waiters via
178     * notifyAll. Even though suboptimal for some purposes, we use
179     * basic builtin wait/notify to take advantage of "monitor
180     * inflation" in JVMs that we would otherwise need to emulate to
181     * avoid adding further per-task bookkeeping overhead. We want
182     * these monitors to be "fat", i.e., not use biasing or thin-lock
183     * techniques, so use some odd coding idioms that tend to avoid
184     * them.
185 jsr166 1.1 */
186 dl 1.17
187     /** The run status of this task */
188 jsr166 1.1 volatile int status; // accessed directly by pool and workers
189    
190 dl 1.16 private static final int NORMAL = -1;
191     private static final int CANCELLED = -2;
192     private static final int EXCEPTIONAL = -3;
193     private static final int SIGNAL = 1;
194 jsr166 1.1
195     /**
196     * Table of exceptions thrown by tasks, to enable reporting by
197     * callers. Because exceptions are rare, we don't directly keep
198     * them with task objects, but instead use a weak ref table. Note
199     * that cancellation exceptions don't appear in the table, but are
200     * instead recorded as status values.
201     * TODO: Use ConcurrentReferenceHashMap
202     */
203     static final Map<ForkJoinTask<?>, Throwable> exceptionMap =
204     Collections.synchronizedMap
205     (new WeakHashMap<ForkJoinTask<?>, Throwable>());
206    
207 dl 1.13 // Maintaining completion status
208 jsr166 1.1
209     /**
210 dl 1.13 * Marks completion and wakes up threads waiting to join this task,
211     * also clearing signal request bits.
212     *
213     * @param completion one of NORMAL, CANCELLED, EXCEPTIONAL
214 jsr166 1.1 */
215 dl 1.17 private void setCompletion(int completion) {
216 dl 1.13 int s;
217     while ((s = status) >= 0) {
218     if (UNSAFE.compareAndSwapInt(this, statusOffset, s, completion)) {
219 dl 1.17 if (s != 0)
220 dl 1.13 synchronized (this) { notifyAll(); }
221 dl 1.17 break;
222 dl 1.13 }
223     }
224 jsr166 1.1 }
225    
226     /**
227 jsr166 1.21 * Records exception and sets exceptional completion.
228 jsr166 1.24 *
229 dl 1.15 * @return status on exit
230 jsr166 1.1 */
231 dl 1.17 private void setExceptionalCompletion(Throwable rex) {
232 dl 1.13 exceptionMap.put(this, rex);
233 dl 1.17 setCompletion(EXCEPTIONAL);
234 jsr166 1.1 }
235    
236     /**
237 dl 1.40 * Blocks a worker thread until completed or timed out. Called
238     * only by pool.
239 jsr166 1.1 */
240 dl 1.40 final void internalAwaitDone(long millis, int nanos) {
241     if (status >= 0) {
242     try { // the odd construction reduces lock bias effects
243 jsr166 1.26 synchronized (this) {
244 dl 1.40 if (status > 0 ||
245     UNSAFE.compareAndSwapInt(this, statusOffset,
246     0, SIGNAL))
247     wait(millis, nanos);
248 jsr166 1.1 }
249 dl 1.17 } catch (InterruptedException ie) {
250     cancelIfTerminating();
251 jsr166 1.1 }
252     }
253     }
254    
255     /**
256 dl 1.40 * Blocks a non-worker-thread until completion.
257 dl 1.19 */
258 dl 1.40 private void externalAwaitDone() {
259     if (status >= 0) {
260     boolean interrupted = false;
261     synchronized(this) {
262     int s;
263     while ((s = status) >= 0) {
264     if (s == 0 &&
265     !UNSAFE.compareAndSwapInt(this, statusOffset,
266     0, SIGNAL))
267     continue;
268     try {
269     wait();
270     } catch (InterruptedException ie) {
271     interrupted = true;
272     }
273 dl 1.19 }
274     }
275 dl 1.40 if (interrupted)
276     Thread.currentThread().interrupt();
277 dl 1.19 }
278     }
279    
280     /**
281 jsr166 1.41 * Blocks a non-worker-thread until completion or interruption or timeout.
282 jsr166 1.1 */
283 dl 1.40 private void externalInterruptibleAwaitDone(boolean timed, long nanos)
284     throws InterruptedException {
285     if (Thread.interrupted())
286     throw new InterruptedException();
287     if (status >= 0) {
288     long startTime = timed ? System.nanoTime() : 0L;
289     synchronized(this) {
290     int s;
291     while ((s = status) >= 0) {
292     long nt;
293     if (s == 0 &&
294     !UNSAFE.compareAndSwapInt(this, statusOffset,
295     0, SIGNAL))
296     continue;
297     else if (!timed)
298     wait();
299     else if ((nt = nanos - (System.nanoTime()-startTime)) > 0L)
300     wait(nt / 1000000, (int)(nt % 1000000));
301     else
302     break;
303 dl 1.13 }
304 jsr166 1.1 }
305     }
306     }
307    
308     /**
309 dl 1.15 * Unless done, calls exec and records status if completed, but
310 dl 1.16 * doesn't wait for completion otherwise. Primary execution method
311     * for ForkJoinWorkerThread.
312 jsr166 1.1 */
313 dl 1.17 final void quietlyExec() {
314 dl 1.15 try {
315     if (status < 0 || !exec())
316     return;
317     } catch (Throwable rex) {
318     setExceptionalCompletion(rex);
319     return;
320 jsr166 1.1 }
321 dl 1.15 setCompletion(NORMAL); // must be outside try block
322 jsr166 1.1 }
323    
324     // public methods
325    
326     /**
327     * Arranges to asynchronously execute this task. While it is not
328     * necessarily enforced, it is a usage error to fork a task more
329 jsr166 1.6 * than once unless it has completed and been reinitialized.
330 jsr166 1.11 * Subsequent modifications to the state of this task or any data
331     * it operates on are not necessarily consistently observable by
332     * any thread other than the one executing it unless preceded by a
333     * call to {@link #join} or related methods, or a call to {@link
334     * #isDone} returning {@code true}.
335 jsr166 1.6 *
336     * <p>This method may be invoked only from within {@code
337 jsr166 1.39 * ForkJoinPool} computations (as may be determined using method
338 jsr166 1.6 * {@link #inForkJoinPool}). Attempts to invoke in other contexts
339     * result in exceptions or errors, possibly including {@code
340     * ClassCastException}.
341 jsr166 1.2 *
342 jsr166 1.6 * @return {@code this}, to simplify usage
343 jsr166 1.1 */
344 jsr166 1.2 public final ForkJoinTask<V> fork() {
345 jsr166 1.1 ((ForkJoinWorkerThread) Thread.currentThread())
346     .pushTask(this);
347 jsr166 1.2 return this;
348 jsr166 1.1 }
349    
350     /**
351 dl 1.38 * Returns the result of the computation when it {@link #isDone is
352     * done}. This method differs from {@link #get()} in that
353 jsr166 1.6 * abnormal completion results in {@code RuntimeException} or
354 dl 1.38 * {@code Error}, not {@code ExecutionException}, and that
355     * interrupts of the calling thread do <em>not</em> cause the
356     * method to abruptly return by throwing {@code
357     * InterruptedException}.
358 jsr166 1.1 *
359     * @return the computed result
360     */
361     public final V join() {
362 dl 1.17 quietlyJoin();
363     Throwable ex;
364     if (status < NORMAL && (ex = getException()) != null)
365     UNSAFE.throwException(ex);
366     return getRawResult();
367 jsr166 1.1 }
368    
369     /**
370     * Commences performing this task, awaits its completion if
371 jsr166 1.21 * necessary, and returns its result, or throws an (unchecked)
372 dl 1.20 * {@code RuntimeException} or {@code Error} if the underlying
373     * computation did so.
374 jsr166 1.1 *
375     * @return the computed result
376     */
377     public final V invoke() {
378 dl 1.17 quietlyInvoke();
379     Throwable ex;
380     if (status < NORMAL && (ex = getException()) != null)
381     UNSAFE.throwException(ex);
382     return getRawResult();
383 jsr166 1.1 }
384    
385     /**
386 jsr166 1.8 * Forks the given tasks, returning when {@code isDone} holds for
387     * each task or an (unchecked) exception is encountered, in which
388 dl 1.20 * case the exception is rethrown. If more than one task
389     * encounters an exception, then this method throws any one of
390     * these exceptions. If any task encounters an exception, the
391     * other may be cancelled. However, the execution status of
392     * individual tasks is not guaranteed upon exceptional return. The
393     * status of each task may be obtained using {@link
394     * #getException()} and related methods to check if they have been
395     * cancelled, completed normally or exceptionally, or left
396     * unprocessed.
397 jsr166 1.6 *
398     * <p>This method may be invoked only from within {@code
399 dl 1.38 * ForkJoinPool} computations (as may be determined using method
400 jsr166 1.6 * {@link #inForkJoinPool}). Attempts to invoke in other contexts
401     * result in exceptions or errors, possibly including {@code
402     * ClassCastException}.
403     *
404     * @param t1 the first task
405     * @param t2 the second task
406     * @throws NullPointerException if any task is null
407 jsr166 1.1 */
408 jsr166 1.6 public static void invokeAll(ForkJoinTask<?> t1, ForkJoinTask<?> t2) {
409 jsr166 1.1 t2.fork();
410     t1.invoke();
411     t2.join();
412     }
413    
414     /**
415 jsr166 1.6 * Forks the given tasks, returning when {@code isDone} holds for
416 jsr166 1.8 * each task or an (unchecked) exception is encountered, in which
417 dl 1.20 * case the exception is rethrown. If more than one task
418     * encounters an exception, then this method throws any one of
419     * these exceptions. If any task encounters an exception, others
420     * may be cancelled. However, the execution status of individual
421     * tasks is not guaranteed upon exceptional return. The status of
422     * each task may be obtained using {@link #getException()} and
423     * related methods to check if they have been cancelled, completed
424     * normally or exceptionally, or left unprocessed.
425 jsr166 1.6 *
426     * <p>This method may be invoked only from within {@code
427 dl 1.38 * ForkJoinPool} computations (as may be determined using method
428 jsr166 1.6 * {@link #inForkJoinPool}). Attempts to invoke in other contexts
429     * result in exceptions or errors, possibly including {@code
430     * ClassCastException}.
431     *
432     * @param tasks the tasks
433 jsr166 1.8 * @throws NullPointerException if any task is null
434 jsr166 1.1 */
435     public static void invokeAll(ForkJoinTask<?>... tasks) {
436     Throwable ex = null;
437     int last = tasks.length - 1;
438     for (int i = last; i >= 0; --i) {
439     ForkJoinTask<?> t = tasks[i];
440     if (t == null) {
441     if (ex == null)
442     ex = new NullPointerException();
443     }
444     else if (i != 0)
445     t.fork();
446 dl 1.17 else {
447     t.quietlyInvoke();
448     if (ex == null && t.status < NORMAL)
449     ex = t.getException();
450     }
451 jsr166 1.1 }
452     for (int i = 1; i <= last; ++i) {
453     ForkJoinTask<?> t = tasks[i];
454     if (t != null) {
455     if (ex != null)
456     t.cancel(false);
457 dl 1.17 else {
458     t.quietlyJoin();
459     if (ex == null && t.status < NORMAL)
460     ex = t.getException();
461     }
462 jsr166 1.1 }
463     }
464     if (ex != null)
465 dl 1.13 UNSAFE.throwException(ex);
466 jsr166 1.1 }
467    
468     /**
469 jsr166 1.7 * Forks all tasks in the specified collection, returning when
470 jsr166 1.8 * {@code isDone} holds for each task or an (unchecked) exception
471 dl 1.20 * is encountered, in which case the exception is rethrown. If
472     * more than one task encounters an exception, then this method
473     * throws any one of these exceptions. If any task encounters an
474     * exception, others may be cancelled. However, the execution
475     * status of individual tasks is not guaranteed upon exceptional
476     * return. The status of each task may be obtained using {@link
477     * #getException()} and related methods to check if they have been
478     * cancelled, completed normally or exceptionally, or left
479     * unprocessed.
480 jsr166 1.6 *
481     * <p>This method may be invoked only from within {@code
482 dl 1.38 * ForkJoinPool} computations (as may be determined using method
483 jsr166 1.6 * {@link #inForkJoinPool}). Attempts to invoke in other contexts
484     * result in exceptions or errors, possibly including {@code
485     * ClassCastException}.
486 jsr166 1.1 *
487     * @param tasks the collection of tasks
488 jsr166 1.2 * @return the tasks argument, to simplify usage
489 jsr166 1.1 * @throws NullPointerException if tasks or any element are null
490     */
491 jsr166 1.2 public static <T extends ForkJoinTask<?>> Collection<T> invokeAll(Collection<T> tasks) {
492 jsr166 1.7 if (!(tasks instanceof RandomAccess) || !(tasks instanceof List<?>)) {
493 jsr166 1.1 invokeAll(tasks.toArray(new ForkJoinTask<?>[tasks.size()]));
494 jsr166 1.2 return tasks;
495 jsr166 1.1 }
496     @SuppressWarnings("unchecked")
497     List<? extends ForkJoinTask<?>> ts =
498     (List<? extends ForkJoinTask<?>>) tasks;
499     Throwable ex = null;
500     int last = ts.size() - 1;
501     for (int i = last; i >= 0; --i) {
502     ForkJoinTask<?> t = ts.get(i);
503     if (t == null) {
504     if (ex == null)
505     ex = new NullPointerException();
506     }
507     else if (i != 0)
508     t.fork();
509 dl 1.17 else {
510     t.quietlyInvoke();
511     if (ex == null && t.status < NORMAL)
512     ex = t.getException();
513     }
514 jsr166 1.1 }
515     for (int i = 1; i <= last; ++i) {
516     ForkJoinTask<?> t = ts.get(i);
517     if (t != null) {
518     if (ex != null)
519     t.cancel(false);
520 dl 1.17 else {
521     t.quietlyJoin();
522     if (ex == null && t.status < NORMAL)
523     ex = t.getException();
524     }
525 jsr166 1.1 }
526     }
527     if (ex != null)
528 dl 1.13 UNSAFE.throwException(ex);
529 jsr166 1.2 return tasks;
530 jsr166 1.1 }
531    
532     /**
533 jsr166 1.7 * Attempts to cancel execution of this task. This attempt will
534 jsr166 1.36 * fail if the task has already completed or could not be
535     * cancelled for some other reason. If successful, and this task
536     * has not started when {@code cancel} is called, execution of
537 dl 1.38 * this task is suppressed. After this method returns
538     * successfully, unless there is an intervening call to {@link
539     * #reinitialize}, subsequent calls to {@link #isCancelled},
540     * {@link #isDone}, and {@code cancel} will return {@code true}
541     * and calls to {@link #join} and related methods will result in
542     * {@code CancellationException}.
543 jsr166 1.1 *
544     * <p>This method may be overridden in subclasses, but if so, must
545 dl 1.38 * still ensure that these properties hold. In particular, the
546     * {@code cancel} method itself must not throw exceptions.
547 jsr166 1.1 *
548 jsr166 1.6 * <p>This method is designed to be invoked by <em>other</em>
549 jsr166 1.1 * tasks. To terminate the current task, you can just return or
550     * throw an unchecked exception from its computation method, or
551 jsr166 1.4 * invoke {@link #completeExceptionally}.
552 jsr166 1.1 *
553 dl 1.38 * @param mayInterruptIfRunning this value has no effect in the
554     * default implementation because interrupts are not used to
555     * control cancellation.
556 jsr166 1.1 *
557 jsr166 1.4 * @return {@code true} if this task is now cancelled
558 jsr166 1.1 */
559     public boolean cancel(boolean mayInterruptIfRunning) {
560     setCompletion(CANCELLED);
561 dl 1.16 return status == CANCELLED;
562 jsr166 1.1 }
563    
564 dl 1.13 /**
565 dl 1.17 * Cancels, ignoring any exceptions thrown by cancel. Used during
566     * worker and pool shutdown. Cancel is spec'ed not to throw any
567     * exceptions, but if it does anyway, we have no recourse during
568     * shutdown, so guard against this case.
569 dl 1.13 */
570     final void cancelIgnoringExceptions() {
571     try {
572     cancel(false);
573     } catch (Throwable ignore) {
574     }
575     }
576    
577     /**
578 jsr166 1.21 * Cancels if current thread is a terminating worker thread,
579     * ignoring any exceptions thrown by cancel.
580 dl 1.13 */
581 dl 1.17 final void cancelIfTerminating() {
582 dl 1.13 Thread t = Thread.currentThread();
583     if ((t instanceof ForkJoinWorkerThread) &&
584 dl 1.14 ((ForkJoinWorkerThread) t).isTerminating()) {
585 dl 1.13 try {
586     cancel(false);
587     } catch (Throwable ignore) {
588     }
589     }
590     }
591    
592 jsr166 1.8 public final boolean isDone() {
593     return status < 0;
594     }
595    
596     public final boolean isCancelled() {
597 dl 1.16 return status == CANCELLED;
598 jsr166 1.8 }
599    
600     /**
601 jsr166 1.4 * Returns {@code true} if this task threw an exception or was cancelled.
602 jsr166 1.1 *
603 jsr166 1.4 * @return {@code true} if this task threw an exception or was cancelled
604 jsr166 1.1 */
605     public final boolean isCompletedAbnormally() {
606 dl 1.16 return status < NORMAL;
607 jsr166 1.1 }
608    
609     /**
610 jsr166 1.8 * Returns {@code true} if this task completed without throwing an
611     * exception and was not cancelled.
612     *
613     * @return {@code true} if this task completed without throwing an
614     * exception and was not cancelled
615     */
616     public final boolean isCompletedNormally() {
617 dl 1.16 return status == NORMAL;
618 jsr166 1.8 }
619    
620     /**
621 jsr166 1.1 * Returns the exception thrown by the base computation, or a
622 jsr166 1.6 * {@code CancellationException} if cancelled, or {@code null} if
623     * none or if the method has not yet completed.
624 jsr166 1.1 *
625 jsr166 1.4 * @return the exception, or {@code null} if none
626 jsr166 1.1 */
627     public final Throwable getException() {
628 dl 1.16 int s = status;
629 jsr166 1.8 return ((s >= NORMAL) ? null :
630     (s == CANCELLED) ? new CancellationException() :
631     exceptionMap.get(this));
632 jsr166 1.1 }
633    
634     /**
635     * Completes this task abnormally, and if not already aborted or
636     * cancelled, causes it to throw the given exception upon
637     * {@code join} and related operations. This method may be used
638     * to induce exceptions in asynchronous tasks, or to force
639     * completion of tasks that would not otherwise complete. Its use
640 jsr166 1.6 * in other situations is discouraged. This method is
641 jsr166 1.1 * overridable, but overridden versions must invoke {@code super}
642     * implementation to maintain guarantees.
643     *
644 jsr166 1.11 * @param ex the exception to throw. If this exception is not a
645     * {@code RuntimeException} or {@code Error}, the actual exception
646     * thrown will be a {@code RuntimeException} with cause {@code ex}.
647 jsr166 1.1 */
648     public void completeExceptionally(Throwable ex) {
649 dl 1.15 setExceptionalCompletion((ex instanceof RuntimeException) ||
650     (ex instanceof Error) ? ex :
651     new RuntimeException(ex));
652 jsr166 1.1 }
653    
654     /**
655     * Completes this task, and if not already aborted or cancelled,
656 dl 1.22 * returning the given value as the result of subsequent
657     * invocations of {@code join} and related operations. This method
658     * may be used to provide results for asynchronous tasks, or to
659     * provide alternative handling for tasks that would not otherwise
660     * complete normally. Its use in other situations is
661     * discouraged. This method is overridable, but overridden
662     * versions must invoke {@code super} implementation to maintain
663     * guarantees.
664 jsr166 1.1 *
665     * @param value the result value for this task
666     */
667     public void complete(V value) {
668     try {
669     setRawResult(value);
670     } catch (Throwable rex) {
671 dl 1.15 setExceptionalCompletion(rex);
672 jsr166 1.1 return;
673     }
674 dl 1.13 setCompletion(NORMAL);
675 jsr166 1.1 }
676    
677 jsr166 1.25 /**
678 dl 1.29 * Waits if necessary for the computation to complete, and then
679     * retrieves its result.
680     *
681     * @return the computed result
682     * @throws CancellationException if the computation was cancelled
683     * @throws ExecutionException if the computation threw an
684     * exception
685     * @throws InterruptedException if the current thread is not a
686     * member of a ForkJoinPool and was interrupted while waiting
687 jsr166 1.25 */
688 jsr166 1.1 public final V get() throws InterruptedException, ExecutionException {
689 dl 1.40 Thread t = Thread.currentThread();
690     if (t instanceof ForkJoinWorkerThread)
691 dl 1.28 quietlyJoin();
692 dl 1.40 else
693     externalInterruptibleAwaitDone(false, 0L);
694     int s = status;
695     if (s != NORMAL) {
696 dl 1.15 Throwable ex;
697     if (s == CANCELLED)
698     throw new CancellationException();
699     if (s == EXCEPTIONAL && (ex = exceptionMap.get(this)) != null)
700     throw new ExecutionException(ex);
701     }
702     return getRawResult();
703 jsr166 1.1 }
704 dl 1.14
705 jsr166 1.25 /**
706 dl 1.29 * Waits if necessary for at most the given time for the computation
707     * to complete, and then retrieves its result, if available.
708     *
709     * @param timeout the maximum time to wait
710     * @param unit the time unit of the timeout argument
711     * @return the computed result
712     * @throws CancellationException if the computation was cancelled
713     * @throws ExecutionException if the computation threw an
714     * exception
715     * @throws InterruptedException if the current thread is not a
716     * member of a ForkJoinPool and was interrupted while waiting
717     * @throws TimeoutException if the wait timed out
718 jsr166 1.25 */
719 jsr166 1.1 public final V get(long timeout, TimeUnit unit)
720     throws InterruptedException, ExecutionException, TimeoutException {
721 dl 1.18 long nanos = unit.toNanos(timeout);
722 dl 1.40 Thread t = Thread.currentThread();
723     if (t instanceof ForkJoinWorkerThread)
724     ((ForkJoinWorkerThread)t).joinTask(this, true, nanos);
725     else
726     externalInterruptibleAwaitDone(true, nanos);
727     int s = status;
728     if (s != NORMAL) {
729 dl 1.15 Throwable ex;
730 dl 1.40 if (s == CANCELLED)
731 dl 1.15 throw new CancellationException();
732 dl 1.40 if (s == EXCEPTIONAL && (ex = exceptionMap.get(this)) != null)
733 dl 1.15 throw new ExecutionException(ex);
734     throw new TimeoutException();
735     }
736     return getRawResult();
737 jsr166 1.1 }
738    
739     /**
740 dl 1.17 * Joins this task, without returning its result or throwing its
741 jsr166 1.1 * exception. This method may be useful when processing
742     * collections of tasks when some have been cancelled or otherwise
743     * known to have aborted.
744     */
745     public final void quietlyJoin() {
746 dl 1.17 Thread t;
747     if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) {
748     ForkJoinWorkerThread w = (ForkJoinWorkerThread) t;
749     if (status >= 0) {
750     if (w.unpushTask(this)) {
751     boolean completed;
752     try {
753     completed = exec();
754     } catch (Throwable rex) {
755     setExceptionalCompletion(rex);
756     return;
757     }
758     if (completed) {
759     setCompletion(NORMAL);
760     return;
761     }
762     }
763 dl 1.32 w.joinTask(this, false, 0L);
764 dl 1.17 }
765     }
766     else
767     externalAwaitDone();
768 jsr166 1.1 }
769    
770     /**
771     * Commences performing this task and awaits its completion if
772 dl 1.17 * necessary, without returning its result or throwing its
773 dl 1.22 * exception.
774 jsr166 1.1 */
775     public final void quietlyInvoke() {
776 dl 1.17 if (status >= 0) {
777     boolean completed;
778     try {
779     completed = exec();
780     } catch (Throwable rex) {
781     setExceptionalCompletion(rex);
782     return;
783     }
784     if (completed)
785     setCompletion(NORMAL);
786     else
787     quietlyJoin();
788     }
789 jsr166 1.1 }
790    
791     /**
792     * Possibly executes tasks until the pool hosting the current task
793 jsr166 1.7 * {@link ForkJoinPool#isQuiescent is quiescent}. This method may
794     * be of use in designs in which many tasks are forked, but none
795     * are explicitly joined, instead executing them until all are
796     * processed.
797 jsr166 1.6 *
798     * <p>This method may be invoked only from within {@code
799 dl 1.38 * ForkJoinPool} computations (as may be determined using method
800 jsr166 1.6 * {@link #inForkJoinPool}). Attempts to invoke in other contexts
801     * result in exceptions or errors, possibly including {@code
802     * ClassCastException}.
803 jsr166 1.1 */
804     public static void helpQuiesce() {
805     ((ForkJoinWorkerThread) Thread.currentThread())
806     .helpQuiescePool();
807     }
808    
809     /**
810     * Resets the internal bookkeeping state of this task, allowing a
811     * subsequent {@code fork}. This method allows repeated reuse of
812     * this task, but only if reuse occurs when this task has either
813     * never been forked, or has been forked, then completed and all
814     * outstanding joins of this task have also completed. Effects
815 jsr166 1.6 * under any other usage conditions are not guaranteed.
816     * This method may be useful when executing
817 jsr166 1.1 * pre-constructed trees of subtasks in loops.
818 jsr166 1.34 *
819 dl 1.33 * <p>Upon completion of this method, {@code isDone()} reports
820     * {@code false}, and {@code getException()} reports {@code
821     * null}. However, the value returned by {@code getRawResult} is
822     * unaffected. To clear this value, you can invoke {@code
823     * setRawResult(null)}.
824 jsr166 1.1 */
825     public void reinitialize() {
826 dl 1.16 if (status == EXCEPTIONAL)
827 jsr166 1.1 exceptionMap.remove(this);
828     status = 0;
829     }
830    
831     /**
832     * Returns the pool hosting the current task execution, or null
833     * if this task is executing outside of any ForkJoinPool.
834     *
835 jsr166 1.6 * @see #inForkJoinPool
836 jsr166 1.4 * @return the pool, or {@code null} if none
837 jsr166 1.1 */
838     public static ForkJoinPool getPool() {
839     Thread t = Thread.currentThread();
840     return (t instanceof ForkJoinWorkerThread) ?
841     ((ForkJoinWorkerThread) t).pool : null;
842     }
843    
844     /**
845 dl 1.42 * Returns {@code true} if the current thread is a {@link
846     * ForkJoinWorkerThread} executing as a ForkJoinPool computation.
847 jsr166 1.1 *
848 dl 1.42 * @return {@code true} if the current thread is a {@link
849     * ForkJoinWorkerThread} executing as a ForkJoinPool computation,
850     * or {@code false} otherwise
851 jsr166 1.1 */
852     public static boolean inForkJoinPool() {
853     return Thread.currentThread() instanceof ForkJoinWorkerThread;
854     }
855    
856     /**
857     * Tries to unschedule this task for execution. This method will
858     * typically succeed if this task is the most recently forked task
859     * by the current thread, and has not commenced executing in
860     * another thread. This method may be useful when arranging
861     * alternative local processing of tasks that could have been, but
862 jsr166 1.6 * were not, stolen.
863     *
864     * <p>This method may be invoked only from within {@code
865 dl 1.38 * ForkJoinPool} computations (as may be determined using method
866 jsr166 1.6 * {@link #inForkJoinPool}). Attempts to invoke in other contexts
867     * result in exceptions or errors, possibly including {@code
868     * ClassCastException}.
869 jsr166 1.1 *
870 jsr166 1.4 * @return {@code true} if unforked
871 jsr166 1.1 */
872     public boolean tryUnfork() {
873     return ((ForkJoinWorkerThread) Thread.currentThread())
874     .unpushTask(this);
875     }
876    
877     /**
878     * Returns an estimate of the number of tasks that have been
879     * forked by the current worker thread but not yet executed. This
880     * value may be useful for heuristic decisions about whether to
881     * fork other tasks.
882     *
883 jsr166 1.6 * <p>This method may be invoked only from within {@code
884 dl 1.38 * ForkJoinPool} computations (as may be determined using method
885 jsr166 1.6 * {@link #inForkJoinPool}). Attempts to invoke in other contexts
886     * result in exceptions or errors, possibly including {@code
887     * ClassCastException}.
888     *
889 jsr166 1.1 * @return the number of tasks
890     */
891     public static int getQueuedTaskCount() {
892     return ((ForkJoinWorkerThread) Thread.currentThread())
893     .getQueueSize();
894     }
895    
896     /**
897     * Returns an estimate of how many more locally queued tasks are
898     * held by the current worker thread than there are other worker
899     * threads that might steal them. This value may be useful for
900     * heuristic decisions about whether to fork other tasks. In many
901     * usages of ForkJoinTasks, at steady state, each worker should
902     * aim to maintain a small constant surplus (for example, 3) of
903     * tasks, and to process computations locally if this threshold is
904     * exceeded.
905     *
906 jsr166 1.6 * <p>This method may be invoked only from within {@code
907 dl 1.38 * ForkJoinPool} computations (as may be determined using method
908 jsr166 1.6 * {@link #inForkJoinPool}). Attempts to invoke in other contexts
909     * result in exceptions or errors, possibly including {@code
910     * ClassCastException}.
911     *
912 jsr166 1.1 * @return the surplus number of tasks, which may be negative
913     */
914     public static int getSurplusQueuedTaskCount() {
915     return ((ForkJoinWorkerThread) Thread.currentThread())
916     .getEstimatedSurplusTaskCount();
917     }
918    
919     // Extension methods
920    
921     /**
922 jsr166 1.4 * Returns the result that would be returned by {@link #join}, even
923     * if this task completed abnormally, or {@code null} if this task
924     * is not known to have been completed. This method is designed
925     * to aid debugging, as well as to support extensions. Its use in
926     * any other context is discouraged.
927 jsr166 1.1 *
928 jsr166 1.4 * @return the result, or {@code null} if not completed
929 jsr166 1.1 */
930     public abstract V getRawResult();
931    
932     /**
933     * Forces the given value to be returned as a result. This method
934     * is designed to support extensions, and should not in general be
935     * called otherwise.
936     *
937     * @param value the value
938     */
939     protected abstract void setRawResult(V value);
940    
941     /**
942     * Immediately performs the base action of this task. This method
943     * is designed to support extensions, and should not in general be
944     * called otherwise. The return value controls whether this task
945     * is considered to be done normally. It may return false in
946     * asynchronous actions that require explicit invocations of
947 jsr166 1.8 * {@link #complete} to become joinable. It may also throw an
948     * (unchecked) exception to indicate abnormal exit.
949 jsr166 1.1 *
950 jsr166 1.4 * @return {@code true} if completed normally
951 jsr166 1.1 */
952     protected abstract boolean exec();
953    
954     /**
955 jsr166 1.5 * Returns, but does not unschedule or execute, a task queued by
956     * the current thread but not yet executed, if one is immediately
957 jsr166 1.1 * available. There is no guarantee that this task will actually
958 jsr166 1.5 * be polled or executed next. Conversely, this method may return
959     * null even if a task exists but cannot be accessed without
960     * contention with other threads. This method is designed
961     * primarily to support extensions, and is unlikely to be useful
962 jsr166 1.6 * otherwise.
963     *
964     * <p>This method may be invoked only from within {@code
965 dl 1.38 * ForkJoinPool} computations (as may be determined using method
966 jsr166 1.6 * {@link #inForkJoinPool}). Attempts to invoke in other contexts
967     * result in exceptions or errors, possibly including {@code
968     * ClassCastException}.
969 jsr166 1.1 *
970 jsr166 1.4 * @return the next task, or {@code null} if none are available
971 jsr166 1.1 */
972     protected static ForkJoinTask<?> peekNextLocalTask() {
973     return ((ForkJoinWorkerThread) Thread.currentThread())
974     .peekTask();
975     }
976    
977     /**
978     * Unschedules and returns, without executing, the next task
979     * queued by the current thread but not yet executed. This method
980     * is designed primarily to support extensions, and is unlikely to
981 jsr166 1.6 * be useful otherwise.
982     *
983     * <p>This method may be invoked only from within {@code
984 dl 1.38 * ForkJoinPool} computations (as may be determined using method
985 jsr166 1.6 * {@link #inForkJoinPool}). Attempts to invoke in other contexts
986     * result in exceptions or errors, possibly including {@code
987     * ClassCastException}.
988 jsr166 1.1 *
989 jsr166 1.4 * @return the next task, or {@code null} if none are available
990 jsr166 1.1 */
991     protected static ForkJoinTask<?> pollNextLocalTask() {
992     return ((ForkJoinWorkerThread) Thread.currentThread())
993     .pollLocalTask();
994     }
995    
996     /**
997     * Unschedules and returns, without executing, the next task
998     * queued by the current thread but not yet executed, if one is
999     * available, or if not available, a task that was forked by some
1000     * other thread, if available. Availability may be transient, so a
1001     * {@code null} result does not necessarily imply quiescence
1002     * of the pool this task is operating in. This method is designed
1003     * primarily to support extensions, and is unlikely to be useful
1004 jsr166 1.6 * otherwise.
1005     *
1006     * <p>This method may be invoked only from within {@code
1007 dl 1.38 * ForkJoinPool} computations (as may be determined using method
1008 jsr166 1.6 * {@link #inForkJoinPool}). Attempts to invoke in other contexts
1009     * result in exceptions or errors, possibly including {@code
1010     * ClassCastException}.
1011 jsr166 1.1 *
1012 jsr166 1.4 * @return a task, or {@code null} if none are available
1013 jsr166 1.1 */
1014     protected static ForkJoinTask<?> pollTask() {
1015     return ((ForkJoinWorkerThread) Thread.currentThread())
1016     .pollTask();
1017     }
1018    
1019 jsr166 1.5 /**
1020     * Adaptor for Runnables. This implements RunnableFuture
1021     * to be compliant with AbstractExecutorService constraints
1022     * when used in ForkJoinPool.
1023     */
1024     static final class AdaptedRunnable<T> extends ForkJoinTask<T>
1025     implements RunnableFuture<T> {
1026     final Runnable runnable;
1027     final T resultOnCompletion;
1028     T result;
1029     AdaptedRunnable(Runnable runnable, T result) {
1030     if (runnable == null) throw new NullPointerException();
1031     this.runnable = runnable;
1032     this.resultOnCompletion = result;
1033     }
1034     public T getRawResult() { return result; }
1035     public void setRawResult(T v) { result = v; }
1036     public boolean exec() {
1037     runnable.run();
1038     result = resultOnCompletion;
1039     return true;
1040     }
1041     public void run() { invoke(); }
1042     private static final long serialVersionUID = 5232453952276885070L;
1043     }
1044    
1045     /**
1046     * Adaptor for Callables
1047     */
1048     static final class AdaptedCallable<T> extends ForkJoinTask<T>
1049     implements RunnableFuture<T> {
1050 jsr166 1.6 final Callable<? extends T> callable;
1051 jsr166 1.5 T result;
1052 jsr166 1.6 AdaptedCallable(Callable<? extends T> callable) {
1053 jsr166 1.5 if (callable == null) throw new NullPointerException();
1054     this.callable = callable;
1055     }
1056     public T getRawResult() { return result; }
1057     public void setRawResult(T v) { result = v; }
1058     public boolean exec() {
1059     try {
1060     result = callable.call();
1061     return true;
1062     } catch (Error err) {
1063     throw err;
1064     } catch (RuntimeException rex) {
1065     throw rex;
1066     } catch (Exception ex) {
1067     throw new RuntimeException(ex);
1068     }
1069     }
1070     public void run() { invoke(); }
1071     private static final long serialVersionUID = 2838392045355241008L;
1072     }
1073 jsr166 1.2
1074     /**
1075 jsr166 1.6 * Returns a new {@code ForkJoinTask} that performs the {@code run}
1076     * method of the given {@code Runnable} as its action, and returns
1077     * a null result upon {@link #join}.
1078 jsr166 1.2 *
1079     * @param runnable the runnable action
1080     * @return the task
1081     */
1082 jsr166 1.6 public static ForkJoinTask<?> adapt(Runnable runnable) {
1083 jsr166 1.5 return new AdaptedRunnable<Void>(runnable, null);
1084 jsr166 1.2 }
1085    
1086     /**
1087 jsr166 1.6 * Returns a new {@code ForkJoinTask} that performs the {@code run}
1088     * method of the given {@code Runnable} as its action, and returns
1089     * the given result upon {@link #join}.
1090 jsr166 1.2 *
1091     * @param runnable the runnable action
1092     * @param result the result upon completion
1093     * @return the task
1094     */
1095     public static <T> ForkJoinTask<T> adapt(Runnable runnable, T result) {
1096 jsr166 1.5 return new AdaptedRunnable<T>(runnable, result);
1097 jsr166 1.2 }
1098    
1099     /**
1100 jsr166 1.6 * Returns a new {@code ForkJoinTask} that performs the {@code call}
1101     * method of the given {@code Callable} as its action, and returns
1102     * its result upon {@link #join}, translating any checked exceptions
1103     * encountered into {@code RuntimeException}.
1104 jsr166 1.2 *
1105     * @param callable the callable action
1106     * @return the task
1107     */
1108 jsr166 1.6 public static <T> ForkJoinTask<T> adapt(Callable<? extends T> callable) {
1109 jsr166 1.5 return new AdaptedCallable<T>(callable);
1110 jsr166 1.2 }
1111    
1112 jsr166 1.1 // Serialization support
1113    
1114     private static final long serialVersionUID = -7721805057305804111L;
1115    
1116     /**
1117 jsr166 1.21 * Saves the state to a stream (that is, serializes it).
1118 jsr166 1.1 *
1119     * @serialData the current run status and the exception thrown
1120 jsr166 1.4 * during execution, or {@code null} if none
1121 jsr166 1.1 * @param s the stream
1122     */
1123     private void writeObject(java.io.ObjectOutputStream s)
1124     throws java.io.IOException {
1125     s.defaultWriteObject();
1126     s.writeObject(getException());
1127     }
1128    
1129     /**
1130 jsr166 1.21 * Reconstitutes the instance from a stream (that is, deserializes it).
1131 jsr166 1.1 *
1132     * @param s the stream
1133     */
1134     private void readObject(java.io.ObjectInputStream s)
1135     throws java.io.IOException, ClassNotFoundException {
1136     s.defaultReadObject();
1137     Object ex = s.readObject();
1138     if (ex != null)
1139 dl 1.15 setExceptionalCompletion((Throwable) ex);
1140 jsr166 1.1 }
1141    
1142 jsr166 1.3 // Unsafe mechanics
1143 jsr166 1.1
1144 jsr166 1.3 private static final sun.misc.Unsafe UNSAFE = sun.misc.Unsafe.getUnsafe();
1145     private static final long statusOffset =
1146     objectFieldOffset("status", ForkJoinTask.class);
1147    
1148     private static long objectFieldOffset(String field, Class<?> klazz) {
1149 jsr166 1.1 try {
1150 jsr166 1.3 return UNSAFE.objectFieldOffset(klazz.getDeclaredField(field));
1151 jsr166 1.1 } catch (NoSuchFieldException e) {
1152 jsr166 1.3 // Convert Exception to corresponding Error
1153     NoSuchFieldError error = new NoSuchFieldError(field);
1154 jsr166 1.1 error.initCause(e);
1155     throw error;
1156     }
1157     }
1158     }