ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinTask.java
Revision: 1.20
Committed: Thu Sep 2 11:31:22 2010 UTC (13 years, 9 months ago) by dl
Branch: MAIN
Changes since 1.19: +30 -22 lines
Log Message:
Incorporate review suggestions

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 dl 1.20 * 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 dl 1.13 * Record exception and set exceptional completion
207 dl 1.15 * @return status on exit
208 jsr166 1.1 */
209 dl 1.17 private void setExceptionalCompletion(Throwable rex) {
210 dl 1.13 exceptionMap.put(this, rex);
211 dl 1.17 setCompletion(EXCEPTIONAL);
212 jsr166 1.1 }
213    
214     /**
215 dl 1.19 * Blocks a worker thread until completion. Called only by
216     * pool. Currently unused -- pool-based waits use timeout
217     * version below.
218 jsr166 1.1 */
219 dl 1.17 final void internalAwaitDone() {
220     int s; // the odd construction reduces lock bias effects
221 dl 1.15 while ((s = status) >= 0) {
222 dl 1.17 try {
223     synchronized(this) {
224     if (UNSAFE.compareAndSwapInt(this, statusOffset, s,SIGNAL))
225     wait();
226 jsr166 1.1 }
227 dl 1.17 } catch (InterruptedException ie) {
228     cancelIfTerminating();
229 jsr166 1.1 }
230     }
231     }
232    
233     /**
234 dl 1.19 * Blocks a worker thread until completed or timed out. Called
235     * only by pool.
236     *
237     * @return status on exit
238     */
239     final int internalAwaitDone(long millis) {
240     int s;
241     if ((s = status) >= 0) {
242     try {
243     synchronized(this) {
244     if (UNSAFE.compareAndSwapInt(this, statusOffset, s,SIGNAL))
245     wait(millis, 0);
246     }
247     } catch (InterruptedException ie) {
248     cancelIfTerminating();
249     }
250     s = status;
251     }
252     return s;
253     }
254    
255     /**
256 dl 1.15 * Blocks a non-worker-thread until completion.
257 jsr166 1.1 */
258 dl 1.17 private void externalAwaitDone() {
259 dl 1.15 int s;
260     while ((s = status) >= 0) {
261     synchronized(this) {
262 dl 1.16 if (UNSAFE.compareAndSwapInt(this, statusOffset, s, SIGNAL)){
263 dl 1.15 boolean interrupted = false;
264 dl 1.17 while (status >= 0) {
265 dl 1.15 try {
266 dl 1.14 wait();
267 dl 1.15 } catch (InterruptedException ie) {
268     interrupted = true;
269 dl 1.13 }
270 dl 1.17 }
271 dl 1.15 if (interrupted)
272     Thread.currentThread().interrupt();
273     break;
274 dl 1.13 }
275 jsr166 1.1 }
276     }
277     }
278    
279     /**
280 dl 1.15 * Unless done, calls exec and records status if completed, but
281 dl 1.16 * doesn't wait for completion otherwise. Primary execution method
282     * for ForkJoinWorkerThread.
283 jsr166 1.1 */
284 dl 1.17 final void quietlyExec() {
285 dl 1.15 try {
286     if (status < 0 || !exec())
287     return;
288     } catch (Throwable rex) {
289     setExceptionalCompletion(rex);
290     return;
291 jsr166 1.1 }
292 dl 1.15 setCompletion(NORMAL); // must be outside try block
293 jsr166 1.1 }
294    
295     // public methods
296    
297     /**
298     * Arranges to asynchronously execute this task. While it is not
299     * necessarily enforced, it is a usage error to fork a task more
300 jsr166 1.6 * than once unless it has completed and been reinitialized.
301 jsr166 1.11 * Subsequent modifications to the state of this task or any data
302     * it operates on are not necessarily consistently observable by
303     * any thread other than the one executing it unless preceded by a
304     * call to {@link #join} or related methods, or a call to {@link
305     * #isDone} returning {@code true}.
306 jsr166 1.6 *
307     * <p>This method may be invoked only from within {@code
308     * ForkJoinTask} computations (as may be determined using method
309     * {@link #inForkJoinPool}). Attempts to invoke in other contexts
310     * result in exceptions or errors, possibly including {@code
311     * ClassCastException}.
312 jsr166 1.2 *
313 jsr166 1.6 * @return {@code this}, to simplify usage
314 jsr166 1.1 */
315 jsr166 1.2 public final ForkJoinTask<V> fork() {
316 jsr166 1.1 ((ForkJoinWorkerThread) Thread.currentThread())
317     .pushTask(this);
318 jsr166 1.2 return this;
319 jsr166 1.1 }
320    
321     /**
322 jsr166 1.10 * Returns the result of the computation when it {@link #isDone is done}.
323 jsr166 1.6 * This method differs from {@link #get()} in that
324     * abnormal completion results in {@code RuntimeException} or
325     * {@code Error}, not {@code ExecutionException}.
326 jsr166 1.1 *
327     * @return the computed result
328     */
329     public final V join() {
330 dl 1.17 quietlyJoin();
331     Throwable ex;
332     if (status < NORMAL && (ex = getException()) != null)
333     UNSAFE.throwException(ex);
334     return getRawResult();
335 jsr166 1.1 }
336    
337     /**
338     * Commences performing this task, awaits its completion if
339 jsr166 1.8 * necessary, and return its result, or throws an (unchecked)
340 dl 1.20 * {@code RuntimeException} or {@code Error} if the underlying
341     * computation did so.
342 jsr166 1.1 *
343     * @return the computed result
344     */
345     public final V invoke() {
346 dl 1.17 quietlyInvoke();
347     Throwable ex;
348     if (status < NORMAL && (ex = getException()) != null)
349     UNSAFE.throwException(ex);
350     return getRawResult();
351 jsr166 1.1 }
352    
353     /**
354 jsr166 1.8 * Forks the given tasks, returning when {@code isDone} holds for
355     * each task or an (unchecked) exception is encountered, in which
356 dl 1.20 * case the exception is rethrown. If more than one task
357     * encounters an exception, then this method throws any one of
358     * these exceptions. If any task encounters an exception, the
359     * other may be cancelled. However, the execution status of
360     * individual tasks is not guaranteed upon exceptional return. The
361     * status of each task may be obtained using {@link
362     * #getException()} and related methods to check if they have been
363     * cancelled, completed normally or exceptionally, or left
364     * unprocessed.
365 jsr166 1.6 *
366     * <p>This method may be invoked only from within {@code
367     * ForkJoinTask} computations (as may be determined using method
368     * {@link #inForkJoinPool}). Attempts to invoke in other contexts
369     * result in exceptions or errors, possibly including {@code
370     * ClassCastException}.
371     *
372     * @param t1 the first task
373     * @param t2 the second task
374     * @throws NullPointerException if any task is null
375 jsr166 1.1 */
376 jsr166 1.6 public static void invokeAll(ForkJoinTask<?> t1, ForkJoinTask<?> t2) {
377 jsr166 1.1 t2.fork();
378     t1.invoke();
379     t2.join();
380     }
381    
382     /**
383 jsr166 1.6 * Forks the given tasks, returning when {@code isDone} holds for
384 jsr166 1.8 * each task or an (unchecked) exception is encountered, in which
385 dl 1.20 * case the exception is rethrown. If more than one task
386     * encounters an exception, then this method throws any one of
387     * these exceptions. If any task encounters an exception, others
388     * may be cancelled. However, the execution status of individual
389     * tasks is not guaranteed upon exceptional return. The status of
390     * each task may be obtained using {@link #getException()} and
391     * related methods to check if they have been cancelled, completed
392     * normally or exceptionally, or left unprocessed.
393 jsr166 1.6 *
394     * <p>This method may be invoked only from within {@code
395     * ForkJoinTask} computations (as may be determined using method
396     * {@link #inForkJoinPool}). Attempts to invoke in other contexts
397     * result in exceptions or errors, possibly including {@code
398     * ClassCastException}.
399     *
400     * @param tasks the tasks
401 jsr166 1.8 * @throws NullPointerException if any task is null
402 jsr166 1.1 */
403     public static void invokeAll(ForkJoinTask<?>... tasks) {
404     Throwable ex = null;
405     int last = tasks.length - 1;
406     for (int i = last; i >= 0; --i) {
407     ForkJoinTask<?> t = tasks[i];
408     if (t == null) {
409     if (ex == null)
410     ex = new NullPointerException();
411     }
412     else if (i != 0)
413     t.fork();
414 dl 1.17 else {
415     t.quietlyInvoke();
416     if (ex == null && t.status < NORMAL)
417     ex = t.getException();
418     }
419 jsr166 1.1 }
420     for (int i = 1; i <= last; ++i) {
421     ForkJoinTask<?> t = tasks[i];
422     if (t != null) {
423     if (ex != null)
424     t.cancel(false);
425 dl 1.17 else {
426     t.quietlyJoin();
427     if (ex == null && t.status < NORMAL)
428     ex = t.getException();
429     }
430 jsr166 1.1 }
431     }
432     if (ex != null)
433 dl 1.13 UNSAFE.throwException(ex);
434 jsr166 1.1 }
435    
436     /**
437 jsr166 1.7 * Forks all tasks in the specified collection, returning when
438 jsr166 1.8 * {@code isDone} holds for each task or an (unchecked) exception
439 dl 1.20 * is encountered, in which case the exception is rethrown. If
440     * more than one task encounters an exception, then this method
441     * throws any one of these exceptions. If any task encounters an
442     * exception, others may be cancelled. However, the execution
443     * status of individual tasks is not guaranteed upon exceptional
444     * return. The status of each task may be obtained using {@link
445     * #getException()} and related methods to check if they have been
446     * cancelled, completed normally or exceptionally, or left
447     * unprocessed.
448 jsr166 1.6 *
449     * <p>This method may be invoked only from within {@code
450     * ForkJoinTask} computations (as may be determined using method
451     * {@link #inForkJoinPool}). Attempts to invoke in other contexts
452     * result in exceptions or errors, possibly including {@code
453     * ClassCastException}.
454 jsr166 1.1 *
455     * @param tasks the collection of tasks
456 jsr166 1.2 * @return the tasks argument, to simplify usage
457 jsr166 1.1 * @throws NullPointerException if tasks or any element are null
458     */
459 jsr166 1.2 public static <T extends ForkJoinTask<?>> Collection<T> invokeAll(Collection<T> tasks) {
460 jsr166 1.7 if (!(tasks instanceof RandomAccess) || !(tasks instanceof List<?>)) {
461 jsr166 1.1 invokeAll(tasks.toArray(new ForkJoinTask<?>[tasks.size()]));
462 jsr166 1.2 return tasks;
463 jsr166 1.1 }
464     @SuppressWarnings("unchecked")
465     List<? extends ForkJoinTask<?>> ts =
466     (List<? extends ForkJoinTask<?>>) tasks;
467     Throwable ex = null;
468     int last = ts.size() - 1;
469     for (int i = last; i >= 0; --i) {
470     ForkJoinTask<?> t = ts.get(i);
471     if (t == null) {
472     if (ex == null)
473     ex = new NullPointerException();
474     }
475     else if (i != 0)
476     t.fork();
477 dl 1.17 else {
478     t.quietlyInvoke();
479     if (ex == null && t.status < NORMAL)
480     ex = t.getException();
481     }
482 jsr166 1.1 }
483     for (int i = 1; i <= last; ++i) {
484     ForkJoinTask<?> t = ts.get(i);
485     if (t != null) {
486     if (ex != null)
487     t.cancel(false);
488 dl 1.17 else {
489     t.quietlyJoin();
490     if (ex == null && t.status < NORMAL)
491     ex = t.getException();
492     }
493 jsr166 1.1 }
494     }
495     if (ex != null)
496 dl 1.13 UNSAFE.throwException(ex);
497 jsr166 1.2 return tasks;
498 jsr166 1.1 }
499    
500     /**
501 jsr166 1.7 * Attempts to cancel execution of this task. This attempt will
502     * fail if the task has already completed, has already been
503     * cancelled, or could not be cancelled for some other reason. If
504     * successful, and this task has not started when cancel is
505     * called, execution of this task is suppressed, {@link
506     * #isCancelled} will report true, and {@link #join} will result
507     * in a {@code CancellationException} being thrown.
508 jsr166 1.1 *
509     * <p>This method may be overridden in subclasses, but if so, must
510     * still ensure that these minimal properties hold. In particular,
511 jsr166 1.6 * the {@code cancel} method itself must not throw exceptions.
512 jsr166 1.1 *
513 jsr166 1.6 * <p>This method is designed to be invoked by <em>other</em>
514 jsr166 1.1 * tasks. To terminate the current task, you can just return or
515     * throw an unchecked exception from its computation method, or
516 jsr166 1.4 * invoke {@link #completeExceptionally}.
517 jsr166 1.1 *
518     * @param mayInterruptIfRunning this value is ignored in the
519 jsr166 1.7 * default implementation because tasks are not
520 jsr166 1.1 * cancelled via interruption
521     *
522 jsr166 1.4 * @return {@code true} if this task is now cancelled
523 jsr166 1.1 */
524     public boolean cancel(boolean mayInterruptIfRunning) {
525     setCompletion(CANCELLED);
526 dl 1.16 return status == CANCELLED;
527 jsr166 1.1 }
528    
529 dl 1.13 /**
530 dl 1.17 * Cancels, ignoring any exceptions thrown by cancel. Used during
531     * worker and pool shutdown. Cancel is spec'ed not to throw any
532     * exceptions, but if it does anyway, we have no recourse during
533     * shutdown, so guard against this case.
534 dl 1.13 */
535     final void cancelIgnoringExceptions() {
536     try {
537     cancel(false);
538     } catch (Throwable ignore) {
539     }
540     }
541    
542     /**
543     * Cancels ignoring exceptions if worker is terminating
544     */
545 dl 1.17 final void cancelIfTerminating() {
546 dl 1.13 Thread t = Thread.currentThread();
547     if ((t instanceof ForkJoinWorkerThread) &&
548 dl 1.14 ((ForkJoinWorkerThread) t).isTerminating()) {
549 dl 1.13 try {
550     cancel(false);
551     } catch (Throwable ignore) {
552     }
553     }
554     }
555    
556 jsr166 1.8 public final boolean isDone() {
557     return status < 0;
558     }
559    
560     public final boolean isCancelled() {
561 dl 1.16 return status == CANCELLED;
562 jsr166 1.8 }
563    
564     /**
565 jsr166 1.4 * Returns {@code true} if this task threw an exception or was cancelled.
566 jsr166 1.1 *
567 jsr166 1.4 * @return {@code true} if this task threw an exception or was cancelled
568 jsr166 1.1 */
569     public final boolean isCompletedAbnormally() {
570 dl 1.16 return status < NORMAL;
571 jsr166 1.1 }
572    
573     /**
574 jsr166 1.8 * Returns {@code true} if this task completed without throwing an
575     * exception and was not cancelled.
576     *
577     * @return {@code true} if this task completed without throwing an
578     * exception and was not cancelled
579     */
580     public final boolean isCompletedNormally() {
581 dl 1.16 return status == NORMAL;
582 jsr166 1.8 }
583    
584     /**
585 jsr166 1.1 * Returns the exception thrown by the base computation, or a
586 jsr166 1.6 * {@code CancellationException} if cancelled, or {@code null} if
587     * none or if the method has not yet completed.
588 jsr166 1.1 *
589 jsr166 1.4 * @return the exception, or {@code null} if none
590 jsr166 1.1 */
591     public final Throwable getException() {
592 dl 1.16 int s = status;
593 jsr166 1.8 return ((s >= NORMAL) ? null :
594     (s == CANCELLED) ? new CancellationException() :
595     exceptionMap.get(this));
596 jsr166 1.1 }
597    
598     /**
599     * Completes this task abnormally, and if not already aborted or
600     * cancelled, causes it to throw the given exception upon
601     * {@code join} and related operations. This method may be used
602     * to induce exceptions in asynchronous tasks, or to force
603     * completion of tasks that would not otherwise complete. Its use
604 jsr166 1.6 * in other situations is discouraged. This method is
605 jsr166 1.1 * overridable, but overridden versions must invoke {@code super}
606     * implementation to maintain guarantees.
607     *
608 jsr166 1.11 * @param ex the exception to throw. If this exception is not a
609     * {@code RuntimeException} or {@code Error}, the actual exception
610     * thrown will be a {@code RuntimeException} with cause {@code ex}.
611 jsr166 1.1 */
612     public void completeExceptionally(Throwable ex) {
613 dl 1.15 setExceptionalCompletion((ex instanceof RuntimeException) ||
614     (ex instanceof Error) ? ex :
615     new RuntimeException(ex));
616 jsr166 1.1 }
617    
618     /**
619     * Completes this task, and if not already aborted or cancelled,
620     * returning a {@code null} result upon {@code join} and related
621     * operations. This method may be used to provide results for
622     * asynchronous tasks, or to provide alternative handling for
623     * tasks that would not otherwise complete normally. Its use in
624 jsr166 1.6 * other situations is discouraged. This method is
625 jsr166 1.1 * overridable, but overridden versions must invoke {@code super}
626     * implementation to maintain guarantees.
627     *
628     * @param value the result value for this task
629     */
630     public void complete(V value) {
631     try {
632     setRawResult(value);
633     } catch (Throwable rex) {
634 dl 1.15 setExceptionalCompletion(rex);
635 jsr166 1.1 return;
636     }
637 dl 1.13 setCompletion(NORMAL);
638 jsr166 1.1 }
639    
640     public final V get() throws InterruptedException, ExecutionException {
641 dl 1.17 quietlyJoin();
642 dl 1.15 if (Thread.interrupted())
643     throw new InterruptedException();
644 dl 1.17 int s = status;
645 dl 1.15 if (s < NORMAL) {
646     Throwable ex;
647     if (s == CANCELLED)
648     throw new CancellationException();
649     if (s == EXCEPTIONAL && (ex = exceptionMap.get(this)) != null)
650     throw new ExecutionException(ex);
651     }
652     return getRawResult();
653 jsr166 1.1 }
654 dl 1.14
655 jsr166 1.1 public final V get(long timeout, TimeUnit unit)
656     throws InterruptedException, ExecutionException, TimeoutException {
657 dl 1.13 Thread t = Thread.currentThread();
658 dl 1.15 ForkJoinPool pool;
659 dl 1.13 if (t instanceof ForkJoinWorkerThread) {
660     ForkJoinWorkerThread w = (ForkJoinWorkerThread) t;
661 dl 1.15 if (status >= 0 && w.unpushTask(this))
662 dl 1.17 quietlyExec();
663 dl 1.15 pool = w.pool;
664 dl 1.13 }
665     else
666 dl 1.15 pool = null;
667     /*
668 dl 1.17 * Timed wait loop intermixes cases for FJ (pool != null) and
669 dl 1.15 * non FJ threads. For FJ, decrement pool count but don't try
670     * for replacement; increment count on completion. For non-FJ,
671     * deal with interrupts. This is messy, but a little less so
672     * than is splitting the FJ and nonFJ cases.
673     */
674     boolean interrupted = false;
675     boolean dec = false; // true if pool count decremented
676 dl 1.18 long nanos = unit.toNanos(timeout);
677 dl 1.15 for (;;) {
678     if (Thread.interrupted() && pool == null) {
679     interrupted = true;
680     break;
681     }
682     int s = status;
683     if (s < 0)
684     break;
685 dl 1.17 if (UNSAFE.compareAndSwapInt(this, statusOffset, s, SIGNAL)) {
686 dl 1.15 long startTime = System.nanoTime();
687     long nt; // wait time
688     while (status >= 0 &&
689     (nt = nanos - (System.nanoTime() - startTime)) > 0) {
690     if (pool != null && !dec)
691     dec = pool.tryDecrementRunningCount();
692     else {
693     long ms = nt / 1000000;
694     int ns = (int) (nt % 1000000);
695     try {
696     synchronized(this) {
697     if (status >= 0)
698     wait(ms, ns);
699     }
700     } catch (InterruptedException ie) {
701     if (pool != null)
702     cancelIfTerminating();
703     else {
704     interrupted = true;
705     break;
706     }
707     }
708     }
709     }
710     break;
711     }
712     }
713     if (pool != null && dec)
714 dl 1.16 pool.incrementRunningCount();
715 dl 1.15 if (interrupted)
716     throw new InterruptedException();
717 dl 1.16 int es = status;
718 dl 1.15 if (es != NORMAL) {
719     Throwable ex;
720     if (es == CANCELLED)
721     throw new CancellationException();
722     if (es == EXCEPTIONAL && (ex = exceptionMap.get(this)) != null)
723     throw new ExecutionException(ex);
724     throw new TimeoutException();
725     }
726     return getRawResult();
727 jsr166 1.1 }
728    
729     /**
730 dl 1.17 * Joins this task, without returning its result or throwing its
731 jsr166 1.1 * exception. This method may be useful when processing
732     * collections of tasks when some have been cancelled or otherwise
733     * known to have aborted.
734     */
735     public final void quietlyJoin() {
736 dl 1.17 Thread t;
737     if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) {
738     ForkJoinWorkerThread w = (ForkJoinWorkerThread) t;
739     if (status >= 0) {
740     if (w.unpushTask(this)) {
741     boolean completed;
742     try {
743     completed = exec();
744     } catch (Throwable rex) {
745     setExceptionalCompletion(rex);
746     return;
747     }
748     if (completed) {
749     setCompletion(NORMAL);
750     return;
751     }
752     }
753     w.joinTask(this);
754     }
755     }
756     else
757     externalAwaitDone();
758 jsr166 1.1 }
759    
760     /**
761     * Commences performing this task and awaits its completion if
762 dl 1.17 * necessary, without returning its result or throwing its
763 jsr166 1.1 * exception. This method may be useful when processing
764     * collections of tasks when some have been cancelled or otherwise
765     * known to have aborted.
766     */
767     public final void quietlyInvoke() {
768 dl 1.17 if (status >= 0) {
769     boolean completed;
770     try {
771     completed = exec();
772     } catch (Throwable rex) {
773     setExceptionalCompletion(rex);
774     return;
775     }
776     if (completed)
777     setCompletion(NORMAL);
778     else
779     quietlyJoin();
780     }
781 jsr166 1.1 }
782    
783     /**
784     * Possibly executes tasks until the pool hosting the current task
785 jsr166 1.7 * {@link ForkJoinPool#isQuiescent is quiescent}. This method may
786     * be of use in designs in which many tasks are forked, but none
787     * are explicitly joined, instead executing them until all are
788     * processed.
789 jsr166 1.6 *
790     * <p>This method may be invoked only from within {@code
791     * ForkJoinTask} computations (as may be determined using method
792     * {@link #inForkJoinPool}). Attempts to invoke in other contexts
793     * result in exceptions or errors, possibly including {@code
794     * ClassCastException}.
795 jsr166 1.1 */
796     public static void helpQuiesce() {
797     ((ForkJoinWorkerThread) Thread.currentThread())
798     .helpQuiescePool();
799     }
800    
801     /**
802     * Resets the internal bookkeeping state of this task, allowing a
803     * subsequent {@code fork}. This method allows repeated reuse of
804     * this task, but only if reuse occurs when this task has either
805     * never been forked, or has been forked, then completed and all
806     * outstanding joins of this task have also completed. Effects
807 jsr166 1.6 * under any other usage conditions are not guaranteed.
808     * This method may be useful when executing
809 jsr166 1.1 * pre-constructed trees of subtasks in loops.
810     */
811     public void reinitialize() {
812 dl 1.16 if (status == EXCEPTIONAL)
813 jsr166 1.1 exceptionMap.remove(this);
814     status = 0;
815     }
816    
817     /**
818     * Returns the pool hosting the current task execution, or null
819     * if this task is executing outside of any ForkJoinPool.
820     *
821 jsr166 1.6 * @see #inForkJoinPool
822 jsr166 1.4 * @return the pool, or {@code null} if none
823 jsr166 1.1 */
824     public static ForkJoinPool getPool() {
825     Thread t = Thread.currentThread();
826     return (t instanceof ForkJoinWorkerThread) ?
827     ((ForkJoinWorkerThread) t).pool : null;
828     }
829    
830     /**
831     * Returns {@code true} if the current thread is executing as a
832     * ForkJoinPool computation.
833     *
834     * @return {@code true} if the current thread is executing as a
835     * ForkJoinPool computation, or false otherwise
836     */
837     public static boolean inForkJoinPool() {
838     return Thread.currentThread() instanceof ForkJoinWorkerThread;
839     }
840    
841     /**
842     * Tries to unschedule this task for execution. This method will
843     * typically succeed if this task is the most recently forked task
844     * by the current thread, and has not commenced executing in
845     * another thread. This method may be useful when arranging
846     * alternative local processing of tasks that could have been, but
847 jsr166 1.6 * were not, stolen.
848     *
849     * <p>This method may be invoked only from within {@code
850     * ForkJoinTask} computations (as may be determined using method
851     * {@link #inForkJoinPool}). Attempts to invoke in other contexts
852     * result in exceptions or errors, possibly including {@code
853     * ClassCastException}.
854 jsr166 1.1 *
855 jsr166 1.4 * @return {@code true} if unforked
856 jsr166 1.1 */
857     public boolean tryUnfork() {
858     return ((ForkJoinWorkerThread) Thread.currentThread())
859     .unpushTask(this);
860     }
861    
862     /**
863     * Returns an estimate of the number of tasks that have been
864     * forked by the current worker thread but not yet executed. This
865     * value may be useful for heuristic decisions about whether to
866     * fork other tasks.
867     *
868 jsr166 1.6 * <p>This method may be invoked only from within {@code
869     * ForkJoinTask} computations (as may be determined using method
870     * {@link #inForkJoinPool}). Attempts to invoke in other contexts
871     * result in exceptions or errors, possibly including {@code
872     * ClassCastException}.
873     *
874 jsr166 1.1 * @return the number of tasks
875     */
876     public static int getQueuedTaskCount() {
877     return ((ForkJoinWorkerThread) Thread.currentThread())
878     .getQueueSize();
879     }
880    
881     /**
882     * Returns an estimate of how many more locally queued tasks are
883     * held by the current worker thread than there are other worker
884     * threads that might steal them. This value may be useful for
885     * heuristic decisions about whether to fork other tasks. In many
886     * usages of ForkJoinTasks, at steady state, each worker should
887     * aim to maintain a small constant surplus (for example, 3) of
888     * tasks, and to process computations locally if this threshold is
889     * exceeded.
890     *
891 jsr166 1.6 * <p>This method may be invoked only from within {@code
892     * ForkJoinTask} computations (as may be determined using method
893     * {@link #inForkJoinPool}). Attempts to invoke in other contexts
894     * result in exceptions or errors, possibly including {@code
895     * ClassCastException}.
896     *
897 jsr166 1.1 * @return the surplus number of tasks, which may be negative
898     */
899     public static int getSurplusQueuedTaskCount() {
900     return ((ForkJoinWorkerThread) Thread.currentThread())
901     .getEstimatedSurplusTaskCount();
902     }
903    
904     // Extension methods
905    
906     /**
907 jsr166 1.4 * Returns the result that would be returned by {@link #join}, even
908     * if this task completed abnormally, or {@code null} if this task
909     * is not known to have been completed. This method is designed
910     * to aid debugging, as well as to support extensions. Its use in
911     * any other context is discouraged.
912 jsr166 1.1 *
913 jsr166 1.4 * @return the result, or {@code null} if not completed
914 jsr166 1.1 */
915     public abstract V getRawResult();
916    
917     /**
918     * Forces the given value to be returned as a result. This method
919     * is designed to support extensions, and should not in general be
920     * called otherwise.
921     *
922     * @param value the value
923     */
924     protected abstract void setRawResult(V value);
925    
926     /**
927     * Immediately performs the base action of this task. This method
928     * is designed to support extensions, and should not in general be
929     * called otherwise. The return value controls whether this task
930     * is considered to be done normally. It may return false in
931     * asynchronous actions that require explicit invocations of
932 jsr166 1.8 * {@link #complete} to become joinable. It may also throw an
933     * (unchecked) exception to indicate abnormal exit.
934 jsr166 1.1 *
935 jsr166 1.4 * @return {@code true} if completed normally
936 jsr166 1.1 */
937     protected abstract boolean exec();
938    
939     /**
940 jsr166 1.5 * Returns, but does not unschedule or execute, a task queued by
941     * the current thread but not yet executed, if one is immediately
942 jsr166 1.1 * available. There is no guarantee that this task will actually
943 jsr166 1.5 * be polled or executed next. Conversely, this method may return
944     * null even if a task exists but cannot be accessed without
945     * contention with other threads. This method is designed
946     * primarily to support extensions, and is unlikely to be useful
947 jsr166 1.6 * otherwise.
948     *
949     * <p>This method may be invoked only from within {@code
950     * ForkJoinTask} computations (as may be determined using method
951     * {@link #inForkJoinPool}). Attempts to invoke in other contexts
952     * result in exceptions or errors, possibly including {@code
953     * ClassCastException}.
954 jsr166 1.1 *
955 jsr166 1.4 * @return the next task, or {@code null} if none are available
956 jsr166 1.1 */
957     protected static ForkJoinTask<?> peekNextLocalTask() {
958     return ((ForkJoinWorkerThread) Thread.currentThread())
959     .peekTask();
960     }
961    
962     /**
963     * Unschedules and returns, without executing, the next task
964     * queued by the current thread but not yet executed. This method
965     * is designed primarily to support extensions, and is unlikely to
966 jsr166 1.6 * be useful otherwise.
967     *
968     * <p>This method may be invoked only from within {@code
969     * ForkJoinTask} computations (as may be determined using method
970     * {@link #inForkJoinPool}). Attempts to invoke in other contexts
971     * result in exceptions or errors, possibly including {@code
972     * ClassCastException}.
973 jsr166 1.1 *
974 jsr166 1.4 * @return the next task, or {@code null} if none are available
975 jsr166 1.1 */
976     protected static ForkJoinTask<?> pollNextLocalTask() {
977     return ((ForkJoinWorkerThread) Thread.currentThread())
978     .pollLocalTask();
979     }
980    
981     /**
982     * Unschedules and returns, without executing, the next task
983     * queued by the current thread but not yet executed, if one is
984     * available, or if not available, a task that was forked by some
985     * other thread, if available. Availability may be transient, so a
986     * {@code null} result does not necessarily imply quiescence
987     * of the pool this task is operating in. This method is designed
988     * primarily to support extensions, and is unlikely to be useful
989 jsr166 1.6 * otherwise.
990     *
991     * <p>This method may be invoked only from within {@code
992     * ForkJoinTask} computations (as may be determined using method
993     * {@link #inForkJoinPool}). Attempts to invoke in other contexts
994     * result in exceptions or errors, possibly including {@code
995     * ClassCastException}.
996 jsr166 1.1 *
997 jsr166 1.4 * @return a task, or {@code null} if none are available
998 jsr166 1.1 */
999     protected static ForkJoinTask<?> pollTask() {
1000     return ((ForkJoinWorkerThread) Thread.currentThread())
1001     .pollTask();
1002     }
1003    
1004 jsr166 1.5 /**
1005     * Adaptor for Runnables. This implements RunnableFuture
1006     * to be compliant with AbstractExecutorService constraints
1007     * when used in ForkJoinPool.
1008     */
1009     static final class AdaptedRunnable<T> extends ForkJoinTask<T>
1010     implements RunnableFuture<T> {
1011     final Runnable runnable;
1012     final T resultOnCompletion;
1013     T result;
1014     AdaptedRunnable(Runnable runnable, T result) {
1015     if (runnable == null) throw new NullPointerException();
1016     this.runnable = runnable;
1017     this.resultOnCompletion = result;
1018     }
1019     public T getRawResult() { return result; }
1020     public void setRawResult(T v) { result = v; }
1021     public boolean exec() {
1022     runnable.run();
1023     result = resultOnCompletion;
1024     return true;
1025     }
1026     public void run() { invoke(); }
1027     private static final long serialVersionUID = 5232453952276885070L;
1028     }
1029    
1030     /**
1031     * Adaptor for Callables
1032     */
1033     static final class AdaptedCallable<T> extends ForkJoinTask<T>
1034     implements RunnableFuture<T> {
1035 jsr166 1.6 final Callable<? extends T> callable;
1036 jsr166 1.5 T result;
1037 jsr166 1.6 AdaptedCallable(Callable<? extends T> callable) {
1038 jsr166 1.5 if (callable == null) throw new NullPointerException();
1039     this.callable = callable;
1040     }
1041     public T getRawResult() { return result; }
1042     public void setRawResult(T v) { result = v; }
1043     public boolean exec() {
1044     try {
1045     result = callable.call();
1046     return true;
1047     } catch (Error err) {
1048     throw err;
1049     } catch (RuntimeException rex) {
1050     throw rex;
1051     } catch (Exception ex) {
1052     throw new RuntimeException(ex);
1053     }
1054     }
1055     public void run() { invoke(); }
1056     private static final long serialVersionUID = 2838392045355241008L;
1057     }
1058 jsr166 1.2
1059     /**
1060 jsr166 1.6 * Returns a new {@code ForkJoinTask} that performs the {@code run}
1061     * method of the given {@code Runnable} as its action, and returns
1062     * a null result upon {@link #join}.
1063 jsr166 1.2 *
1064     * @param runnable the runnable action
1065     * @return the task
1066     */
1067 jsr166 1.6 public static ForkJoinTask<?> adapt(Runnable runnable) {
1068 jsr166 1.5 return new AdaptedRunnable<Void>(runnable, null);
1069 jsr166 1.2 }
1070    
1071     /**
1072 jsr166 1.6 * Returns a new {@code ForkJoinTask} that performs the {@code run}
1073     * method of the given {@code Runnable} as its action, and returns
1074     * the given result upon {@link #join}.
1075 jsr166 1.2 *
1076     * @param runnable the runnable action
1077     * @param result the result upon completion
1078     * @return the task
1079     */
1080     public static <T> ForkJoinTask<T> adapt(Runnable runnable, T result) {
1081 jsr166 1.5 return new AdaptedRunnable<T>(runnable, result);
1082 jsr166 1.2 }
1083    
1084     /**
1085 jsr166 1.6 * Returns a new {@code ForkJoinTask} that performs the {@code call}
1086     * method of the given {@code Callable} as its action, and returns
1087     * its result upon {@link #join}, translating any checked exceptions
1088     * encountered into {@code RuntimeException}.
1089 jsr166 1.2 *
1090     * @param callable the callable action
1091     * @return the task
1092     */
1093 jsr166 1.6 public static <T> ForkJoinTask<T> adapt(Callable<? extends T> callable) {
1094 jsr166 1.5 return new AdaptedCallable<T>(callable);
1095 jsr166 1.2 }
1096    
1097 jsr166 1.1 // Serialization support
1098    
1099     private static final long serialVersionUID = -7721805057305804111L;
1100    
1101     /**
1102 jsr166 1.12 * Saves the state to a stream.
1103 jsr166 1.1 *
1104     * @serialData the current run status and the exception thrown
1105 jsr166 1.4 * during execution, or {@code null} if none
1106 jsr166 1.1 * @param s the stream
1107     */
1108     private void writeObject(java.io.ObjectOutputStream s)
1109     throws java.io.IOException {
1110     s.defaultWriteObject();
1111     s.writeObject(getException());
1112     }
1113    
1114     /**
1115 jsr166 1.12 * Reconstitutes the instance from a stream.
1116 jsr166 1.1 *
1117     * @param s the stream
1118     */
1119     private void readObject(java.io.ObjectInputStream s)
1120     throws java.io.IOException, ClassNotFoundException {
1121     s.defaultReadObject();
1122     Object ex = s.readObject();
1123     if (ex != null)
1124 dl 1.15 setExceptionalCompletion((Throwable) ex);
1125 jsr166 1.1 }
1126    
1127 jsr166 1.3 // Unsafe mechanics
1128 jsr166 1.1
1129 jsr166 1.3 private static final sun.misc.Unsafe UNSAFE = sun.misc.Unsafe.getUnsafe();
1130     private static final long statusOffset =
1131     objectFieldOffset("status", ForkJoinTask.class);
1132    
1133     private static long objectFieldOffset(String field, Class<?> klazz) {
1134 jsr166 1.1 try {
1135 jsr166 1.3 return UNSAFE.objectFieldOffset(klazz.getDeclaredField(field));
1136 jsr166 1.1 } catch (NoSuchFieldException e) {
1137 jsr166 1.3 // Convert Exception to corresponding Error
1138     NoSuchFieldError error = new NoSuchFieldError(field);
1139 jsr166 1.1 error.initCause(e);
1140     throw error;
1141     }
1142     }
1143     }