ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinTask.java
Revision: 1.24
Committed: Tue Sep 7 23:17:10 2010 UTC (13 years, 9 months ago) by jsr166
Branch: MAIN
Changes since 1.23: +1 -1 lines
Log Message:
trailing whitespace

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