Making java.util.concurrent compilable without references to sun.misc.Unsafe and co.
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.List;
41 import java.util.RandomAccess;
42 import java.lang.ref.WeakReference;
43 import java.lang.ref.ReferenceQueue;
44 import java.util.concurrent.Callable;
45 import java.util.concurrent.CancellationException;
46 import java.util.concurrent.ExecutionException;
47 import java.util.concurrent.Future;
48 import java.util.concurrent.RejectedExecutionException;
49 import java.util.concurrent.RunnableFuture;
50 import java.util.concurrent.TimeUnit;
51 import java.util.concurrent.TimeoutException;
52 import java.util.concurrent.locks.ReentrantLock;
53 import java.lang.reflect.Constructor;
56 * Abstract base class for tasks that run within a {@link ForkJoinPool}.
57 * A {@code ForkJoinTask} is a thread-like entity that is much
58 * lighter weight than a normal thread. Huge numbers of tasks and
59 * subtasks may be hosted by a small number of actual threads in a
60 * ForkJoinPool, at the price of some usage limitations.
62 * <p>A "main" {@code ForkJoinTask} begins execution when submitted
63 * to a {@link ForkJoinPool}. Once started, it will usually in turn
64 * start other subtasks. As indicated by the name of this class,
65 * many programs using {@code ForkJoinTask} employ only methods
66 * {@link #fork} and {@link #join}, or derivatives such as {@link
67 * #invokeAll(ForkJoinTask...) invokeAll}. However, this class also
68 * provides a number of other methods that can come into play in
69 * advanced usages, as well as extension mechanics that allow
70 * support of new forms of fork/join processing.
72 * <p>A {@code ForkJoinTask} is a lightweight form of {@link Future}.
73 * The efficiency of {@code ForkJoinTask}s stems from a set of
74 * restrictions (that are only partially statically enforceable)
75 * reflecting their intended use as computational tasks calculating
76 * pure functions or operating on purely isolated objects. The
77 * primary coordination mechanisms are {@link #fork}, that arranges
78 * asynchronous execution, and {@link #join}, that doesn't proceed
79 * until the task's result has been computed. Computations should
80 * avoid {@code synchronized} methods or blocks, and should minimize
81 * other blocking synchronization apart from joining other tasks or
82 * using synchronizers such as Phasers that are advertised to
83 * cooperate with fork/join scheduling. Tasks should also not perform
84 * blocking IO, and should ideally access variables that are
85 * completely independent of those accessed by other running
86 * tasks. Minor breaches of these restrictions, for example using
87 * shared output streams, may be tolerable in practice, but frequent
88 * use may result in poor performance, and the potential to
89 * indefinitely stall if the number of threads not waiting for IO or
90 * other external synchronization becomes exhausted. This usage
91 * restriction is in part enforced by not permitting checked
92 * exceptions such as {@code IOExceptions} to be thrown. However,
93 * computations may still encounter unchecked exceptions, that are
94 * rethrown to callers attempting to join them. These exceptions may
95 * additionally include {@link RejectedExecutionException} stemming
96 * from internal resource exhaustion, such as failure to allocate
97 * internal task queues. Rethrown exceptions behave in the same way as
98 * regular exceptions, but, when possible, contain stack traces (as
99 * displayed for example using {@code ex.printStackTrace()}) of both
100 * the thread that initiated the computation as well as the thread
101 * actually encountering the exception; minimally only the latter.
103 * <p>The primary method for awaiting completion and extracting
104 * results of a task is {@link #join}, but there are several variants:
105 * The {@link Future#get} methods support interruptible and/or timed
106 * waits for completion and report results using {@code Future}
107 * conventions. Method {@link #invoke} is semantically
108 * equivalent to {@code fork(); join()} but always attempts to begin
109 * execution in the current thread. The "<em>quiet</em>" forms of
110 * these methods do not extract results or report exceptions. These
111 * may be useful when a set of tasks are being executed, and you need
112 * to delay processing of results or exceptions until all complete.
113 * Method {@code invokeAll} (available in multiple versions)
114 * performs the most common form of parallel invocation: forking a set
115 * of tasks and joining them all.
117 * <p>The execution status of tasks may be queried at several levels
118 * of detail: {@link #isDone} is true if a task completed in any way
119 * (including the case where a task was cancelled without executing);
120 * {@link #isCompletedNormally} is true if a task completed without
121 * cancellation or encountering an exception; {@link #isCancelled} is
122 * true if the task was cancelled (in which case {@link #getException}
123 * returns a {@link java.util.concurrent.CancellationException}); and
124 * {@link #isCompletedAbnormally} is true if a task was either
125 * cancelled or encountered an exception, in which case {@link
126 * #getException} will return either the encountered exception or
127 * {@link java.util.concurrent.CancellationException}.
129 * <p>The ForkJoinTask class is not usually directly subclassed.
130 * Instead, you subclass one of the abstract classes that support a
131 * particular style of fork/join processing, typically {@link
132 * RecursiveAction} for computations that do not return results, or
133 * {@link RecursiveTask} for those that do. Normally, a concrete
134 * ForkJoinTask subclass declares fields comprising its parameters,
135 * established in a constructor, and then defines a {@code compute}
136 * method that somehow uses the control methods supplied by this base
137 * class. While these methods have {@code public} access (to allow
138 * instances of different task subclasses to call each other's
139 * methods), some of them may only be called from within other
140 * ForkJoinTasks (as may be determined using method {@link
141 * #inForkJoinPool}). Attempts to invoke them in other contexts
142 * result in exceptions or errors, possibly including
143 * {@code ClassCastException}.
145 * <p>Method {@link #join} and its variants are appropriate for use
146 * only when completion dependencies are acyclic; that is, the
147 * parallel computation can be described as a directed acyclic graph
148 * (DAG). Otherwise, executions may encounter a form of deadlock as
149 * tasks cyclically wait for each other. However, this framework
150 * supports other methods and techniques (for example the use of
151 * {@link Phaser}, {@link #helpQuiesce}, and {@link #complete}) that
152 * may be of use in constructing custom subclasses for problems that
153 * are not statically structured as DAGs.
155 * <p>Most base support methods are {@code final}, to prevent
156 * overriding of implementations that are intrinsically tied to the
157 * underlying lightweight task scheduling framework. Developers
158 * creating new basic styles of fork/join processing should minimally
159 * implement {@code protected} methods {@link #exec}, {@link
160 * #setRawResult}, and {@link #getRawResult}, while also introducing
161 * an abstract computational method that can be implemented in its
162 * subclasses, possibly relying on other {@code protected} methods
163 * provided by this class.
165 * <p>ForkJoinTasks should perform relatively small amounts of
166 * computation. Large tasks should be split into smaller subtasks,
167 * usually via recursive decomposition. As a very rough rule of thumb,
168 * a task should perform more than 100 and less than 10000 basic
169 * computational steps, and should avoid indefinite looping. If tasks
170 * are too big, then parallelism cannot improve throughput. If too
171 * small, then memory and internal task maintenance overhead may
172 * overwhelm processing.
174 * <p>This class provides {@code adapt} methods for {@link Runnable}
175 * and {@link Callable}, that may be of use when mixing execution of
176 * {@code ForkJoinTasks} with other kinds of tasks. When all tasks are
177 * of this form, consider using a pool constructed in <em>asyncMode</em>.
179 * <p>ForkJoinTasks are {@code Serializable}, which enables them to be
180 * used in extensions such as remote execution frameworks. It is
181 * sensible to serialize tasks only before or after, but not during,
182 * execution. Serialization is not relied on during execution itself.
187 public abstract class ForkJoinTask<V> implements Future<V>, Serializable {
190 * See the internal documentation of class ForkJoinPool for a
191 * general implementation overview. ForkJoinTasks are mainly
192 * responsible for maintaining their "status" field amidst relays
193 * to methods in ForkJoinWorkerThread and ForkJoinPool. The
194 * methods of this class are more-or-less layered into (1) basic
195 * status maintenance (2) execution and awaiting completion (3)
196 * user-level methods that additionally report results. This is
197 * sometimes hard to see because this file orders exported methods
198 * in a way that flows well in javadocs.
202 * The status field holds run control status bits packed into a
203 * single int to minimize footprint and to ensure atomicity (via
204 * CAS). Status is initially zero, and takes on nonnegative
205 * values until completed, upon which status holds value
206 * NORMAL, CANCELLED, or EXCEPTIONAL. Tasks undergoing blocking
207 * waits by other threads have the SIGNAL bit set. Completion of
208 * a stolen task with SIGNAL set awakens any waiters via
209 * notifyAll. Even though suboptimal for some purposes, we use
210 * basic builtin wait/notify to take advantage of "monitor
211 * inflation" in JVMs that we would otherwise need to emulate to
212 * avoid adding further per-task bookkeeping overhead. We want
213 * these monitors to be "fat", i.e., not use biasing or thin-lock
214 * techniques, so use some odd coding idioms that tend to avoid
218 /** The run status of this task */
219 volatile int status; // accessed directly by pool and workers
220 private static final int NORMAL = -1;
221 private static final int CANCELLED = -2;
222 private static final int EXCEPTIONAL = -3;
223 private static final int SIGNAL = 1;
226 * Marks completion and wakes up threads waiting to join this task,
227 * also clearing signal request bits.
229 * @param completion one of NORMAL, CANCELLED, EXCEPTIONAL
230 * @return completion status on exit
232 private int setCompletion(int completion) {
234 if ((s = status) < 0)
236 if (UNSAFE.compareAndSwapInt(this, statusOffset, s, completion)) {
238 synchronized (this) { notifyAll(); }
245 * Tries to block a worker thread until completed or timed out.
246 * Uses Object.wait time argument conventions.
247 * May fail on contention or interrupt.
249 * @param millis if > 0, wait time.
251 final void tryAwaitDone(long millis) {
254 if (((s = status) > 0 ||
256 UNSAFE.compareAndSwapInt(this, statusOffset, 0, SIGNAL))) &&
258 synchronized (this) {
263 } catch (InterruptedException ie) {
264 // caller must check termination
269 * Blocks a non-worker-thread until completion.
270 * @return status upon completion
272 private int externalAwaitDone() {
274 if ((s = status) >= 0) {
275 boolean interrupted = false;
276 synchronized (this) {
277 while ((s = status) >= 0) {
279 UNSAFE.compareAndSwapInt(this, statusOffset,
284 } catch (InterruptedException ie) {
291 Thread.currentThread().interrupt();
297 * Blocks a non-worker-thread until completion or interruption or timeout.
299 private int externalInterruptibleAwaitDone(long millis)
300 throws InterruptedException {
302 if (Thread.interrupted())
303 throw new InterruptedException();
304 if ((s = status) >= 0) {
305 synchronized (this) {
306 while ((s = status) >= 0) {
308 UNSAFE.compareAndSwapInt(this, statusOffset,
322 * Primary execution method for stolen tasks. Unless done, calls
323 * exec and records status if completed, but doesn't wait for
324 * completion otherwise.
326 final void doExec() {
331 } catch (Throwable rex) {
332 setExceptionalCompletion(rex);
336 setCompletion(NORMAL); // must be outside try block
341 * Primary mechanics for join, get, quietlyJoin.
342 * @return status upon completion
344 private int doJoin() {
345 Thread t; ForkJoinWorkerThread w; int s; boolean completed;
346 if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) {
347 if ((s = status) < 0)
349 if ((w = (ForkJoinWorkerThread)t).unpushTask(this)) {
352 } catch (Throwable rex) {
353 return setExceptionalCompletion(rex);
356 return setCompletion(NORMAL);
358 return w.joinTask(this);
361 return externalAwaitDone();
365 * Primary mechanics for invoke, quietlyInvoke.
366 * @return status upon completion
368 private int doInvoke() {
369 int s; boolean completed;
370 if ((s = status) < 0)
374 } catch (Throwable rex) {
375 return setExceptionalCompletion(rex);
378 return setCompletion(NORMAL);
383 // Exception table support
386 * Table of exceptions thrown by tasks, to enable reporting by
387 * callers. Because exceptions are rare, we don't directly keep
388 * them with task objects, but instead use a weak ref table. Note
389 * that cancellation exceptions don't appear in the table, but are
390 * instead recorded as status values.
392 * Note: These statics are initialized below in static block.
394 private static final ExceptionNode[] exceptionTable;
395 private static final ReentrantLock exceptionTableLock;
396 private static final ReferenceQueue<Object> exceptionTableRefQueue;
399 * Fixed capacity for exceptionTable.
401 private static final int EXCEPTION_MAP_CAPACITY = 32;
404 * Key-value nodes for exception table. The chained hash table
405 * uses identity comparisons, full locking, and weak references
406 * for keys. The table has a fixed capacity because it only
407 * maintains task exceptions long enough for joiners to access
408 * them, so should never become very large for sustained
409 * periods. However, since we do not know when the last joiner
410 * completes, we must use weak references and expunge them. We do
411 * so on each operation (hence full locking). Also, some thread in
412 * any ForkJoinPool will call helpExpungeStaleExceptions when its
413 * pool becomes isQuiescent.
415 static final class ExceptionNode extends WeakReference<ForkJoinTask<?>>{
418 final long thrower; // use id not ref to avoid weak cycles
419 ExceptionNode(ForkJoinTask<?> task, Throwable ex, ExceptionNode next) {
420 super(task, exceptionTableRefQueue);
423 this.thrower = Thread.currentThread().getId();
428 * Records exception and sets exceptional completion.
430 * @return status on exit
432 private int setExceptionalCompletion(Throwable ex) {
433 int h = System.identityHashCode(this);
434 final ReentrantLock lock = exceptionTableLock;
437 expungeStaleExceptions();
438 ExceptionNode[] t = exceptionTable;
439 int i = h & (t.length - 1);
440 for (ExceptionNode e = t[i]; ; e = e.next) {
442 t[i] = new ExceptionNode(this, ex, t[i]);
445 if (e.get() == this) // already present
451 return setCompletion(EXCEPTIONAL);
455 * Removes exception node and clears status
457 private void clearExceptionalCompletion() {
458 int h = System.identityHashCode(this);
459 final ReentrantLock lock = exceptionTableLock;
462 ExceptionNode[] t = exceptionTable;
463 int i = h & (t.length - 1);
464 ExceptionNode e = t[i];
465 ExceptionNode pred = null;
467 ExceptionNode next = e.next;
468 if (e.get() == this) {
478 expungeStaleExceptions();
486 * Returns a rethrowable exception for the given task, if
487 * available. To provide accurate stack traces, if the exception
488 * was not thrown by the current thread, we try to create a new
489 * exception of the same type as the one thrown, but with the
490 * recorded exception as its cause. If there is no such
491 * constructor, we instead try to use a no-arg constructor,
492 * followed by initCause, to the same effect. If none of these
493 * apply, or any fail due to other exceptions, we return the
494 * recorded exception, which is still correct, although it may
495 * contain a misleading stack trace.
497 * @return the exception, or null if none
499 private Throwable getThrowableException() {
500 if (status != EXCEPTIONAL)
502 int h = System.identityHashCode(this);
504 final ReentrantLock lock = exceptionTableLock;
507 expungeStaleExceptions();
508 ExceptionNode[] t = exceptionTable;
509 e = t[h & (t.length - 1)];
510 while (e != null && e.get() != this)
516 if (e == null || (ex = e.ex) == null)
518 if (e.thrower != Thread.currentThread().getId()) {
519 Class ec = ex.getClass();
521 Constructor<?> noArgCtor = null;
522 Constructor<?>[] cs = ec.getConstructors();// public ctors only
523 for (int i = 0; i < cs.length; ++i) {
524 Constructor<?> c = cs[i];
525 Class<?>[] ps = c.getParameterTypes();
528 else if (ps.length == 1 && ps[0] == Throwable.class)
529 return (Throwable)(c.newInstance(ex));
531 if (noArgCtor != null) {
532 Throwable wx = (Throwable)(noArgCtor.newInstance());
536 } catch (Exception ignore) {
543 * Poll stale refs and remove them. Call only while holding lock.
545 private static void expungeStaleExceptions() {
546 for (Object x; (x = exceptionTableRefQueue.poll()) != null;) {
547 if (x instanceof ExceptionNode) {
548 ForkJoinTask<?> key = ((ExceptionNode)x).get();
549 ExceptionNode[] t = exceptionTable;
550 int i = System.identityHashCode(key) & (t.length - 1);
551 ExceptionNode e = t[i];
552 ExceptionNode pred = null;
554 ExceptionNode next = e.next;
570 * If lock is available, poll stale refs and remove them.
571 * Called from ForkJoinPool when pools become quiescent.
573 static final void helpExpungeStaleExceptions() {
574 final ReentrantLock lock = exceptionTableLock;
575 if (lock.tryLock()) {
577 expungeStaleExceptions();
585 * Report the result of invoke or join; called only upon
586 * non-normal return of internal versions.
588 private V reportResult() {
590 if ((s = status) == CANCELLED)
591 throw new CancellationException();
592 if (s == EXCEPTIONAL && (ex = getThrowableException()) != null)
593 UNSAFE.throwException(ex);
594 return getRawResult();
600 * Arranges to asynchronously execute this task. While it is not
601 * necessarily enforced, it is a usage error to fork a task more
602 * than once unless it has completed and been reinitialized.
603 * Subsequent modifications to the state of this task or any data
604 * it operates on are not necessarily consistently observable by
605 * any thread other than the one executing it unless preceded by a
606 * call to {@link #join} or related methods, or a call to {@link
607 * #isDone} returning {@code true}.
609 * <p>This method may be invoked only from within {@code
610 * ForkJoinPool} computations (as may be determined using method
611 * {@link #inForkJoinPool}). Attempts to invoke in other contexts
612 * result in exceptions or errors, possibly including {@code
613 * ClassCastException}.
615 * @return {@code this}, to simplify usage
617 public final ForkJoinTask<V> fork() {
618 ((ForkJoinWorkerThread) Thread.currentThread())
624 * Returns the result of the computation when it {@link #isDone is
625 * done}. This method differs from {@link #get()} in that
626 * abnormal completion results in {@code RuntimeException} or
627 * {@code Error}, not {@code ExecutionException}, and that
628 * interrupts of the calling thread do <em>not</em> cause the
629 * method to abruptly return by throwing {@code
630 * InterruptedException}.
632 * @return the computed result
634 public final V join() {
635 if (doJoin() != NORMAL)
636 return reportResult();
638 return getRawResult();
642 * Commences performing this task, awaits its completion if
643 * necessary, and returns its result, or throws an (unchecked)
644 * {@code RuntimeException} or {@code Error} if the underlying
645 * computation did so.
647 * @return the computed result
649 public final V invoke() {
650 if (doInvoke() != NORMAL)
651 return reportResult();
653 return getRawResult();
657 * Forks the given tasks, returning when {@code isDone} holds for
658 * each task or an (unchecked) exception is encountered, in which
659 * case the exception is rethrown. If more than one task
660 * encounters an exception, then this method throws any one of
661 * these exceptions. If any task encounters an exception, the
662 * other may be cancelled. However, the execution status of
663 * individual tasks is not guaranteed upon exceptional return. The
664 * status of each task may be obtained using {@link
665 * #getException()} and related methods to check if they have been
666 * cancelled, completed normally or exceptionally, or left
669 * <p>This method may be invoked only from within {@code
670 * ForkJoinPool} computations (as may be determined using method
671 * {@link #inForkJoinPool}). Attempts to invoke in other contexts
672 * result in exceptions or errors, possibly including {@code
673 * ClassCastException}.
675 * @param t1 the first task
676 * @param t2 the second task
677 * @throws NullPointerException if any task is null
679 public static void invokeAll(ForkJoinTask<?> t1, ForkJoinTask<?> t2) {
686 * Forks the given tasks, returning when {@code isDone} holds for
687 * each task or an (unchecked) exception is encountered, in which
688 * case the exception is rethrown. If more than one task
689 * encounters an exception, then this method throws any one of
690 * these exceptions. If any task encounters an exception, others
691 * may be cancelled. However, the execution status of individual
692 * tasks is not guaranteed upon exceptional return. The status of
693 * each task may be obtained using {@link #getException()} and
694 * related methods to check if they have been cancelled, completed
695 * normally or exceptionally, or left unprocessed.
697 * <p>This method may be invoked only from within {@code
698 * ForkJoinPool} computations (as may be determined using method
699 * {@link #inForkJoinPool}). Attempts to invoke in other contexts
700 * result in exceptions or errors, possibly including {@code
701 * ClassCastException}.
703 * @param tasks the tasks
704 * @throws NullPointerException if any task is null
706 public static void invokeAll(ForkJoinTask<?>... tasks) {
708 int last = tasks.length - 1;
709 for (int i = last; i >= 0; --i) {
710 ForkJoinTask<?> t = tasks[i];
713 ex = new NullPointerException();
717 else if (t.doInvoke() < NORMAL && ex == null)
718 ex = t.getException();
720 for (int i = 1; i <= last; ++i) {
721 ForkJoinTask<?> t = tasks[i];
725 else if (t.doJoin() < NORMAL && ex == null)
726 ex = t.getException();
730 UNSAFE.throwException(ex);
734 * Forks all tasks in the specified collection, returning when
735 * {@code isDone} holds for each task or an (unchecked) exception
736 * is encountered, in which case the exception is rethrown. If
737 * more than one task encounters an exception, then this method
738 * throws any one of these exceptions. If any task encounters an
739 * exception, others may be cancelled. However, the execution
740 * status of individual tasks is not guaranteed upon exceptional
741 * return. The status of each task may be obtained using {@link
742 * #getException()} and related methods to check if they have been
743 * cancelled, completed normally or exceptionally, or left
746 * <p>This method may be invoked only from within {@code
747 * ForkJoinPool} computations (as may be determined using method
748 * {@link #inForkJoinPool}). Attempts to invoke in other contexts
749 * result in exceptions or errors, possibly including {@code
750 * ClassCastException}.
752 * @param tasks the collection of tasks
753 * @return the tasks argument, to simplify usage
754 * @throws NullPointerException if tasks or any element are null
756 public static <T extends ForkJoinTask<?>> Collection<T> invokeAll(Collection<T> tasks) {
757 if (!(tasks instanceof RandomAccess) || !(tasks instanceof List<?>)) {
758 invokeAll(tasks.toArray(new ForkJoinTask<?>[tasks.size()]));
761 @SuppressWarnings("unchecked")
762 List<? extends ForkJoinTask<?>> ts =
763 (List<? extends ForkJoinTask<?>>) tasks;
765 int last = ts.size() - 1;
766 for (int i = last; i >= 0; --i) {
767 ForkJoinTask<?> t = ts.get(i);
770 ex = new NullPointerException();
774 else if (t.doInvoke() < NORMAL && ex == null)
775 ex = t.getException();
777 for (int i = 1; i <= last; ++i) {
778 ForkJoinTask<?> t = ts.get(i);
782 else if (t.doJoin() < NORMAL && ex == null)
783 ex = t.getException();
787 UNSAFE.throwException(ex);
792 * Attempts to cancel execution of this task. This attempt will
793 * fail if the task has already completed or could not be
794 * cancelled for some other reason. If successful, and this task
795 * has not started when {@code cancel} is called, execution of
796 * this task is suppressed. After this method returns
797 * successfully, unless there is an intervening call to {@link
798 * #reinitialize}, subsequent calls to {@link #isCancelled},
799 * {@link #isDone}, and {@code cancel} will return {@code true}
800 * and calls to {@link #join} and related methods will result in
801 * {@code CancellationException}.
803 * <p>This method may be overridden in subclasses, but if so, must
804 * still ensure that these properties hold. In particular, the
805 * {@code cancel} method itself must not throw exceptions.
807 * <p>This method is designed to be invoked by <em>other</em>
808 * tasks. To terminate the current task, you can just return or
809 * throw an unchecked exception from its computation method, or
810 * invoke {@link #completeExceptionally}.
812 * @param mayInterruptIfRunning this value has no effect in the
813 * default implementation because interrupts are not used to
814 * control cancellation.
816 * @return {@code true} if this task is now cancelled
818 public boolean cancel(boolean mayInterruptIfRunning) {
819 return setCompletion(CANCELLED) == CANCELLED;
823 * Cancels, ignoring any exceptions thrown by cancel. Used during
824 * worker and pool shutdown. Cancel is spec'ed not to throw any
825 * exceptions, but if it does anyway, we have no recourse during
826 * shutdown, so guard against this case.
828 final void cancelIgnoringExceptions() {
831 } catch (Throwable ignore) {
835 public final boolean isDone() {
839 public final boolean isCancelled() {
840 return status == CANCELLED;
844 * Returns {@code true} if this task threw an exception or was cancelled.
846 * @return {@code true} if this task threw an exception or was cancelled
848 public final boolean isCompletedAbnormally() {
849 return status < NORMAL;
853 * Returns {@code true} if this task completed without throwing an
854 * exception and was not cancelled.
856 * @return {@code true} if this task completed without throwing an
857 * exception and was not cancelled
859 public final boolean isCompletedNormally() {
860 return status == NORMAL;
864 * Returns the exception thrown by the base computation, or a
865 * {@code CancellationException} if cancelled, or {@code null} if
866 * none or if the method has not yet completed.
868 * @return the exception, or {@code null} if none
870 public final Throwable getException() {
872 return ((s >= NORMAL) ? null :
873 (s == CANCELLED) ? new CancellationException() :
874 getThrowableException());
878 * Completes this task abnormally, and if not already aborted or
879 * cancelled, causes it to throw the given exception upon
880 * {@code join} and related operations. This method may be used
881 * to induce exceptions in asynchronous tasks, or to force
882 * completion of tasks that would not otherwise complete. Its use
883 * in other situations is discouraged. This method is
884 * overridable, but overridden versions must invoke {@code super}
885 * implementation to maintain guarantees.
887 * @param ex the exception to throw. If this exception is not a
888 * {@code RuntimeException} or {@code Error}, the actual exception
889 * thrown will be a {@code RuntimeException} with cause {@code ex}.
891 public void completeExceptionally(Throwable ex) {
892 setExceptionalCompletion((ex instanceof RuntimeException) ||
893 (ex instanceof Error) ? ex :
894 new RuntimeException(ex));
898 * Completes this task, and if not already aborted or cancelled,
899 * returning the given value as the result of subsequent
900 * invocations of {@code join} and related operations. This method
901 * may be used to provide results for asynchronous tasks, or to
902 * provide alternative handling for tasks that would not otherwise
903 * complete normally. Its use in other situations is
904 * discouraged. This method is overridable, but overridden
905 * versions must invoke {@code super} implementation to maintain
908 * @param value the result value for this task
910 public void complete(V value) {
913 } catch (Throwable rex) {
914 setExceptionalCompletion(rex);
917 setCompletion(NORMAL);
921 * Waits if necessary for the computation to complete, and then
922 * retrieves its result.
924 * @return the computed result
925 * @throws CancellationException if the computation was cancelled
926 * @throws ExecutionException if the computation threw an
928 * @throws InterruptedException if the current thread is not a
929 * member of a ForkJoinPool and was interrupted while waiting
931 public final V get() throws InterruptedException, ExecutionException {
932 int s = (Thread.currentThread() instanceof ForkJoinWorkerThread) ?
933 doJoin() : externalInterruptibleAwaitDone(0L);
936 throw new CancellationException();
937 if (s == EXCEPTIONAL && (ex = getThrowableException()) != null)
938 throw new ExecutionException(ex);
939 return getRawResult();
943 * Waits if necessary for at most the given time for the computation
944 * to complete, and then retrieves its result, if available.
946 * @param timeout the maximum time to wait
947 * @param unit the time unit of the timeout argument
948 * @return the computed result
949 * @throws CancellationException if the computation was cancelled
950 * @throws ExecutionException if the computation threw an
952 * @throws InterruptedException if the current thread is not a
953 * member of a ForkJoinPool and was interrupted while waiting
954 * @throws TimeoutException if the wait timed out
956 public final V get(long timeout, TimeUnit unit)
957 throws InterruptedException, ExecutionException, TimeoutException {
958 Thread t = Thread.currentThread();
959 if (t instanceof ForkJoinWorkerThread) {
960 ForkJoinWorkerThread w = (ForkJoinWorkerThread) t;
961 long nanos = unit.toNanos(timeout);
963 boolean completed = false;
964 if (w.unpushTask(this)) {
967 } catch (Throwable rex) {
968 setExceptionalCompletion(rex);
972 setCompletion(NORMAL);
973 else if (status >= 0 && nanos > 0)
974 w.pool.timedAwaitJoin(this, nanos);
978 long millis = unit.toMillis(timeout);
980 externalInterruptibleAwaitDone(millis);
986 throw new CancellationException();
987 if (s != EXCEPTIONAL)
988 throw new TimeoutException();
989 if ((ex = getThrowableException()) != null)
990 throw new ExecutionException(ex);
992 return getRawResult();
996 * Joins this task, without returning its result or throwing its
997 * exception. This method may be useful when processing
998 * collections of tasks when some have been cancelled or otherwise
999 * known to have aborted.
1001 public final void quietlyJoin() {
1006 * Commences performing this task and awaits its completion if
1007 * necessary, without returning its result or throwing its
1010 public final void quietlyInvoke() {
1015 * Possibly executes tasks until the pool hosting the current task
1016 * {@link ForkJoinPool#isQuiescent is quiescent}. This method may
1017 * be of use in designs in which many tasks are forked, but none
1018 * are explicitly joined, instead executing them until all are
1021 * <p>This method may be invoked only from within {@code
1022 * ForkJoinPool} computations (as may be determined using method
1023 * {@link #inForkJoinPool}). Attempts to invoke in other contexts
1024 * result in exceptions or errors, possibly including {@code
1025 * ClassCastException}.
1027 public static void helpQuiesce() {
1028 ((ForkJoinWorkerThread) Thread.currentThread())
1033 * Resets the internal bookkeeping state of this task, allowing a
1034 * subsequent {@code fork}. This method allows repeated reuse of
1035 * this task, but only if reuse occurs when this task has either
1036 * never been forked, or has been forked, then completed and all
1037 * outstanding joins of this task have also completed. Effects
1038 * under any other usage conditions are not guaranteed.
1039 * This method may be useful when executing
1040 * pre-constructed trees of subtasks in loops.
1042 * <p>Upon completion of this method, {@code isDone()} reports
1043 * {@code false}, and {@code getException()} reports {@code
1044 * null}. However, the value returned by {@code getRawResult} is
1045 * unaffected. To clear this value, you can invoke {@code
1046 * setRawResult(null)}.
1048 public void reinitialize() {
1049 if (status == EXCEPTIONAL)
1050 clearExceptionalCompletion();
1056 * Returns the pool hosting the current task execution, or null
1057 * if this task is executing outside of any ForkJoinPool.
1059 * @see #inForkJoinPool
1060 * @return the pool, or {@code null} if none
1062 public static ForkJoinPool getPool() {
1063 Thread t = Thread.currentThread();
1064 return (t instanceof ForkJoinWorkerThread) ?
1065 ((ForkJoinWorkerThread) t).pool : null;
1069 * Returns {@code true} if the current thread is a {@link
1070 * ForkJoinWorkerThread} executing as a ForkJoinPool computation.
1072 * @return {@code true} if the current thread is a {@link
1073 * ForkJoinWorkerThread} executing as a ForkJoinPool computation,
1074 * or {@code false} otherwise
1076 public static boolean inForkJoinPool() {
1077 return Thread.currentThread() instanceof ForkJoinWorkerThread;
1081 * Tries to unschedule this task for execution. This method will
1082 * typically succeed if this task is the most recently forked task
1083 * by the current thread, and has not commenced executing in
1084 * another thread. This method may be useful when arranging
1085 * alternative local processing of tasks that could have been, but
1088 * <p>This method may be invoked only from within {@code
1089 * ForkJoinPool} computations (as may be determined using method
1090 * {@link #inForkJoinPool}). Attempts to invoke in other contexts
1091 * result in exceptions or errors, possibly including {@code
1092 * ClassCastException}.
1094 * @return {@code true} if unforked
1096 public boolean tryUnfork() {
1097 return ((ForkJoinWorkerThread) Thread.currentThread())
1102 * Returns an estimate of the number of tasks that have been
1103 * forked by the current worker thread but not yet executed. This
1104 * value may be useful for heuristic decisions about whether to
1107 * <p>This method may be invoked only from within {@code
1108 * ForkJoinPool} computations (as may be determined using method
1109 * {@link #inForkJoinPool}). Attempts to invoke in other contexts
1110 * result in exceptions or errors, possibly including {@code
1111 * ClassCastException}.
1113 * @return the number of tasks
1115 public static int getQueuedTaskCount() {
1116 return ((ForkJoinWorkerThread) Thread.currentThread())
1121 * Returns an estimate of how many more locally queued tasks are
1122 * held by the current worker thread than there are other worker
1123 * threads that might steal them. This value may be useful for
1124 * heuristic decisions about whether to fork other tasks. In many
1125 * usages of ForkJoinTasks, at steady state, each worker should
1126 * aim to maintain a small constant surplus (for example, 3) of
1127 * tasks, and to process computations locally if this threshold is
1130 * <p>This method may be invoked only from within {@code
1131 * ForkJoinPool} computations (as may be determined using method
1132 * {@link #inForkJoinPool}). Attempts to invoke in other contexts
1133 * result in exceptions or errors, possibly including {@code
1134 * ClassCastException}.
1136 * @return the surplus number of tasks, which may be negative
1138 public static int getSurplusQueuedTaskCount() {
1139 return ((ForkJoinWorkerThread) Thread.currentThread())
1140 .getEstimatedSurplusTaskCount();
1143 // Extension methods
1146 * Returns the result that would be returned by {@link #join}, even
1147 * if this task completed abnormally, or {@code null} if this task
1148 * is not known to have been completed. This method is designed
1149 * to aid debugging, as well as to support extensions. Its use in
1150 * any other context is discouraged.
1152 * @return the result, or {@code null} if not completed
1154 public abstract V getRawResult();
1157 * Forces the given value to be returned as a result. This method
1158 * is designed to support extensions, and should not in general be
1161 * @param value the value
1163 protected abstract void setRawResult(V value);
1166 * Immediately performs the base action of this task. This method
1167 * is designed to support extensions, and should not in general be
1168 * called otherwise. The return value controls whether this task
1169 * is considered to be done normally. It may return false in
1170 * asynchronous actions that require explicit invocations of
1171 * {@link #complete} to become joinable. It may also throw an
1172 * (unchecked) exception to indicate abnormal exit.
1174 * @return {@code true} if completed normally
1176 protected abstract boolean exec();
1179 * Returns, but does not unschedule or execute, a task queued by
1180 * the current thread but not yet executed, if one is immediately
1181 * available. There is no guarantee that this task will actually
1182 * be polled or executed next. Conversely, this method may return
1183 * null even if a task exists but cannot be accessed without
1184 * contention with other threads. This method is designed
1185 * primarily to support extensions, and is unlikely to be useful
1188 * <p>This method may be invoked only from within {@code
1189 * ForkJoinPool} computations (as may be determined using method
1190 * {@link #inForkJoinPool}). Attempts to invoke in other contexts
1191 * result in exceptions or errors, possibly including {@code
1192 * ClassCastException}.
1194 * @return the next task, or {@code null} if none are available
1196 protected static ForkJoinTask<?> peekNextLocalTask() {
1197 return ((ForkJoinWorkerThread) Thread.currentThread())
1202 * Unschedules and returns, without executing, the next task
1203 * queued by the current thread but not yet executed. This method
1204 * is designed primarily to support extensions, and is unlikely to
1205 * be useful otherwise.
1207 * <p>This method may be invoked only from within {@code
1208 * ForkJoinPool} computations (as may be determined using method
1209 * {@link #inForkJoinPool}). Attempts to invoke in other contexts
1210 * result in exceptions or errors, possibly including {@code
1211 * ClassCastException}.
1213 * @return the next task, or {@code null} if none are available
1215 protected static ForkJoinTask<?> pollNextLocalTask() {
1216 return ((ForkJoinWorkerThread) Thread.currentThread())
1221 * Unschedules and returns, without executing, the next task
1222 * queued by the current thread but not yet executed, if one is
1223 * available, or if not available, a task that was forked by some
1224 * other thread, if available. Availability may be transient, so a
1225 * {@code null} result does not necessarily imply quiescence
1226 * of the pool this task is operating in. This method is designed
1227 * primarily to support extensions, and is unlikely to be useful
1230 * <p>This method may be invoked only from within {@code
1231 * ForkJoinPool} computations (as may be determined using method
1232 * {@link #inForkJoinPool}). Attempts to invoke in other contexts
1233 * result in exceptions or errors, possibly including {@code
1234 * ClassCastException}.
1236 * @return a task, or {@code null} if none are available
1238 protected static ForkJoinTask<?> pollTask() {
1239 return ((ForkJoinWorkerThread) Thread.currentThread())
1244 * Adaptor for Runnables. This implements RunnableFuture
1245 * to be compliant with AbstractExecutorService constraints
1246 * when used in ForkJoinPool.
1248 static final class AdaptedRunnable<T> extends ForkJoinTask<T>
1249 implements RunnableFuture<T> {
1250 final Runnable runnable;
1251 final T resultOnCompletion;
1253 AdaptedRunnable(Runnable runnable, T result) {
1254 if (runnable == null) throw new NullPointerException();
1255 this.runnable = runnable;
1256 this.resultOnCompletion = result;
1258 public T getRawResult() { return result; }
1259 public void setRawResult(T v) { result = v; }
1260 public boolean exec() {
1262 result = resultOnCompletion;
1265 public void run() { invoke(); }
1266 private static final long serialVersionUID = 5232453952276885070L;
1270 * Adaptor for Callables
1272 static final class AdaptedCallable<T> extends ForkJoinTask<T>
1273 implements RunnableFuture<T> {
1274 final Callable<? extends T> callable;
1276 AdaptedCallable(Callable<? extends T> callable) {
1277 if (callable == null) throw new NullPointerException();
1278 this.callable = callable;
1280 public T getRawResult() { return result; }
1281 public void setRawResult(T v) { result = v; }
1282 public boolean exec() {
1284 result = callable.call();
1286 } catch (Error err) {
1288 } catch (RuntimeException rex) {
1290 } catch (Exception ex) {
1291 throw new RuntimeException(ex);
1294 public void run() { invoke(); }
1295 private static final long serialVersionUID = 2838392045355241008L;
1299 * Returns a new {@code ForkJoinTask} that performs the {@code run}
1300 * method of the given {@code Runnable} as its action, and returns
1301 * a null result upon {@link #join}.
1303 * @param runnable the runnable action
1306 public static ForkJoinTask<?> adapt(Runnable runnable) {
1307 return new AdaptedRunnable<Void>(runnable, null);
1311 * Returns a new {@code ForkJoinTask} that performs the {@code run}
1312 * method of the given {@code Runnable} as its action, and returns
1313 * the given result upon {@link #join}.
1315 * @param runnable the runnable action
1316 * @param result the result upon completion
1319 public static <T> ForkJoinTask<T> adapt(Runnable runnable, T result) {
1320 return new AdaptedRunnable<T>(runnable, result);
1324 * Returns a new {@code ForkJoinTask} that performs the {@code call}
1325 * method of the given {@code Callable} as its action, and returns
1326 * its result upon {@link #join}, translating any checked exceptions
1327 * encountered into {@code RuntimeException}.
1329 * @param callable the callable action
1332 public static <T> ForkJoinTask<T> adapt(Callable<? extends T> callable) {
1333 return new AdaptedCallable<T>(callable);
1336 // Serialization support
1338 private static final long serialVersionUID = -7721805057305804111L;
1341 * Saves the state to a stream (that is, serializes it).
1343 * @serialData the current run status and the exception thrown
1344 * during execution, or {@code null} if none
1345 * @param s the stream
1347 private void writeObject(java.io.ObjectOutputStream s)
1348 throws java.io.IOException {
1349 s.defaultWriteObject();
1350 s.writeObject(getException());
1354 * Reconstitutes the instance from a stream (that is, deserializes it).
1356 * @param s the stream
1358 private void readObject(java.io.ObjectInputStream s)
1359 throws java.io.IOException, ClassNotFoundException {
1360 s.defaultReadObject();
1361 Object ex = s.readObject();
1363 setExceptionalCompletion((Throwable)ex);
1367 private static final Unsafe UNSAFE;
1368 private static final long statusOffset;
1370 exceptionTableLock = new ReentrantLock();
1371 exceptionTableRefQueue = new ReferenceQueue<Object>();
1372 exceptionTable = new ExceptionNode[EXCEPTION_MAP_CAPACITY];
1374 UNSAFE = Unsafe.getUnsafe();
1375 statusOffset = UNSAFE.objectFieldOffset
1376 (ForkJoinTask.class.getDeclaredField("status"));
1377 } catch (Exception e) {