2 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 * This code is free software; you can redistribute it and/or modify it
5 * under the terms of the GNU General Public License version 2 only, as
6 * published by the Free Software Foundation. Oracle designates this
7 * particular file as subject to the "Classpath" exception as provided
8 * by Oracle in the LICENSE file that accompanied this code.
10 * This code is distributed in the hope that it will be useful, but WITHOUT
11 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
13 * version 2 for more details (a copy is included in the LICENSE file that
14 * accompanied this code).
16 * You should have received a copy of the GNU General Public License version
17 * 2 along with this work; if not, write to the Free Software Foundation,
18 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
21 * or visit www.oracle.com if you need additional information or have any
26 * This file is available under and governed by the GNU General Public
27 * License version 2 only, as published by the Free Software Foundation.
28 * However, the following notice accompanied the original version of this
31 * Written by Doug Lea with assistance from members of JCP JSR-166
32 * Expert Group and released to the public domain, as explained at
33 * http://creativecommons.org/publicdomain/zero/1.0/
36 package java.util.concurrent;
38 import java.io.Serializable;
39 import java.util.Collection;
40 import java.util.Collections;
41 import java.util.List;
42 import java.util.RandomAccess;
44 import java.lang.ref.WeakReference;
45 import java.lang.ref.ReferenceQueue;
46 import java.util.concurrent.Callable;
47 import java.util.concurrent.CancellationException;
48 import java.util.concurrent.ExecutionException;
49 import java.util.concurrent.Executor;
50 import java.util.concurrent.ExecutorService;
51 import java.util.concurrent.Future;
52 import java.util.concurrent.RejectedExecutionException;
53 import java.util.concurrent.RunnableFuture;
54 import java.util.concurrent.TimeUnit;
55 import java.util.concurrent.TimeoutException;
56 import java.util.concurrent.locks.ReentrantLock;
57 import java.lang.reflect.Constructor;
60 * Abstract base class for tasks that run within a {@link ForkJoinPool}.
61 * A {@code ForkJoinTask} is a thread-like entity that is much
62 * lighter weight than a normal thread. Huge numbers of tasks and
63 * subtasks may be hosted by a small number of actual threads in a
64 * ForkJoinPool, at the price of some usage limitations.
66 * <p>A "main" {@code ForkJoinTask} begins execution when submitted
67 * to a {@link ForkJoinPool}. Once started, it will usually in turn
68 * start other subtasks. As indicated by the name of this class,
69 * many programs using {@code ForkJoinTask} employ only methods
70 * {@link #fork} and {@link #join}, or derivatives such as {@link
71 * #invokeAll(ForkJoinTask...) invokeAll}. However, this class also
72 * provides a number of other methods that can come into play in
73 * advanced usages, as well as extension mechanics that allow
74 * support of new forms of fork/join processing.
76 * <p>A {@code ForkJoinTask} is a lightweight form of {@link Future}.
77 * The efficiency of {@code ForkJoinTask}s stems from a set of
78 * restrictions (that are only partially statically enforceable)
79 * reflecting their intended use as computational tasks calculating
80 * pure functions or operating on purely isolated objects. The
81 * primary coordination mechanisms are {@link #fork}, that arranges
82 * asynchronous execution, and {@link #join}, that doesn't proceed
83 * until the task's result has been computed. Computations should
84 * avoid {@code synchronized} methods or blocks, and should minimize
85 * other blocking synchronization apart from joining other tasks or
86 * using synchronizers such as Phasers that are advertised to
87 * cooperate with fork/join scheduling. Tasks should also not perform
88 * blocking IO, and should ideally access variables that are
89 * completely independent of those accessed by other running
90 * tasks. Minor breaches of these restrictions, for example using
91 * shared output streams, may be tolerable in practice, but frequent
92 * use may result in poor performance, and the potential to
93 * indefinitely stall if the number of threads not waiting for IO or
94 * other external synchronization becomes exhausted. This usage
95 * restriction is in part enforced by not permitting checked
96 * exceptions such as {@code IOExceptions} to be thrown. However,
97 * computations may still encounter unchecked exceptions, that are
98 * rethrown to callers attempting to join them. These exceptions may
99 * additionally include {@link RejectedExecutionException} stemming
100 * from internal resource exhaustion, such as failure to allocate
101 * internal task queues. Rethrown exceptions behave in the same way as
102 * regular exceptions, but, when possible, contain stack traces (as
103 * displayed for example using {@code ex.printStackTrace()}) of both
104 * the thread that initiated the computation as well as the thread
105 * actually encountering the exception; minimally only the latter.
107 * <p>The primary method for awaiting completion and extracting
108 * results of a task is {@link #join}, but there are several variants:
109 * The {@link Future#get} methods support interruptible and/or timed
110 * waits for completion and report results using {@code Future}
111 * conventions. Method {@link #invoke} is semantically
112 * equivalent to {@code fork(); join()} but always attempts to begin
113 * execution in the current thread. The "<em>quiet</em>" forms of
114 * these methods do not extract results or report exceptions. These
115 * may be useful when a set of tasks are being executed, and you need
116 * to delay processing of results or exceptions until all complete.
117 * Method {@code invokeAll} (available in multiple versions)
118 * performs the most common form of parallel invocation: forking a set
119 * of tasks and joining them all.
121 * <p>The execution status of tasks may be queried at several levels
122 * of detail: {@link #isDone} is true if a task completed in any way
123 * (including the case where a task was cancelled without executing);
124 * {@link #isCompletedNormally} is true if a task completed without
125 * cancellation or encountering an exception; {@link #isCancelled} is
126 * true if the task was cancelled (in which case {@link #getException}
127 * returns a {@link java.util.concurrent.CancellationException}); and
128 * {@link #isCompletedAbnormally} is true if a task was either
129 * cancelled or encountered an exception, in which case {@link
130 * #getException} will return either the encountered exception or
131 * {@link java.util.concurrent.CancellationException}.
133 * <p>The ForkJoinTask class is not usually directly subclassed.
134 * Instead, you subclass one of the abstract classes that support a
135 * particular style of fork/join processing, typically {@link
136 * RecursiveAction} for computations that do not return results, or
137 * {@link RecursiveTask} for those that do. Normally, a concrete
138 * ForkJoinTask subclass declares fields comprising its parameters,
139 * established in a constructor, and then defines a {@code compute}
140 * method that somehow uses the control methods supplied by this base
141 * class. While these methods have {@code public} access (to allow
142 * instances of different task subclasses to call each other's
143 * methods), some of them may only be called from within other
144 * ForkJoinTasks (as may be determined using method {@link
145 * #inForkJoinPool}). Attempts to invoke them in other contexts
146 * result in exceptions or errors, possibly including
147 * {@code ClassCastException}.
149 * <p>Method {@link #join} and its variants are appropriate for use
150 * only when completion dependencies are acyclic; that is, the
151 * parallel computation can be described as a directed acyclic graph
152 * (DAG). Otherwise, executions may encounter a form of deadlock as
153 * tasks cyclically wait for each other. However, this framework
154 * supports other methods and techniques (for example the use of
155 * {@link Phaser}, {@link #helpQuiesce}, and {@link #complete}) that
156 * may be of use in constructing custom subclasses for problems that
157 * are not statically structured as DAGs.
159 * <p>Most base support methods are {@code final}, to prevent
160 * overriding of implementations that are intrinsically tied to the
161 * underlying lightweight task scheduling framework. Developers
162 * creating new basic styles of fork/join processing should minimally
163 * implement {@code protected} methods {@link #exec}, {@link
164 * #setRawResult}, and {@link #getRawResult}, while also introducing
165 * an abstract computational method that can be implemented in its
166 * subclasses, possibly relying on other {@code protected} methods
167 * provided by this class.
169 * <p>ForkJoinTasks should perform relatively small amounts of
170 * computation. Large tasks should be split into smaller subtasks,
171 * usually via recursive decomposition. As a very rough rule of thumb,
172 * a task should perform more than 100 and less than 10000 basic
173 * computational steps, and should avoid indefinite looping. If tasks
174 * are too big, then parallelism cannot improve throughput. If too
175 * small, then memory and internal task maintenance overhead may
176 * overwhelm processing.
178 * <p>This class provides {@code adapt} methods for {@link Runnable}
179 * and {@link Callable}, that may be of use when mixing execution of
180 * {@code ForkJoinTasks} with other kinds of tasks. When all tasks are
181 * of this form, consider using a pool constructed in <em>asyncMode</em>.
183 * <p>ForkJoinTasks are {@code Serializable}, which enables them to be
184 * used in extensions such as remote execution frameworks. It is
185 * sensible to serialize tasks only before or after, but not during,
186 * execution. Serialization is not relied on during execution itself.
191 public abstract class ForkJoinTask<V> implements Future<V>, Serializable {
194 * See the internal documentation of class ForkJoinPool for a
195 * general implementation overview. ForkJoinTasks are mainly
196 * responsible for maintaining their "status" field amidst relays
197 * to methods in ForkJoinWorkerThread and ForkJoinPool. The
198 * methods of this class are more-or-less layered into (1) basic
199 * status maintenance (2) execution and awaiting completion (3)
200 * user-level methods that additionally report results. This is
201 * sometimes hard to see because this file orders exported methods
202 * in a way that flows well in javadocs.
206 * The status field holds run control status bits packed into a
207 * single int to minimize footprint and to ensure atomicity (via
208 * CAS). Status is initially zero, and takes on nonnegative
209 * values until completed, upon which status holds value
210 * NORMAL, CANCELLED, or EXCEPTIONAL. Tasks undergoing blocking
211 * waits by other threads have the SIGNAL bit set. Completion of
212 * a stolen task with SIGNAL set awakens any waiters via
213 * notifyAll. Even though suboptimal for some purposes, we use
214 * basic builtin wait/notify to take advantage of "monitor
215 * inflation" in JVMs that we would otherwise need to emulate to
216 * avoid adding further per-task bookkeeping overhead. We want
217 * these monitors to be "fat", i.e., not use biasing or thin-lock
218 * techniques, so use some odd coding idioms that tend to avoid
222 /** The run status of this task */
223 volatile int status; // accessed directly by pool and workers
224 private static final int NORMAL = -1;
225 private static final int CANCELLED = -2;
226 private static final int EXCEPTIONAL = -3;
227 private static final int SIGNAL = 1;
230 * Marks completion and wakes up threads waiting to join this task,
231 * also clearing signal request bits.
233 * @param completion one of NORMAL, CANCELLED, EXCEPTIONAL
234 * @return completion status on exit
236 private int setCompletion(int completion) {
238 if ((s = status) < 0)
240 if (UNSAFE.compareAndSwapInt(this, statusOffset, s, completion)) {
242 synchronized (this) { notifyAll(); }
249 * Tries to block a worker thread until completed or timed out.
250 * Uses Object.wait time argument conventions.
251 * May fail on contention or interrupt.
253 * @param millis if > 0, wait time.
255 final void tryAwaitDone(long millis) {
258 if (((s = status) > 0 ||
260 UNSAFE.compareAndSwapInt(this, statusOffset, 0, SIGNAL))) &&
262 synchronized (this) {
267 } catch (InterruptedException ie) {
268 // caller must check termination
273 * Blocks a non-worker-thread until completion.
274 * @return status upon completion
276 private int externalAwaitDone() {
278 if ((s = status) >= 0) {
279 boolean interrupted = false;
280 synchronized (this) {
281 while ((s = status) >= 0) {
283 UNSAFE.compareAndSwapInt(this, statusOffset,
288 } catch (InterruptedException ie) {
295 Thread.currentThread().interrupt();
301 * Blocks a non-worker-thread until completion or interruption or timeout.
303 private int externalInterruptibleAwaitDone(long millis)
304 throws InterruptedException {
306 if (Thread.interrupted())
307 throw new InterruptedException();
308 if ((s = status) >= 0) {
309 synchronized (this) {
310 while ((s = status) >= 0) {
312 UNSAFE.compareAndSwapInt(this, statusOffset,
326 * Primary execution method for stolen tasks. Unless done, calls
327 * exec and records status if completed, but doesn't wait for
328 * completion otherwise.
330 final void doExec() {
335 } catch (Throwable rex) {
336 setExceptionalCompletion(rex);
340 setCompletion(NORMAL); // must be outside try block
345 * Primary mechanics for join, get, quietlyJoin.
346 * @return status upon completion
348 private int doJoin() {
349 Thread t; ForkJoinWorkerThread w; int s; boolean completed;
350 if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) {
351 if ((s = status) < 0)
353 if ((w = (ForkJoinWorkerThread)t).unpushTask(this)) {
356 } catch (Throwable rex) {
357 return setExceptionalCompletion(rex);
360 return setCompletion(NORMAL);
362 return w.joinTask(this);
365 return externalAwaitDone();
369 * Primary mechanics for invoke, quietlyInvoke.
370 * @return status upon completion
372 private int doInvoke() {
373 int s; boolean completed;
374 if ((s = status) < 0)
378 } catch (Throwable rex) {
379 return setExceptionalCompletion(rex);
382 return setCompletion(NORMAL);
387 // Exception table support
390 * Table of exceptions thrown by tasks, to enable reporting by
391 * callers. Because exceptions are rare, we don't directly keep
392 * them with task objects, but instead use a weak ref table. Note
393 * that cancellation exceptions don't appear in the table, but are
394 * instead recorded as status values.
396 * Note: These statics are initialized below in static block.
398 private static final ExceptionNode[] exceptionTable;
399 private static final ReentrantLock exceptionTableLock;
400 private static final ReferenceQueue<Object> exceptionTableRefQueue;
403 * Fixed capacity for exceptionTable.
405 private static final int EXCEPTION_MAP_CAPACITY = 32;
408 * Key-value nodes for exception table. The chained hash table
409 * uses identity comparisons, full locking, and weak references
410 * for keys. The table has a fixed capacity because it only
411 * maintains task exceptions long enough for joiners to access
412 * them, so should never become very large for sustained
413 * periods. However, since we do not know when the last joiner
414 * completes, we must use weak references and expunge them. We do
415 * so on each operation (hence full locking). Also, some thread in
416 * any ForkJoinPool will call helpExpungeStaleExceptions when its
417 * pool becomes isQuiescent.
419 static final class ExceptionNode extends WeakReference<ForkJoinTask<?>>{
422 final long thrower; // use id not ref to avoid weak cycles
423 ExceptionNode(ForkJoinTask<?> task, Throwable ex, ExceptionNode next) {
424 super(task, exceptionTableRefQueue);
427 this.thrower = Thread.currentThread().getId();
432 * Records exception and sets exceptional completion.
434 * @return status on exit
436 private int setExceptionalCompletion(Throwable ex) {
437 int h = System.identityHashCode(this);
438 final ReentrantLock lock = exceptionTableLock;
441 expungeStaleExceptions();
442 ExceptionNode[] t = exceptionTable;
443 int i = h & (t.length - 1);
444 for (ExceptionNode e = t[i]; ; e = e.next) {
446 t[i] = new ExceptionNode(this, ex, t[i]);
449 if (e.get() == this) // already present
455 return setCompletion(EXCEPTIONAL);
459 * Removes exception node and clears status
461 private void clearExceptionalCompletion() {
462 int h = System.identityHashCode(this);
463 final ReentrantLock lock = exceptionTableLock;
466 ExceptionNode[] t = exceptionTable;
467 int i = h & (t.length - 1);
468 ExceptionNode e = t[i];
469 ExceptionNode pred = null;
471 ExceptionNode next = e.next;
472 if (e.get() == this) {
482 expungeStaleExceptions();
490 * Returns a rethrowable exception for the given task, if
491 * available. To provide accurate stack traces, if the exception
492 * was not thrown by the current thread, we try to create a new
493 * exception of the same type as the one thrown, but with the
494 * recorded exception as its cause. If there is no such
495 * constructor, we instead try to use a no-arg constructor,
496 * followed by initCause, to the same effect. If none of these
497 * apply, or any fail due to other exceptions, we return the
498 * recorded exception, which is still correct, although it may
499 * contain a misleading stack trace.
501 * @return the exception, or null if none
503 private Throwable getThrowableException() {
504 if (status != EXCEPTIONAL)
506 int h = System.identityHashCode(this);
508 final ReentrantLock lock = exceptionTableLock;
511 expungeStaleExceptions();
512 ExceptionNode[] t = exceptionTable;
513 e = t[h & (t.length - 1)];
514 while (e != null && e.get() != this)
520 if (e == null || (ex = e.ex) == null)
522 if (e.thrower != Thread.currentThread().getId()) {
523 Class ec = ex.getClass();
525 Constructor<?> noArgCtor = null;
526 Constructor<?>[] cs = ec.getConstructors();// public ctors only
527 for (int i = 0; i < cs.length; ++i) {
528 Constructor<?> c = cs[i];
529 Class<?>[] ps = c.getParameterTypes();
532 else if (ps.length == 1 && ps[0] == Throwable.class)
533 return (Throwable)(c.newInstance(ex));
535 if (noArgCtor != null) {
536 Throwable wx = (Throwable)(noArgCtor.newInstance());
540 } catch (Exception ignore) {
547 * Poll stale refs and remove them. Call only while holding lock.
549 private static void expungeStaleExceptions() {
550 for (Object x; (x = exceptionTableRefQueue.poll()) != null;) {
551 if (x instanceof ExceptionNode) {
552 ForkJoinTask<?> key = ((ExceptionNode)x).get();
553 ExceptionNode[] t = exceptionTable;
554 int i = System.identityHashCode(key) & (t.length - 1);
555 ExceptionNode e = t[i];
556 ExceptionNode pred = null;
558 ExceptionNode next = e.next;
574 * If lock is available, poll stale refs and remove them.
575 * Called from ForkJoinPool when pools become quiescent.
577 static final void helpExpungeStaleExceptions() {
578 final ReentrantLock lock = exceptionTableLock;
579 if (lock.tryLock()) {
581 expungeStaleExceptions();
589 * Report the result of invoke or join; called only upon
590 * non-normal return of internal versions.
592 private V reportResult() {
594 if ((s = status) == CANCELLED)
595 throw new CancellationException();
596 if (s == EXCEPTIONAL && (ex = getThrowableException()) != null)
597 UNSAFE.throwException(ex);
598 return getRawResult();
604 * Arranges to asynchronously execute this task. While it is not
605 * necessarily enforced, it is a usage error to fork a task more
606 * than once unless it has completed and been reinitialized.
607 * Subsequent modifications to the state of this task or any data
608 * it operates on are not necessarily consistently observable by
609 * any thread other than the one executing it unless preceded by a
610 * call to {@link #join} or related methods, or a call to {@link
611 * #isDone} returning {@code true}.
613 * <p>This method may be invoked only from within {@code
614 * ForkJoinPool} computations (as may be determined using method
615 * {@link #inForkJoinPool}). Attempts to invoke in other contexts
616 * result in exceptions or errors, possibly including {@code
617 * ClassCastException}.
619 * @return {@code this}, to simplify usage
621 public final ForkJoinTask<V> fork() {
622 ((ForkJoinWorkerThread) Thread.currentThread())
628 * Returns the result of the computation when it {@link #isDone is
629 * done}. This method differs from {@link #get()} in that
630 * abnormal completion results in {@code RuntimeException} or
631 * {@code Error}, not {@code ExecutionException}, and that
632 * interrupts of the calling thread do <em>not</em> cause the
633 * method to abruptly return by throwing {@code
634 * InterruptedException}.
636 * @return the computed result
638 public final V join() {
639 if (doJoin() != NORMAL)
640 return reportResult();
642 return getRawResult();
646 * Commences performing this task, awaits its completion if
647 * necessary, and returns its result, or throws an (unchecked)
648 * {@code RuntimeException} or {@code Error} if the underlying
649 * computation did so.
651 * @return the computed result
653 public final V invoke() {
654 if (doInvoke() != NORMAL)
655 return reportResult();
657 return getRawResult();
661 * Forks the given tasks, returning when {@code isDone} holds for
662 * each task or an (unchecked) exception is encountered, in which
663 * case the exception is rethrown. If more than one task
664 * encounters an exception, then this method throws any one of
665 * these exceptions. If any task encounters an exception, the
666 * other may be cancelled. However, the execution status of
667 * individual tasks is not guaranteed upon exceptional return. The
668 * status of each task may be obtained using {@link
669 * #getException()} and related methods to check if they have been
670 * cancelled, completed normally or exceptionally, or left
673 * <p>This method may be invoked only from within {@code
674 * ForkJoinPool} computations (as may be determined using method
675 * {@link #inForkJoinPool}). Attempts to invoke in other contexts
676 * result in exceptions or errors, possibly including {@code
677 * ClassCastException}.
679 * @param t1 the first task
680 * @param t2 the second task
681 * @throws NullPointerException if any task is null
683 public static void invokeAll(ForkJoinTask<?> t1, ForkJoinTask<?> t2) {
690 * Forks the given tasks, returning when {@code isDone} holds for
691 * each task or an (unchecked) exception is encountered, in which
692 * case the exception is rethrown. If more than one task
693 * encounters an exception, then this method throws any one of
694 * these exceptions. If any task encounters an exception, others
695 * may be cancelled. However, the execution status of individual
696 * tasks is not guaranteed upon exceptional return. The status of
697 * each task may be obtained using {@link #getException()} and
698 * related methods to check if they have been cancelled, completed
699 * normally or exceptionally, or left unprocessed.
701 * <p>This method may be invoked only from within {@code
702 * ForkJoinPool} computations (as may be determined using method
703 * {@link #inForkJoinPool}). Attempts to invoke in other contexts
704 * result in exceptions or errors, possibly including {@code
705 * ClassCastException}.
707 * @param tasks the tasks
708 * @throws NullPointerException if any task is null
710 public static void invokeAll(ForkJoinTask<?>... tasks) {
712 int last = tasks.length - 1;
713 for (int i = last; i >= 0; --i) {
714 ForkJoinTask<?> t = tasks[i];
717 ex = new NullPointerException();
721 else if (t.doInvoke() < NORMAL && ex == null)
722 ex = t.getException();
724 for (int i = 1; i <= last; ++i) {
725 ForkJoinTask<?> t = tasks[i];
729 else if (t.doJoin() < NORMAL && ex == null)
730 ex = t.getException();
734 UNSAFE.throwException(ex);
738 * Forks all tasks in the specified collection, returning when
739 * {@code isDone} holds for each task or an (unchecked) exception
740 * is encountered, in which case the exception is rethrown. If
741 * more than one task encounters an exception, then this method
742 * throws any one of these exceptions. If any task encounters an
743 * exception, others may be cancelled. However, the execution
744 * status of individual tasks is not guaranteed upon exceptional
745 * return. The status of each task may be obtained using {@link
746 * #getException()} and related methods to check if they have been
747 * cancelled, completed normally or exceptionally, or left
750 * <p>This method may be invoked only from within {@code
751 * ForkJoinPool} computations (as may be determined using method
752 * {@link #inForkJoinPool}). Attempts to invoke in other contexts
753 * result in exceptions or errors, possibly including {@code
754 * ClassCastException}.
756 * @param tasks the collection of tasks
757 * @return the tasks argument, to simplify usage
758 * @throws NullPointerException if tasks or any element are null
760 public static <T extends ForkJoinTask<?>> Collection<T> invokeAll(Collection<T> tasks) {
761 if (!(tasks instanceof RandomAccess) || !(tasks instanceof List<?>)) {
762 invokeAll(tasks.toArray(new ForkJoinTask<?>[tasks.size()]));
765 @SuppressWarnings("unchecked")
766 List<? extends ForkJoinTask<?>> ts =
767 (List<? extends ForkJoinTask<?>>) tasks;
769 int last = ts.size() - 1;
770 for (int i = last; i >= 0; --i) {
771 ForkJoinTask<?> t = ts.get(i);
774 ex = new NullPointerException();
778 else if (t.doInvoke() < NORMAL && ex == null)
779 ex = t.getException();
781 for (int i = 1; i <= last; ++i) {
782 ForkJoinTask<?> t = ts.get(i);
786 else if (t.doJoin() < NORMAL && ex == null)
787 ex = t.getException();
791 UNSAFE.throwException(ex);
796 * Attempts to cancel execution of this task. This attempt will
797 * fail if the task has already completed or could not be
798 * cancelled for some other reason. If successful, and this task
799 * has not started when {@code cancel} is called, execution of
800 * this task is suppressed. After this method returns
801 * successfully, unless there is an intervening call to {@link
802 * #reinitialize}, subsequent calls to {@link #isCancelled},
803 * {@link #isDone}, and {@code cancel} will return {@code true}
804 * and calls to {@link #join} and related methods will result in
805 * {@code CancellationException}.
807 * <p>This method may be overridden in subclasses, but if so, must
808 * still ensure that these properties hold. In particular, the
809 * {@code cancel} method itself must not throw exceptions.
811 * <p>This method is designed to be invoked by <em>other</em>
812 * tasks. To terminate the current task, you can just return or
813 * throw an unchecked exception from its computation method, or
814 * invoke {@link #completeExceptionally}.
816 * @param mayInterruptIfRunning this value has no effect in the
817 * default implementation because interrupts are not used to
818 * control cancellation.
820 * @return {@code true} if this task is now cancelled
822 public boolean cancel(boolean mayInterruptIfRunning) {
823 return setCompletion(CANCELLED) == CANCELLED;
827 * Cancels, ignoring any exceptions thrown by cancel. Used during
828 * worker and pool shutdown. Cancel is spec'ed not to throw any
829 * exceptions, but if it does anyway, we have no recourse during
830 * shutdown, so guard against this case.
832 final void cancelIgnoringExceptions() {
835 } catch (Throwable ignore) {
839 public final boolean isDone() {
843 public final boolean isCancelled() {
844 return status == CANCELLED;
848 * Returns {@code true} if this task threw an exception or was cancelled.
850 * @return {@code true} if this task threw an exception or was cancelled
852 public final boolean isCompletedAbnormally() {
853 return status < NORMAL;
857 * Returns {@code true} if this task completed without throwing an
858 * exception and was not cancelled.
860 * @return {@code true} if this task completed without throwing an
861 * exception and was not cancelled
863 public final boolean isCompletedNormally() {
864 return status == NORMAL;
868 * Returns the exception thrown by the base computation, or a
869 * {@code CancellationException} if cancelled, or {@code null} if
870 * none or if the method has not yet completed.
872 * @return the exception, or {@code null} if none
874 public final Throwable getException() {
876 return ((s >= NORMAL) ? null :
877 (s == CANCELLED) ? new CancellationException() :
878 getThrowableException());
882 * Completes this task abnormally, and if not already aborted or
883 * cancelled, causes it to throw the given exception upon
884 * {@code join} and related operations. This method may be used
885 * to induce exceptions in asynchronous tasks, or to force
886 * completion of tasks that would not otherwise complete. Its use
887 * in other situations is discouraged. This method is
888 * overridable, but overridden versions must invoke {@code super}
889 * implementation to maintain guarantees.
891 * @param ex the exception to throw. If this exception is not a
892 * {@code RuntimeException} or {@code Error}, the actual exception
893 * thrown will be a {@code RuntimeException} with cause {@code ex}.
895 public void completeExceptionally(Throwable ex) {
896 setExceptionalCompletion((ex instanceof RuntimeException) ||
897 (ex instanceof Error) ? ex :
898 new RuntimeException(ex));
902 * Completes this task, and if not already aborted or cancelled,
903 * returning the given value as the result of subsequent
904 * invocations of {@code join} and related operations. This method
905 * may be used to provide results for asynchronous tasks, or to
906 * provide alternative handling for tasks that would not otherwise
907 * complete normally. Its use in other situations is
908 * discouraged. This method is overridable, but overridden
909 * versions must invoke {@code super} implementation to maintain
912 * @param value the result value for this task
914 public void complete(V value) {
917 } catch (Throwable rex) {
918 setExceptionalCompletion(rex);
921 setCompletion(NORMAL);
925 * Waits if necessary for the computation to complete, and then
926 * retrieves its result.
928 * @return the computed result
929 * @throws CancellationException if the computation was cancelled
930 * @throws ExecutionException if the computation threw an
932 * @throws InterruptedException if the current thread is not a
933 * member of a ForkJoinPool and was interrupted while waiting
935 public final V get() throws InterruptedException, ExecutionException {
936 int s = (Thread.currentThread() instanceof ForkJoinWorkerThread) ?
937 doJoin() : externalInterruptibleAwaitDone(0L);
940 throw new CancellationException();
941 if (s == EXCEPTIONAL && (ex = getThrowableException()) != null)
942 throw new ExecutionException(ex);
943 return getRawResult();
947 * Waits if necessary for at most the given time for the computation
948 * to complete, and then retrieves its result, if available.
950 * @param timeout the maximum time to wait
951 * @param unit the time unit of the timeout argument
952 * @return the computed result
953 * @throws CancellationException if the computation was cancelled
954 * @throws ExecutionException if the computation threw an
956 * @throws InterruptedException if the current thread is not a
957 * member of a ForkJoinPool and was interrupted while waiting
958 * @throws TimeoutException if the wait timed out
960 public final V get(long timeout, TimeUnit unit)
961 throws InterruptedException, ExecutionException, TimeoutException {
962 Thread t = Thread.currentThread();
963 if (t instanceof ForkJoinWorkerThread) {
964 ForkJoinWorkerThread w = (ForkJoinWorkerThread) t;
965 long nanos = unit.toNanos(timeout);
967 boolean completed = false;
968 if (w.unpushTask(this)) {
971 } catch (Throwable rex) {
972 setExceptionalCompletion(rex);
976 setCompletion(NORMAL);
977 else if (status >= 0 && nanos > 0)
978 w.pool.timedAwaitJoin(this, nanos);
982 long millis = unit.toMillis(timeout);
984 externalInterruptibleAwaitDone(millis);
990 throw new CancellationException();
991 if (s != EXCEPTIONAL)
992 throw new TimeoutException();
993 if ((ex = getThrowableException()) != null)
994 throw new ExecutionException(ex);
996 return getRawResult();
1000 * Joins this task, without returning its result or throwing its
1001 * exception. This method may be useful when processing
1002 * collections of tasks when some have been cancelled or otherwise
1003 * known to have aborted.
1005 public final void quietlyJoin() {
1010 * Commences performing this task and awaits its completion if
1011 * necessary, without returning its result or throwing its
1014 public final void quietlyInvoke() {
1019 * Possibly executes tasks until the pool hosting the current task
1020 * {@link ForkJoinPool#isQuiescent is quiescent}. This method may
1021 * be of use in designs in which many tasks are forked, but none
1022 * are explicitly joined, instead executing them until all are
1025 * <p>This method may be invoked only from within {@code
1026 * ForkJoinPool} computations (as may be determined using method
1027 * {@link #inForkJoinPool}). Attempts to invoke in other contexts
1028 * result in exceptions or errors, possibly including {@code
1029 * ClassCastException}.
1031 public static void helpQuiesce() {
1032 ((ForkJoinWorkerThread) Thread.currentThread())
1037 * Resets the internal bookkeeping state of this task, allowing a
1038 * subsequent {@code fork}. This method allows repeated reuse of
1039 * this task, but only if reuse occurs when this task has either
1040 * never been forked, or has been forked, then completed and all
1041 * outstanding joins of this task have also completed. Effects
1042 * under any other usage conditions are not guaranteed.
1043 * This method may be useful when executing
1044 * pre-constructed trees of subtasks in loops.
1046 * <p>Upon completion of this method, {@code isDone()} reports
1047 * {@code false}, and {@code getException()} reports {@code
1048 * null}. However, the value returned by {@code getRawResult} is
1049 * unaffected. To clear this value, you can invoke {@code
1050 * setRawResult(null)}.
1052 public void reinitialize() {
1053 if (status == EXCEPTIONAL)
1054 clearExceptionalCompletion();
1060 * Returns the pool hosting the current task execution, or null
1061 * if this task is executing outside of any ForkJoinPool.
1063 * @see #inForkJoinPool
1064 * @return the pool, or {@code null} if none
1066 public static ForkJoinPool getPool() {
1067 Thread t = Thread.currentThread();
1068 return (t instanceof ForkJoinWorkerThread) ?
1069 ((ForkJoinWorkerThread) t).pool : null;
1073 * Returns {@code true} if the current thread is a {@link
1074 * ForkJoinWorkerThread} executing as a ForkJoinPool computation.
1076 * @return {@code true} if the current thread is a {@link
1077 * ForkJoinWorkerThread} executing as a ForkJoinPool computation,
1078 * or {@code false} otherwise
1080 public static boolean inForkJoinPool() {
1081 return Thread.currentThread() instanceof ForkJoinWorkerThread;
1085 * Tries to unschedule this task for execution. This method will
1086 * typically succeed if this task is the most recently forked task
1087 * by the current thread, and has not commenced executing in
1088 * another thread. This method may be useful when arranging
1089 * alternative local processing of tasks that could have been, but
1092 * <p>This method may be invoked only from within {@code
1093 * ForkJoinPool} computations (as may be determined using method
1094 * {@link #inForkJoinPool}). Attempts to invoke in other contexts
1095 * result in exceptions or errors, possibly including {@code
1096 * ClassCastException}.
1098 * @return {@code true} if unforked
1100 public boolean tryUnfork() {
1101 return ((ForkJoinWorkerThread) Thread.currentThread())
1106 * Returns an estimate of the number of tasks that have been
1107 * forked by the current worker thread but not yet executed. This
1108 * value may be useful for heuristic decisions about whether to
1111 * <p>This method may be invoked only from within {@code
1112 * ForkJoinPool} computations (as may be determined using method
1113 * {@link #inForkJoinPool}). Attempts to invoke in other contexts
1114 * result in exceptions or errors, possibly including {@code
1115 * ClassCastException}.
1117 * @return the number of tasks
1119 public static int getQueuedTaskCount() {
1120 return ((ForkJoinWorkerThread) Thread.currentThread())
1125 * Returns an estimate of how many more locally queued tasks are
1126 * held by the current worker thread than there are other worker
1127 * threads that might steal them. This value may be useful for
1128 * heuristic decisions about whether to fork other tasks. In many
1129 * usages of ForkJoinTasks, at steady state, each worker should
1130 * aim to maintain a small constant surplus (for example, 3) of
1131 * tasks, and to process computations locally if this threshold is
1134 * <p>This method may be invoked only from within {@code
1135 * ForkJoinPool} computations (as may be determined using method
1136 * {@link #inForkJoinPool}). Attempts to invoke in other contexts
1137 * result in exceptions or errors, possibly including {@code
1138 * ClassCastException}.
1140 * @return the surplus number of tasks, which may be negative
1142 public static int getSurplusQueuedTaskCount() {
1143 return ((ForkJoinWorkerThread) Thread.currentThread())
1144 .getEstimatedSurplusTaskCount();
1147 // Extension methods
1150 * Returns the result that would be returned by {@link #join}, even
1151 * if this task completed abnormally, or {@code null} if this task
1152 * is not known to have been completed. This method is designed
1153 * to aid debugging, as well as to support extensions. Its use in
1154 * any other context is discouraged.
1156 * @return the result, or {@code null} if not completed
1158 public abstract V getRawResult();
1161 * Forces the given value to be returned as a result. This method
1162 * is designed to support extensions, and should not in general be
1165 * @param value the value
1167 protected abstract void setRawResult(V value);
1170 * Immediately performs the base action of this task. This method
1171 * is designed to support extensions, and should not in general be
1172 * called otherwise. The return value controls whether this task
1173 * is considered to be done normally. It may return false in
1174 * asynchronous actions that require explicit invocations of
1175 * {@link #complete} to become joinable. It may also throw an
1176 * (unchecked) exception to indicate abnormal exit.
1178 * @return {@code true} if completed normally
1180 protected abstract boolean exec();
1183 * Returns, but does not unschedule or execute, a task queued by
1184 * the current thread but not yet executed, if one is immediately
1185 * available. There is no guarantee that this task will actually
1186 * be polled or executed next. Conversely, this method may return
1187 * null even if a task exists but cannot be accessed without
1188 * contention with other threads. This method is designed
1189 * primarily to support extensions, and is unlikely to be useful
1192 * <p>This method may be invoked only from within {@code
1193 * ForkJoinPool} computations (as may be determined using method
1194 * {@link #inForkJoinPool}). Attempts to invoke in other contexts
1195 * result in exceptions or errors, possibly including {@code
1196 * ClassCastException}.
1198 * @return the next task, or {@code null} if none are available
1200 protected static ForkJoinTask<?> peekNextLocalTask() {
1201 return ((ForkJoinWorkerThread) Thread.currentThread())
1206 * Unschedules and returns, without executing, the next task
1207 * queued by the current thread but not yet executed. This method
1208 * is designed primarily to support extensions, and is unlikely to
1209 * be useful otherwise.
1211 * <p>This method may be invoked only from within {@code
1212 * ForkJoinPool} computations (as may be determined using method
1213 * {@link #inForkJoinPool}). Attempts to invoke in other contexts
1214 * result in exceptions or errors, possibly including {@code
1215 * ClassCastException}.
1217 * @return the next task, or {@code null} if none are available
1219 protected static ForkJoinTask<?> pollNextLocalTask() {
1220 return ((ForkJoinWorkerThread) Thread.currentThread())
1225 * Unschedules and returns, without executing, the next task
1226 * queued by the current thread but not yet executed, if one is
1227 * available, or if not available, a task that was forked by some
1228 * other thread, if available. Availability may be transient, so a
1229 * {@code null} result does not necessarily imply quiescence
1230 * of the pool this task is operating in. This method is designed
1231 * primarily to support extensions, and is unlikely to be useful
1234 * <p>This method may be invoked only from within {@code
1235 * ForkJoinPool} computations (as may be determined using method
1236 * {@link #inForkJoinPool}). Attempts to invoke in other contexts
1237 * result in exceptions or errors, possibly including {@code
1238 * ClassCastException}.
1240 * @return a task, or {@code null} if none are available
1242 protected static ForkJoinTask<?> pollTask() {
1243 return ((ForkJoinWorkerThread) Thread.currentThread())
1248 * Adaptor for Runnables. This implements RunnableFuture
1249 * to be compliant with AbstractExecutorService constraints
1250 * when used in ForkJoinPool.
1252 static final class AdaptedRunnable<T> extends ForkJoinTask<T>
1253 implements RunnableFuture<T> {
1254 final Runnable runnable;
1255 final T resultOnCompletion;
1257 AdaptedRunnable(Runnable runnable, T result) {
1258 if (runnable == null) throw new NullPointerException();
1259 this.runnable = runnable;
1260 this.resultOnCompletion = result;
1262 public T getRawResult() { return result; }
1263 public void setRawResult(T v) { result = v; }
1264 public boolean exec() {
1266 result = resultOnCompletion;
1269 public void run() { invoke(); }
1270 private static final long serialVersionUID = 5232453952276885070L;
1274 * Adaptor for Callables
1276 static final class AdaptedCallable<T> extends ForkJoinTask<T>
1277 implements RunnableFuture<T> {
1278 final Callable<? extends T> callable;
1280 AdaptedCallable(Callable<? extends T> callable) {
1281 if (callable == null) throw new NullPointerException();
1282 this.callable = callable;
1284 public T getRawResult() { return result; }
1285 public void setRawResult(T v) { result = v; }
1286 public boolean exec() {
1288 result = callable.call();
1290 } catch (Error err) {
1292 } catch (RuntimeException rex) {
1294 } catch (Exception ex) {
1295 throw new RuntimeException(ex);
1298 public void run() { invoke(); }
1299 private static final long serialVersionUID = 2838392045355241008L;
1303 * Returns a new {@code ForkJoinTask} that performs the {@code run}
1304 * method of the given {@code Runnable} as its action, and returns
1305 * a null result upon {@link #join}.
1307 * @param runnable the runnable action
1310 public static ForkJoinTask<?> adapt(Runnable runnable) {
1311 return new AdaptedRunnable<Void>(runnable, null);
1315 * Returns a new {@code ForkJoinTask} that performs the {@code run}
1316 * method of the given {@code Runnable} as its action, and returns
1317 * the given result upon {@link #join}.
1319 * @param runnable the runnable action
1320 * @param result the result upon completion
1323 public static <T> ForkJoinTask<T> adapt(Runnable runnable, T result) {
1324 return new AdaptedRunnable<T>(runnable, result);
1328 * Returns a new {@code ForkJoinTask} that performs the {@code call}
1329 * method of the given {@code Callable} as its action, and returns
1330 * its result upon {@link #join}, translating any checked exceptions
1331 * encountered into {@code RuntimeException}.
1333 * @param callable the callable action
1336 public static <T> ForkJoinTask<T> adapt(Callable<? extends T> callable) {
1337 return new AdaptedCallable<T>(callable);
1340 // Serialization support
1342 private static final long serialVersionUID = -7721805057305804111L;
1345 * Saves the state to a stream (that is, serializes it).
1347 * @serialData the current run status and the exception thrown
1348 * during execution, or {@code null} if none
1349 * @param s the stream
1351 private void writeObject(java.io.ObjectOutputStream s)
1352 throws java.io.IOException {
1353 s.defaultWriteObject();
1354 s.writeObject(getException());
1358 * Reconstitutes the instance from a stream (that is, deserializes it).
1360 * @param s the stream
1362 private void readObject(java.io.ObjectInputStream s)
1363 throws java.io.IOException, ClassNotFoundException {
1364 s.defaultReadObject();
1365 Object ex = s.readObject();
1367 setExceptionalCompletion((Throwable)ex);
1371 private static final sun.misc.Unsafe UNSAFE;
1372 private static final long statusOffset;
1374 exceptionTableLock = new ReentrantLock();
1375 exceptionTableRefQueue = new ReferenceQueue<Object>();
1376 exceptionTable = new ExceptionNode[EXCEPTION_MAP_CAPACITY];
1378 UNSAFE = sun.misc.Unsafe.getUnsafe();
1379 statusOffset = UNSAFE.objectFieldOffset
1380 (ForkJoinTask.class.getDeclaredField("status"));
1381 } catch (Exception e) {