ForkJoinTask.java revision 2805
1771N/A/*
1771N/A * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
1771N/A *
1771N/A * This code is free software; you can redistribute it and/or modify it
1771N/A * under the terms of the GNU General Public License version 2 only, as
2362N/A * published by the Free Software Foundation. Oracle designates this
1771N/A * particular file as subject to the "Classpath" exception as provided
2362N/A * by Oracle in the LICENSE file that accompanied this code.
1771N/A *
1771N/A * This code is distributed in the hope that it will be useful, but WITHOUT
1771N/A * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
1771N/A * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
1771N/A * version 2 for more details (a copy is included in the LICENSE file that
1771N/A * accompanied this code).
1771N/A *
1771N/A * You should have received a copy of the GNU General Public License version
1771N/A * 2 along with this work; if not, write to the Free Software Foundation,
1771N/A * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
1771N/A *
2362N/A * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
2362N/A * or visit www.oracle.com if you need additional information or have any
2362N/A * questions.
1771N/A */
1771N/A
1771N/A/*
1771N/A * This file is available under and governed by the GNU General Public
1771N/A * License version 2 only, as published by the Free Software Foundation.
1771N/A * However, the following notice accompanied the original version of this
1771N/A * file:
1771N/A *
1771N/A * Written by Doug Lea with assistance from members of JCP JSR-166
1771N/A * Expert Group and released to the public domain, as explained at
1771N/A * http://creativecommons.org/licenses/publicdomain
1771N/A */
1771N/A
1771N/Apackage java.util.concurrent;
1771N/A
1771N/Aimport java.io.Serializable;
1771N/Aimport java.util.Collection;
1771N/Aimport java.util.Collections;
1771N/Aimport java.util.List;
1771N/Aimport java.util.RandomAccess;
1771N/Aimport java.util.Map;
1771N/Aimport java.util.WeakHashMap;
1771N/A
1771N/A/**
1771N/A * Abstract base class for tasks that run within a {@link ForkJoinPool}.
1771N/A * A {@code ForkJoinTask} is a thread-like entity that is much
1771N/A * lighter weight than a normal thread. Huge numbers of tasks and
1771N/A * subtasks may be hosted by a small number of actual threads in a
1771N/A * ForkJoinPool, at the price of some usage limitations.
1771N/A *
1771N/A * <p>A "main" {@code ForkJoinTask} begins execution when submitted
1771N/A * to a {@link ForkJoinPool}. Once started, it will usually in turn
1771N/A * start other subtasks. As indicated by the name of this class,
1771N/A * many programs using {@code ForkJoinTask} employ only methods
1771N/A * {@link #fork} and {@link #join}, or derivatives such as {@link
2805N/A * #invokeAll(ForkJoinTask...) invokeAll}. However, this class also
2805N/A * provides a number of other methods that can come into play in
2805N/A * advanced usages, as well as extension mechanics that allow
2805N/A * support of new forms of fork/join processing.
1771N/A *
1771N/A * <p>A {@code ForkJoinTask} is a lightweight form of {@link Future}.
1771N/A * The efficiency of {@code ForkJoinTask}s stems from a set of
1771N/A * restrictions (that are only partially statically enforceable)
1771N/A * reflecting their intended use as computational tasks calculating
1771N/A * pure functions or operating on purely isolated objects. The
1771N/A * primary coordination mechanisms are {@link #fork}, that arranges
1771N/A * asynchronous execution, and {@link #join}, that doesn't proceed
1771N/A * until the task's result has been computed. Computations should
1771N/A * avoid {@code synchronized} methods or blocks, and should minimize
1771N/A * other blocking synchronization apart from joining other tasks or
1771N/A * using synchronizers such as Phasers that are advertised to
1771N/A * cooperate with fork/join scheduling. Tasks should also not perform
1771N/A * blocking IO, and should ideally access variables that are
1771N/A * completely independent of those accessed by other running
1771N/A * tasks. Minor breaches of these restrictions, for example using
1771N/A * shared output streams, may be tolerable in practice, but frequent
1771N/A * use may result in poor performance, and the potential to
1771N/A * indefinitely stall if the number of threads not waiting for IO or
1771N/A * other external synchronization becomes exhausted. This usage
1771N/A * restriction is in part enforced by not permitting checked
1771N/A * exceptions such as {@code IOExceptions} to be thrown. However,
1771N/A * computations may still encounter unchecked exceptions, that are
1771N/A * rethrown to callers attempting to join them. These exceptions may
1771N/A * additionally include {@link RejectedExecutionException} stemming
1771N/A * from internal resource exhaustion, such as failure to allocate
1771N/A * internal task queues.
1771N/A *
1771N/A * <p>The primary method for awaiting completion and extracting
1771N/A * results of a task is {@link #join}, but there are several variants:
1771N/A * The {@link Future#get} methods support interruptible and/or timed
1771N/A * waits for completion and report results using {@code Future}
2754N/A * conventions. Method {@link #invoke} is semantically
1771N/A * equivalent to {@code fork(); join()} but always attempts to begin
1771N/A * execution in the current thread. The "<em>quiet</em>" forms of
1771N/A * these methods do not extract results or report exceptions. These
1771N/A * may be useful when a set of tasks are being executed, and you need
1771N/A * to delay processing of results or exceptions until all complete.
1771N/A * Method {@code invokeAll} (available in multiple versions)
1771N/A * performs the most common form of parallel invocation: forking a set
1771N/A * of tasks and joining them all.
1771N/A *
1771N/A * <p>The execution status of tasks may be queried at several levels
1771N/A * of detail: {@link #isDone} is true if a task completed in any way
1771N/A * (including the case where a task was cancelled without executing);
1771N/A * {@link #isCompletedNormally} is true if a task completed without
1771N/A * cancellation or encountering an exception; {@link #isCancelled} is
1771N/A * true if the task was cancelled (in which case {@link #getException}
1771N/A * returns a {@link java.util.concurrent.CancellationException}); and
1771N/A * {@link #isCompletedAbnormally} is true if a task was either
1771N/A * cancelled or encountered an exception, in which case {@link
1771N/A * #getException} will return either the encountered exception or
1771N/A * {@link java.util.concurrent.CancellationException}.
1771N/A *
1771N/A * <p>The ForkJoinTask class is not usually directly subclassed.
1771N/A * Instead, you subclass one of the abstract classes that support a
1771N/A * particular style of fork/join processing, typically {@link
1771N/A * RecursiveAction} for computations that do not return results, or
1771N/A * {@link RecursiveTask} for those that do. Normally, a concrete
1771N/A * ForkJoinTask subclass declares fields comprising its parameters,
1771N/A * established in a constructor, and then defines a {@code compute}
1771N/A * method that somehow uses the control methods supplied by this base
1771N/A * class. While these methods have {@code public} access (to allow
1771N/A * instances of different task subclasses to call each other's
1771N/A * methods), some of them may only be called from within other
1771N/A * ForkJoinTasks (as may be determined using method {@link
1771N/A * #inForkJoinPool}). Attempts to invoke them in other contexts
1771N/A * result in exceptions or errors, possibly including
2754N/A * {@code ClassCastException}.
1771N/A *
1771N/A * <p>Most base support methods are {@code final}, to prevent
1771N/A * overriding of implementations that are intrinsically tied to the
1771N/A * underlying lightweight task scheduling framework. Developers
1771N/A * creating new basic styles of fork/join processing should minimally
1771N/A * implement {@code protected} methods {@link #exec}, {@link
1771N/A * #setRawResult}, and {@link #getRawResult}, while also introducing
1771N/A * an abstract computational method that can be implemented in its
1771N/A * subclasses, possibly relying on other {@code protected} methods
1771N/A * provided by this class.
1771N/A *
1771N/A * <p>ForkJoinTasks should perform relatively small amounts of
1771N/A * computation. Large tasks should be split into smaller subtasks,
1771N/A * usually via recursive decomposition. As a very rough rule of thumb,
1771N/A * a task should perform more than 100 and less than 10000 basic
1771N/A * computational steps. If tasks are too big, then parallelism cannot
1771N/A * improve throughput. If too small, then memory and internal task
1771N/A * maintenance overhead may overwhelm processing.
1771N/A *
1771N/A * <p>This class provides {@code adapt} methods for {@link Runnable}
1771N/A * and {@link Callable}, that may be of use when mixing execution of
2754N/A * {@code ForkJoinTasks} with other kinds of tasks. When all tasks are
2754N/A * of this form, consider using a pool constructed in <em>asyncMode</em>.
1771N/A *
1771N/A * <p>ForkJoinTasks are {@code Serializable}, which enables them to be
1771N/A * used in extensions such as remote execution frameworks. It is
1771N/A * sensible to serialize tasks only before or after, but not during,
1771N/A * execution. Serialization is not relied on during execution itself.
1771N/A *
1771N/A * @since 1.7
1771N/A * @author Doug Lea
1771N/A */
1771N/Apublic abstract class ForkJoinTask<V> implements Future<V>, Serializable {
1771N/A
2754N/A /*
2754N/A * See the internal documentation of class ForkJoinPool for a
2754N/A * general implementation overview. ForkJoinTasks are mainly
2754N/A * responsible for maintaining their "status" field amidst relays
2754N/A * to methods in ForkJoinWorkerThread and ForkJoinPool. The
2754N/A * methods of this class are more-or-less layered into (1) basic
2754N/A * status maintenance (2) execution and awaiting completion (3)
2754N/A * user-level methods that additionally report results. This is
2754N/A * sometimes hard to see because this file orders exported methods
2754N/A * in a way that flows well in javadocs. In particular, most
2754N/A * join mechanics are in method quietlyJoin, below.
1771N/A */
2754N/A
2754N/A /*
2754N/A * The status field holds run control status bits packed into a
2754N/A * single int to minimize footprint and to ensure atomicity (via
2754N/A * CAS). Status is initially zero, and takes on nonnegative
2754N/A * values until completed, upon which status holds value
2754N/A * NORMAL, CANCELLED, or EXCEPTIONAL. Tasks undergoing blocking
2754N/A * waits by other threads have the SIGNAL bit set. Completion of
2754N/A * a stolen task with SIGNAL set awakens any waiters via
2754N/A * notifyAll. Even though suboptimal for some purposes, we use
2754N/A * basic builtin wait/notify to take advantage of "monitor
2754N/A * inflation" in JVMs that we would otherwise need to emulate to
2754N/A * avoid adding further per-task bookkeeping overhead. We want
2754N/A * these monitors to be "fat", i.e., not use biasing or thin-lock
2754N/A * techniques, so use some odd coding idioms that tend to avoid
2754N/A * them.
2754N/A */
2754N/A
2754N/A /** The run status of this task */
1771N/A volatile int status; // accessed directly by pool and workers
1771N/A
2754N/A private static final int NORMAL = -1;
2754N/A private static final int CANCELLED = -2;
2754N/A private static final int EXCEPTIONAL = -3;
2754N/A private static final int SIGNAL = 1;
1771N/A
1771N/A /**
1771N/A * Table of exceptions thrown by tasks, to enable reporting by
1771N/A * callers. Because exceptions are rare, we don't directly keep
1771N/A * them with task objects, but instead use a weak ref table. Note
1771N/A * that cancellation exceptions don't appear in the table, but are
1771N/A * instead recorded as status values.
1771N/A * TODO: Use ConcurrentReferenceHashMap
1771N/A */
1771N/A static final Map<ForkJoinTask<?>, Throwable> exceptionMap =
1771N/A Collections.synchronizedMap
1771N/A (new WeakHashMap<ForkJoinTask<?>, Throwable>());
1771N/A
2754N/A // Maintaining completion status
1771N/A
1771N/A /**
2754N/A * Marks completion and wakes up threads waiting to join this task,
2754N/A * also clearing signal request bits.
1771N/A *
1771N/A * @param completion one of NORMAL, CANCELLED, EXCEPTIONAL
1771N/A */
2754N/A private void setCompletion(int completion) {
1771N/A int s;
2754N/A while ((s = status) >= 0) {
2754N/A if (UNSAFE.compareAndSwapInt(this, statusOffset, s, completion)) {
2754N/A if (s != 0)
2754N/A synchronized (this) { notifyAll(); }
2754N/A break;
2754N/A }
1771N/A }
1771N/A }
1771N/A
1771N/A /**
2754N/A * Records exception and sets exceptional completion.
2754N/A *
2754N/A * @return status on exit
1771N/A */
2754N/A private void setExceptionalCompletion(Throwable rex) {
2754N/A exceptionMap.put(this, rex);
2754N/A setCompletion(EXCEPTIONAL);
2754N/A }
2754N/A
2754N/A /**
2754N/A * Blocks a worker thread until completion. Called only by
2754N/A * pool. Currently unused -- pool-based waits use timeout
2754N/A * version below.
2754N/A */
2754N/A final void internalAwaitDone() {
2754N/A int s; // the odd construction reduces lock bias effects
2754N/A while ((s = status) >= 0) {
1771N/A try {
2805N/A synchronized (this) {
2754N/A if (UNSAFE.compareAndSwapInt(this, statusOffset, s,SIGNAL))
2754N/A wait();
1771N/A }
1771N/A } catch (InterruptedException ie) {
2754N/A cancelIfTerminating();
1771N/A }
1771N/A }
1771N/A }
1771N/A
1771N/A /**
2754N/A * Blocks a worker thread until completed or timed out. Called
2754N/A * only by pool.
1771N/A *
2754N/A * @return status on exit
1771N/A */
2754N/A final int internalAwaitDone(long millis) {
1771N/A int s;
2754N/A if ((s = status) >= 0) {
2754N/A try {
2805N/A synchronized (this) {
2754N/A if (UNSAFE.compareAndSwapInt(this, statusOffset, s,SIGNAL))
2754N/A wait(millis, 0);
2754N/A }
2754N/A } catch (InterruptedException ie) {
2754N/A cancelIfTerminating();
1771N/A }
2754N/A s = status;
1771N/A }
1771N/A return s;
1771N/A }
1771N/A
1771N/A /**
2754N/A * Blocks a non-worker-thread until completion.
1771N/A */
2754N/A private void externalAwaitDone() {
1771N/A int s;
1771N/A while ((s = status) >= 0) {
2805N/A synchronized (this) {
2754N/A if (UNSAFE.compareAndSwapInt(this, statusOffset, s, SIGNAL)){
2754N/A boolean interrupted = false;
2754N/A while (status >= 0) {
2754N/A try {
2754N/A wait();
2754N/A } catch (InterruptedException ie) {
2754N/A interrupted = true;
2754N/A }
2754N/A }
2754N/A if (interrupted)
2754N/A Thread.currentThread().interrupt();
1771N/A break;
1771N/A }
1771N/A }
1771N/A }
1771N/A }
1771N/A
1771N/A /**
2754N/A * Unless done, calls exec and records status if completed, but
2754N/A * doesn't wait for completion otherwise. Primary execution method
2754N/A * for ForkJoinWorkerThread.
1771N/A */
1771N/A final void quietlyExec() {
2754N/A try {
2754N/A if (status < 0 || !exec())
1771N/A return;
1771N/A } catch (Throwable rex) {
2754N/A setExceptionalCompletion(rex);
2754N/A return;
1771N/A }
2754N/A setCompletion(NORMAL); // must be outside try block
1771N/A }
1771N/A
1771N/A // public methods
1771N/A
1771N/A /**
1771N/A * Arranges to asynchronously execute this task. While it is not
1771N/A * necessarily enforced, it is a usage error to fork a task more
1771N/A * than once unless it has completed and been reinitialized.
1771N/A * Subsequent modifications to the state of this task or any data
1771N/A * it operates on are not necessarily consistently observable by
1771N/A * any thread other than the one executing it unless preceded by a
1771N/A * call to {@link #join} or related methods, or a call to {@link
1771N/A * #isDone} returning {@code true}.
1771N/A *
1771N/A * <p>This method may be invoked only from within {@code
1771N/A * ForkJoinTask} computations (as may be determined using method
1771N/A * {@link #inForkJoinPool}). Attempts to invoke in other contexts
1771N/A * result in exceptions or errors, possibly including {@code
1771N/A * ClassCastException}.
1771N/A *
1771N/A * @return {@code this}, to simplify usage
1771N/A */
1771N/A public final ForkJoinTask<V> fork() {
1771N/A ((ForkJoinWorkerThread) Thread.currentThread())
1771N/A .pushTask(this);
1771N/A return this;
1771N/A }
1771N/A
1771N/A /**
1771N/A * Returns the result of the computation when it {@link #isDone is done}.
1771N/A * This method differs from {@link #get()} in that
1771N/A * abnormal completion results in {@code RuntimeException} or
1771N/A * {@code Error}, not {@code ExecutionException}.
1771N/A *
1771N/A * @return the computed result
1771N/A */
1771N/A public final V join() {
2754N/A quietlyJoin();
2754N/A Throwable ex;
2754N/A if (status < NORMAL && (ex = getException()) != null)
2754N/A UNSAFE.throwException(ex);
1771N/A return getRawResult();
1771N/A }
1771N/A
1771N/A /**
1771N/A * Commences performing this task, awaits its completion if
2754N/A * necessary, and returns its result, or throws an (unchecked)
2754N/A * {@code RuntimeException} or {@code Error} if the underlying
2754N/A * computation did so.
1771N/A *
1771N/A * @return the computed result
1771N/A */
1771N/A public final V invoke() {
2754N/A quietlyInvoke();
2754N/A Throwable ex;
2754N/A if (status < NORMAL && (ex = getException()) != null)
2754N/A UNSAFE.throwException(ex);
2754N/A return getRawResult();
1771N/A }
1771N/A
1771N/A /**
1771N/A * Forks the given tasks, returning when {@code isDone} holds for
1771N/A * each task or an (unchecked) exception is encountered, in which
2754N/A * case the exception is rethrown. If more than one task
2754N/A * encounters an exception, then this method throws any one of
2754N/A * these exceptions. If any task encounters an exception, the
2754N/A * other may be cancelled. However, the execution status of
2754N/A * individual tasks is not guaranteed upon exceptional return. The
2754N/A * status of each task may be obtained using {@link
2754N/A * #getException()} and related methods to check if they have been
2754N/A * cancelled, completed normally or exceptionally, or left
2754N/A * unprocessed.
1771N/A *
1771N/A * <p>This method may be invoked only from within {@code
1771N/A * ForkJoinTask} computations (as may be determined using method
1771N/A * {@link #inForkJoinPool}). Attempts to invoke in other contexts
1771N/A * result in exceptions or errors, possibly including {@code
1771N/A * ClassCastException}.
1771N/A *
1771N/A * @param t1 the first task
1771N/A * @param t2 the second task
1771N/A * @throws NullPointerException if any task is null
1771N/A */
1771N/A public static void invokeAll(ForkJoinTask<?> t1, ForkJoinTask<?> t2) {
1771N/A t2.fork();
1771N/A t1.invoke();
1771N/A t2.join();
1771N/A }
1771N/A
1771N/A /**
1771N/A * Forks the given tasks, returning when {@code isDone} holds for
1771N/A * each task or an (unchecked) exception is encountered, in which
2754N/A * case the exception is rethrown. If more than one task
2754N/A * encounters an exception, then this method throws any one of
2754N/A * these exceptions. If any task encounters an exception, others
2754N/A * may be cancelled. However, the execution status of individual
2754N/A * tasks is not guaranteed upon exceptional return. The status of
2754N/A * each task may be obtained using {@link #getException()} and
2754N/A * related methods to check if they have been cancelled, completed
2754N/A * normally or exceptionally, or left unprocessed.
1771N/A *
1771N/A * <p>This method may be invoked only from within {@code
1771N/A * ForkJoinTask} computations (as may be determined using method
1771N/A * {@link #inForkJoinPool}). Attempts to invoke in other contexts
1771N/A * result in exceptions or errors, possibly including {@code
1771N/A * ClassCastException}.
1771N/A *
1771N/A * @param tasks the tasks
1771N/A * @throws NullPointerException if any task is null
1771N/A */
1771N/A public static void invokeAll(ForkJoinTask<?>... tasks) {
1771N/A Throwable ex = null;
1771N/A int last = tasks.length - 1;
1771N/A for (int i = last; i >= 0; --i) {
1771N/A ForkJoinTask<?> t = tasks[i];
1771N/A if (t == null) {
1771N/A if (ex == null)
1771N/A ex = new NullPointerException();
1771N/A }
1771N/A else if (i != 0)
1771N/A t.fork();
1771N/A else {
1771N/A t.quietlyInvoke();
2754N/A if (ex == null && t.status < NORMAL)
1771N/A ex = t.getException();
1771N/A }
1771N/A }
1771N/A for (int i = 1; i <= last; ++i) {
1771N/A ForkJoinTask<?> t = tasks[i];
1771N/A if (t != null) {
1771N/A if (ex != null)
1771N/A t.cancel(false);
1771N/A else {
1771N/A t.quietlyJoin();
2754N/A if (ex == null && t.status < NORMAL)
1771N/A ex = t.getException();
1771N/A }
1771N/A }
1771N/A }
1771N/A if (ex != null)
2754N/A UNSAFE.throwException(ex);
1771N/A }
1771N/A
1771N/A /**
1771N/A * Forks all tasks in the specified collection, returning when
1771N/A * {@code isDone} holds for each task or an (unchecked) exception
2754N/A * is encountered, in which case the exception is rethrown. If
2754N/A * more than one task encounters an exception, then this method
2754N/A * throws any one of these exceptions. If any task encounters an
2754N/A * exception, others may be cancelled. However, the execution
2754N/A * status of individual tasks is not guaranteed upon exceptional
2754N/A * return. The status of each task may be obtained using {@link
2754N/A * #getException()} and related methods to check if they have been
2754N/A * cancelled, completed normally or exceptionally, or left
2754N/A * unprocessed.
1771N/A *
1771N/A * <p>This method may be invoked only from within {@code
1771N/A * ForkJoinTask} computations (as may be determined using method
1771N/A * {@link #inForkJoinPool}). Attempts to invoke in other contexts
1771N/A * result in exceptions or errors, possibly including {@code
1771N/A * ClassCastException}.
1771N/A *
1771N/A * @param tasks the collection of tasks
1771N/A * @return the tasks argument, to simplify usage
1771N/A * @throws NullPointerException if tasks or any element are null
1771N/A */
1771N/A public static <T extends ForkJoinTask<?>> Collection<T> invokeAll(Collection<T> tasks) {
1771N/A if (!(tasks instanceof RandomAccess) || !(tasks instanceof List<?>)) {
1771N/A invokeAll(tasks.toArray(new ForkJoinTask<?>[tasks.size()]));
1771N/A return tasks;
1771N/A }
1771N/A @SuppressWarnings("unchecked")
1771N/A List<? extends ForkJoinTask<?>> ts =
1771N/A (List<? extends ForkJoinTask<?>>) tasks;
1771N/A Throwable ex = null;
1771N/A int last = ts.size() - 1;
1771N/A for (int i = last; i >= 0; --i) {
1771N/A ForkJoinTask<?> t = ts.get(i);
1771N/A if (t == null) {
1771N/A if (ex == null)
1771N/A ex = new NullPointerException();
1771N/A }
1771N/A else if (i != 0)
1771N/A t.fork();
1771N/A else {
1771N/A t.quietlyInvoke();
2754N/A if (ex == null && t.status < NORMAL)
1771N/A ex = t.getException();
1771N/A }
1771N/A }
1771N/A for (int i = 1; i <= last; ++i) {
1771N/A ForkJoinTask<?> t = ts.get(i);
1771N/A if (t != null) {
1771N/A if (ex != null)
1771N/A t.cancel(false);
1771N/A else {
1771N/A t.quietlyJoin();
2754N/A if (ex == null && t.status < NORMAL)
1771N/A ex = t.getException();
1771N/A }
1771N/A }
1771N/A }
1771N/A if (ex != null)
2754N/A UNSAFE.throwException(ex);
1771N/A return tasks;
1771N/A }
1771N/A
1771N/A /**
1771N/A * Attempts to cancel execution of this task. This attempt will
1771N/A * fail if the task has already completed, has already been
1771N/A * cancelled, or could not be cancelled for some other reason. If
1771N/A * successful, and this task has not started when cancel is
1771N/A * called, execution of this task is suppressed, {@link
1771N/A * #isCancelled} will report true, and {@link #join} will result
1771N/A * in a {@code CancellationException} being thrown.
1771N/A *
1771N/A * <p>This method may be overridden in subclasses, but if so, must
1771N/A * still ensure that these minimal properties hold. In particular,
1771N/A * the {@code cancel} method itself must not throw exceptions.
1771N/A *
1771N/A * <p>This method is designed to be invoked by <em>other</em>
1771N/A * tasks. To terminate the current task, you can just return or
1771N/A * throw an unchecked exception from its computation method, or
1771N/A * invoke {@link #completeExceptionally}.
1771N/A *
1771N/A * @param mayInterruptIfRunning this value is ignored in the
1771N/A * default implementation because tasks are not
1771N/A * cancelled via interruption
1771N/A *
1771N/A * @return {@code true} if this task is now cancelled
1771N/A */
1771N/A public boolean cancel(boolean mayInterruptIfRunning) {
1771N/A setCompletion(CANCELLED);
2754N/A return status == CANCELLED;
2754N/A }
2754N/A
2754N/A /**
2754N/A * Cancels, ignoring any exceptions thrown by cancel. Used during
2754N/A * worker and pool shutdown. Cancel is spec'ed not to throw any
2754N/A * exceptions, but if it does anyway, we have no recourse during
2754N/A * shutdown, so guard against this case.
2754N/A */
2754N/A final void cancelIgnoringExceptions() {
2754N/A try {
2754N/A cancel(false);
2754N/A } catch (Throwable ignore) {
2754N/A }
2754N/A }
2754N/A
2754N/A /**
2754N/A * Cancels if current thread is a terminating worker thread,
2754N/A * ignoring any exceptions thrown by cancel.
2754N/A */
2754N/A final void cancelIfTerminating() {
2754N/A Thread t = Thread.currentThread();
2754N/A if ((t instanceof ForkJoinWorkerThread) &&
2754N/A ((ForkJoinWorkerThread) t).isTerminating()) {
2754N/A try {
2754N/A cancel(false);
2754N/A } catch (Throwable ignore) {
2754N/A }
2754N/A }
1771N/A }
1771N/A
1771N/A public final boolean isDone() {
1771N/A return status < 0;
1771N/A }
1771N/A
1771N/A public final boolean isCancelled() {
2754N/A return status == CANCELLED;
1771N/A }
1771N/A
1771N/A /**
1771N/A * Returns {@code true} if this task threw an exception or was cancelled.
1771N/A *
1771N/A * @return {@code true} if this task threw an exception or was cancelled
1771N/A */
1771N/A public final boolean isCompletedAbnormally() {
2754N/A return status < NORMAL;
1771N/A }
1771N/A
1771N/A /**
1771N/A * Returns {@code true} if this task completed without throwing an
1771N/A * exception and was not cancelled.
1771N/A *
1771N/A * @return {@code true} if this task completed without throwing an
1771N/A * exception and was not cancelled
1771N/A */
1771N/A public final boolean isCompletedNormally() {
2754N/A return status == NORMAL;
1771N/A }
1771N/A
1771N/A /**
1771N/A * Returns the exception thrown by the base computation, or a
1771N/A * {@code CancellationException} if cancelled, or {@code null} if
1771N/A * none or if the method has not yet completed.
1771N/A *
1771N/A * @return the exception, or {@code null} if none
1771N/A */
1771N/A public final Throwable getException() {
2754N/A int s = status;
1771N/A return ((s >= NORMAL) ? null :
1771N/A (s == CANCELLED) ? new CancellationException() :
1771N/A exceptionMap.get(this));
1771N/A }
1771N/A
1771N/A /**
1771N/A * Completes this task abnormally, and if not already aborted or
1771N/A * cancelled, causes it to throw the given exception upon
1771N/A * {@code join} and related operations. This method may be used
1771N/A * to induce exceptions in asynchronous tasks, or to force
1771N/A * completion of tasks that would not otherwise complete. Its use
1771N/A * in other situations is discouraged. This method is
1771N/A * overridable, but overridden versions must invoke {@code super}
1771N/A * implementation to maintain guarantees.
1771N/A *
1771N/A * @param ex the exception to throw. If this exception is not a
1771N/A * {@code RuntimeException} or {@code Error}, the actual exception
1771N/A * thrown will be a {@code RuntimeException} with cause {@code ex}.
1771N/A */
1771N/A public void completeExceptionally(Throwable ex) {
2754N/A setExceptionalCompletion((ex instanceof RuntimeException) ||
2754N/A (ex instanceof Error) ? ex :
2754N/A new RuntimeException(ex));
1771N/A }
1771N/A
1771N/A /**
1771N/A * Completes this task, and if not already aborted or cancelled,
2754N/A * returning the given value as the result of subsequent
2754N/A * invocations of {@code join} and related operations. This method
2754N/A * may be used to provide results for asynchronous tasks, or to
2754N/A * provide alternative handling for tasks that would not otherwise
2754N/A * complete normally. Its use in other situations is
2754N/A * discouraged. This method is overridable, but overridden
2754N/A * versions must invoke {@code super} implementation to maintain
2754N/A * guarantees.
1771N/A *
1771N/A * @param value the result value for this task
1771N/A */
1771N/A public void complete(V value) {
1771N/A try {
1771N/A setRawResult(value);
1771N/A } catch (Throwable rex) {
2754N/A setExceptionalCompletion(rex);
1771N/A return;
1771N/A }
2754N/A setCompletion(NORMAL);
1771N/A }
1771N/A
2805N/A /**
2805N/A * Waits if necessary for the computation to complete, and then
2805N/A * retrieves its result.
2805N/A *
2805N/A * @return the computed result
2805N/A * @throws CancellationException if the computation was cancelled
2805N/A * @throws ExecutionException if the computation threw an
2805N/A * exception
2805N/A * @throws InterruptedException if the current thread is not a
2805N/A * member of a ForkJoinPool and was interrupted while waiting
2805N/A */
1771N/A public final V get() throws InterruptedException, ExecutionException {
2805N/A int s;
2805N/A if (Thread.currentThread() instanceof ForkJoinWorkerThread) {
2805N/A quietlyJoin();
2805N/A s = status;
2805N/A }
2805N/A else {
2805N/A while ((s = status) >= 0) {
2805N/A synchronized (this) { // interruptible form of awaitDone
2805N/A if (UNSAFE.compareAndSwapInt(this, statusOffset,
2805N/A s, SIGNAL)) {
2805N/A while (status >= 0)
2805N/A wait();
2805N/A }
2805N/A }
2805N/A }
2805N/A }
2754N/A if (s < NORMAL) {
2754N/A Throwable ex;
2754N/A if (s == CANCELLED)
2754N/A throw new CancellationException();
2754N/A if (s == EXCEPTIONAL && (ex = exceptionMap.get(this)) != null)
2754N/A throw new ExecutionException(ex);
2754N/A }
2754N/A return getRawResult();
1771N/A }
1771N/A
2805N/A /**
2805N/A * Waits if necessary for at most the given time for the computation
2805N/A * to complete, and then retrieves its result, if available.
2805N/A *
2805N/A * @param timeout the maximum time to wait
2805N/A * @param unit the time unit of the timeout argument
2805N/A * @return the computed result
2805N/A * @throws CancellationException if the computation was cancelled
2805N/A * @throws ExecutionException if the computation threw an
2805N/A * exception
2805N/A * @throws InterruptedException if the current thread is not a
2805N/A * member of a ForkJoinPool and was interrupted while waiting
2805N/A * @throws TimeoutException if the wait timed out
2805N/A */
1771N/A public final V get(long timeout, TimeUnit unit)
1771N/A throws InterruptedException, ExecutionException, TimeoutException {
2754N/A Thread t = Thread.currentThread();
2754N/A ForkJoinPool pool;
2754N/A if (t instanceof ForkJoinWorkerThread) {
2754N/A ForkJoinWorkerThread w = (ForkJoinWorkerThread) t;
2754N/A if (status >= 0 && w.unpushTask(this))
2754N/A quietlyExec();
2754N/A pool = w.pool;
2754N/A }
2754N/A else
2754N/A pool = null;
2754N/A /*
2754N/A * Timed wait loop intermixes cases for FJ (pool != null) and
2754N/A * non FJ threads. For FJ, decrement pool count but don't try
2754N/A * for replacement; increment count on completion. For non-FJ,
2754N/A * deal with interrupts. This is messy, but a little less so
2754N/A * than is splitting the FJ and nonFJ cases.
2754N/A */
2754N/A boolean interrupted = false;
2754N/A boolean dec = false; // true if pool count decremented
1771N/A long nanos = unit.toNanos(timeout);
2754N/A for (;;) {
2754N/A if (pool == null && Thread.interrupted()) {
2754N/A interrupted = true;
2754N/A break;
2754N/A }
2754N/A int s = status;
2754N/A if (s < 0)
2754N/A break;
2754N/A if (UNSAFE.compareAndSwapInt(this, statusOffset, s, SIGNAL)) {
2754N/A long startTime = System.nanoTime();
2754N/A long nt; // wait time
2754N/A while (status >= 0 &&
2754N/A (nt = nanos - (System.nanoTime() - startTime)) > 0) {
2754N/A if (pool != null && !dec)
2754N/A dec = pool.tryDecrementRunningCount();
2754N/A else {
2754N/A long ms = nt / 1000000;
2754N/A int ns = (int) (nt % 1000000);
2754N/A try {
2805N/A synchronized (this) {
2754N/A if (status >= 0)
2754N/A wait(ms, ns);
2754N/A }
2754N/A } catch (InterruptedException ie) {
2754N/A if (pool != null)
2754N/A cancelIfTerminating();
2754N/A else {
2754N/A interrupted = true;
2754N/A break;
2754N/A }
2754N/A }
2754N/A }
2754N/A }
2754N/A break;
2754N/A }
2754N/A }
2754N/A if (pool != null && dec)
2754N/A pool.incrementRunningCount();
2754N/A if (interrupted)
2754N/A throw new InterruptedException();
2754N/A int es = status;
2754N/A if (es != NORMAL) {
2754N/A Throwable ex;
2754N/A if (es == CANCELLED)
2754N/A throw new CancellationException();
2754N/A if (es == EXCEPTIONAL && (ex = exceptionMap.get(this)) != null)
2754N/A throw new ExecutionException(ex);
2754N/A throw new TimeoutException();
2754N/A }
1771N/A return getRawResult();
1771N/A }
1771N/A
1771N/A /**
2754N/A * Joins this task, without returning its result or throwing its
1771N/A * exception. This method may be useful when processing
1771N/A * collections of tasks when some have been cancelled or otherwise
1771N/A * known to have aborted.
1771N/A */
1771N/A public final void quietlyJoin() {
2754N/A Thread t;
2754N/A if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) {
2754N/A ForkJoinWorkerThread w = (ForkJoinWorkerThread) t;
2754N/A if (status >= 0) {
2754N/A if (w.unpushTask(this)) {
2754N/A boolean completed;
2754N/A try {
2754N/A completed = exec();
2754N/A } catch (Throwable rex) {
2754N/A setExceptionalCompletion(rex);
2754N/A return;
2754N/A }
2754N/A if (completed) {
2754N/A setCompletion(NORMAL);
2754N/A return;
2754N/A }
2754N/A }
2754N/A w.joinTask(this);
2754N/A }
1771N/A }
2754N/A else
2754N/A externalAwaitDone();
1771N/A }
1771N/A
1771N/A /**
1771N/A * Commences performing this task and awaits its completion if
2754N/A * necessary, without returning its result or throwing its
2754N/A * exception.
1771N/A */
1771N/A public final void quietlyInvoke() {
2754N/A if (status >= 0) {
2754N/A boolean completed;
2754N/A try {
2754N/A completed = exec();
2754N/A } catch (Throwable rex) {
2754N/A setExceptionalCompletion(rex);
2754N/A return;
2754N/A }
2754N/A if (completed)
2754N/A setCompletion(NORMAL);
2754N/A else
2754N/A quietlyJoin();
2754N/A }
1771N/A }
1771N/A
1771N/A /**
1771N/A * Possibly executes tasks until the pool hosting the current task
1771N/A * {@link ForkJoinPool#isQuiescent is quiescent}. This method may
1771N/A * be of use in designs in which many tasks are forked, but none
1771N/A * are explicitly joined, instead executing them until all are
1771N/A * processed.
1771N/A *
1771N/A * <p>This method may be invoked only from within {@code
1771N/A * ForkJoinTask} computations (as may be determined using method
1771N/A * {@link #inForkJoinPool}). Attempts to invoke in other contexts
1771N/A * result in exceptions or errors, possibly including {@code
1771N/A * ClassCastException}.
1771N/A */
1771N/A public static void helpQuiesce() {
1771N/A ((ForkJoinWorkerThread) Thread.currentThread())
1771N/A .helpQuiescePool();
1771N/A }
1771N/A
1771N/A /**
1771N/A * Resets the internal bookkeeping state of this task, allowing a
1771N/A * subsequent {@code fork}. This method allows repeated reuse of
1771N/A * this task, but only if reuse occurs when this task has either
1771N/A * never been forked, or has been forked, then completed and all
1771N/A * outstanding joins of this task have also completed. Effects
1771N/A * under any other usage conditions are not guaranteed.
1771N/A * This method may be useful when executing
1771N/A * pre-constructed trees of subtasks in loops.
1771N/A */
1771N/A public void reinitialize() {
2754N/A if (status == EXCEPTIONAL)
1771N/A exceptionMap.remove(this);
1771N/A status = 0;
1771N/A }
1771N/A
1771N/A /**
1771N/A * Returns the pool hosting the current task execution, or null
1771N/A * if this task is executing outside of any ForkJoinPool.
1771N/A *
1771N/A * @see #inForkJoinPool
1771N/A * @return the pool, or {@code null} if none
1771N/A */
1771N/A public static ForkJoinPool getPool() {
1771N/A Thread t = Thread.currentThread();
1771N/A return (t instanceof ForkJoinWorkerThread) ?
1771N/A ((ForkJoinWorkerThread) t).pool : null;
1771N/A }
1771N/A
1771N/A /**
1771N/A * Returns {@code true} if the current thread is executing as a
1771N/A * ForkJoinPool computation.
1771N/A *
1771N/A * @return {@code true} if the current thread is executing as a
1771N/A * ForkJoinPool computation, or false otherwise
1771N/A */
1771N/A public static boolean inForkJoinPool() {
1771N/A return Thread.currentThread() instanceof ForkJoinWorkerThread;
1771N/A }
1771N/A
1771N/A /**
1771N/A * Tries to unschedule this task for execution. This method will
1771N/A * typically succeed if this task is the most recently forked task
1771N/A * by the current thread, and has not commenced executing in
1771N/A * another thread. This method may be useful when arranging
1771N/A * alternative local processing of tasks that could have been, but
1771N/A * were not, stolen.
1771N/A *
1771N/A * <p>This method may be invoked only from within {@code
1771N/A * ForkJoinTask} computations (as may be determined using method
1771N/A * {@link #inForkJoinPool}). Attempts to invoke in other contexts
1771N/A * result in exceptions or errors, possibly including {@code
1771N/A * ClassCastException}.
1771N/A *
1771N/A * @return {@code true} if unforked
1771N/A */
1771N/A public boolean tryUnfork() {
1771N/A return ((ForkJoinWorkerThread) Thread.currentThread())
1771N/A .unpushTask(this);
1771N/A }
1771N/A
1771N/A /**
1771N/A * Returns an estimate of the number of tasks that have been
1771N/A * forked by the current worker thread but not yet executed. This
1771N/A * value may be useful for heuristic decisions about whether to
1771N/A * fork other tasks.
1771N/A *
1771N/A * <p>This method may be invoked only from within {@code
1771N/A * ForkJoinTask} computations (as may be determined using method
1771N/A * {@link #inForkJoinPool}). Attempts to invoke in other contexts
1771N/A * result in exceptions or errors, possibly including {@code
1771N/A * ClassCastException}.
1771N/A *
1771N/A * @return the number of tasks
1771N/A */
1771N/A public static int getQueuedTaskCount() {
1771N/A return ((ForkJoinWorkerThread) Thread.currentThread())
1771N/A .getQueueSize();
1771N/A }
1771N/A
1771N/A /**
1771N/A * Returns an estimate of how many more locally queued tasks are
1771N/A * held by the current worker thread than there are other worker
1771N/A * threads that might steal them. This value may be useful for
1771N/A * heuristic decisions about whether to fork other tasks. In many
1771N/A * usages of ForkJoinTasks, at steady state, each worker should
1771N/A * aim to maintain a small constant surplus (for example, 3) of
1771N/A * tasks, and to process computations locally if this threshold is
1771N/A * exceeded.
1771N/A *
1771N/A * <p>This method may be invoked only from within {@code
1771N/A * ForkJoinTask} computations (as may be determined using method
1771N/A * {@link #inForkJoinPool}). Attempts to invoke in other contexts
1771N/A * result in exceptions or errors, possibly including {@code
1771N/A * ClassCastException}.
1771N/A *
1771N/A * @return the surplus number of tasks, which may be negative
1771N/A */
1771N/A public static int getSurplusQueuedTaskCount() {
1771N/A return ((ForkJoinWorkerThread) Thread.currentThread())
1771N/A .getEstimatedSurplusTaskCount();
1771N/A }
1771N/A
1771N/A // Extension methods
1771N/A
1771N/A /**
1771N/A * Returns the result that would be returned by {@link #join}, even
1771N/A * if this task completed abnormally, or {@code null} if this task
1771N/A * is not known to have been completed. This method is designed
1771N/A * to aid debugging, as well as to support extensions. Its use in
1771N/A * any other context is discouraged.
1771N/A *
1771N/A * @return the result, or {@code null} if not completed
1771N/A */
1771N/A public abstract V getRawResult();
1771N/A
1771N/A /**
1771N/A * Forces the given value to be returned as a result. This method
1771N/A * is designed to support extensions, and should not in general be
1771N/A * called otherwise.
1771N/A *
1771N/A * @param value the value
1771N/A */
1771N/A protected abstract void setRawResult(V value);
1771N/A
1771N/A /**
1771N/A * Immediately performs the base action of this task. This method
1771N/A * is designed to support extensions, and should not in general be
1771N/A * called otherwise. The return value controls whether this task
1771N/A * is considered to be done normally. It may return false in
1771N/A * asynchronous actions that require explicit invocations of
1771N/A * {@link #complete} to become joinable. It may also throw an
1771N/A * (unchecked) exception to indicate abnormal exit.
1771N/A *
1771N/A * @return {@code true} if completed normally
1771N/A */
1771N/A protected abstract boolean exec();
1771N/A
1771N/A /**
1771N/A * Returns, but does not unschedule or execute, a task queued by
1771N/A * the current thread but not yet executed, if one is immediately
1771N/A * available. There is no guarantee that this task will actually
1771N/A * be polled or executed next. Conversely, this method may return
1771N/A * null even if a task exists but cannot be accessed without
1771N/A * contention with other threads. This method is designed
1771N/A * primarily to support extensions, and is unlikely to be useful
1771N/A * otherwise.
1771N/A *
1771N/A * <p>This method may be invoked only from within {@code
1771N/A * ForkJoinTask} computations (as may be determined using method
1771N/A * {@link #inForkJoinPool}). Attempts to invoke in other contexts
1771N/A * result in exceptions or errors, possibly including {@code
1771N/A * ClassCastException}.
1771N/A *
1771N/A * @return the next task, or {@code null} if none are available
1771N/A */
1771N/A protected static ForkJoinTask<?> peekNextLocalTask() {
1771N/A return ((ForkJoinWorkerThread) Thread.currentThread())
1771N/A .peekTask();
1771N/A }
1771N/A
1771N/A /**
1771N/A * Unschedules and returns, without executing, the next task
1771N/A * queued by the current thread but not yet executed. This method
1771N/A * is designed primarily to support extensions, and is unlikely to
1771N/A * be useful otherwise.
1771N/A *
1771N/A * <p>This method may be invoked only from within {@code
1771N/A * ForkJoinTask} computations (as may be determined using method
1771N/A * {@link #inForkJoinPool}). Attempts to invoke in other contexts
1771N/A * result in exceptions or errors, possibly including {@code
1771N/A * ClassCastException}.
1771N/A *
1771N/A * @return the next task, or {@code null} if none are available
1771N/A */
1771N/A protected static ForkJoinTask<?> pollNextLocalTask() {
1771N/A return ((ForkJoinWorkerThread) Thread.currentThread())
1771N/A .pollLocalTask();
1771N/A }
1771N/A
1771N/A /**
1771N/A * Unschedules and returns, without executing, the next task
1771N/A * queued by the current thread but not yet executed, if one is
1771N/A * available, or if not available, a task that was forked by some
1771N/A * other thread, if available. Availability may be transient, so a
1771N/A * {@code null} result does not necessarily imply quiescence
1771N/A * of the pool this task is operating in. This method is designed
1771N/A * primarily to support extensions, and is unlikely to be useful
1771N/A * otherwise.
1771N/A *
1771N/A * <p>This method may be invoked only from within {@code
1771N/A * ForkJoinTask} computations (as may be determined using method
1771N/A * {@link #inForkJoinPool}). Attempts to invoke in other contexts
1771N/A * result in exceptions or errors, possibly including {@code
1771N/A * ClassCastException}.
1771N/A *
1771N/A * @return a task, or {@code null} if none are available
1771N/A */
1771N/A protected static ForkJoinTask<?> pollTask() {
1771N/A return ((ForkJoinWorkerThread) Thread.currentThread())
1771N/A .pollTask();
1771N/A }
1771N/A
1771N/A /**
1771N/A * Adaptor for Runnables. This implements RunnableFuture
1771N/A * to be compliant with AbstractExecutorService constraints
1771N/A * when used in ForkJoinPool.
1771N/A */
1771N/A static final class AdaptedRunnable<T> extends ForkJoinTask<T>
1771N/A implements RunnableFuture<T> {
1771N/A final Runnable runnable;
1771N/A final T resultOnCompletion;
1771N/A T result;
1771N/A AdaptedRunnable(Runnable runnable, T result) {
1771N/A if (runnable == null) throw new NullPointerException();
1771N/A this.runnable = runnable;
1771N/A this.resultOnCompletion = result;
1771N/A }
1771N/A public T getRawResult() { return result; }
1771N/A public void setRawResult(T v) { result = v; }
1771N/A public boolean exec() {
1771N/A runnable.run();
1771N/A result = resultOnCompletion;
1771N/A return true;
1771N/A }
1771N/A public void run() { invoke(); }
1771N/A private static final long serialVersionUID = 5232453952276885070L;
1771N/A }
1771N/A
1771N/A /**
1771N/A * Adaptor for Callables
1771N/A */
1771N/A static final class AdaptedCallable<T> extends ForkJoinTask<T>
1771N/A implements RunnableFuture<T> {
1771N/A final Callable<? extends T> callable;
1771N/A T result;
1771N/A AdaptedCallable(Callable<? extends T> callable) {
1771N/A if (callable == null) throw new NullPointerException();
1771N/A this.callable = callable;
1771N/A }
1771N/A public T getRawResult() { return result; }
1771N/A public void setRawResult(T v) { result = v; }
1771N/A public boolean exec() {
1771N/A try {
1771N/A result = callable.call();
1771N/A return true;
1771N/A } catch (Error err) {
1771N/A throw err;
1771N/A } catch (RuntimeException rex) {
1771N/A throw rex;
1771N/A } catch (Exception ex) {
1771N/A throw new RuntimeException(ex);
1771N/A }
1771N/A }
1771N/A public void run() { invoke(); }
1771N/A private static final long serialVersionUID = 2838392045355241008L;
1771N/A }
1771N/A
1771N/A /**
1771N/A * Returns a new {@code ForkJoinTask} that performs the {@code run}
1771N/A * method of the given {@code Runnable} as its action, and returns
1771N/A * a null result upon {@link #join}.
1771N/A *
1771N/A * @param runnable the runnable action
1771N/A * @return the task
1771N/A */
1771N/A public static ForkJoinTask<?> adapt(Runnable runnable) {
1771N/A return new AdaptedRunnable<Void>(runnable, null);
1771N/A }
1771N/A
1771N/A /**
1771N/A * Returns a new {@code ForkJoinTask} that performs the {@code run}
1771N/A * method of the given {@code Runnable} as its action, and returns
1771N/A * the given result upon {@link #join}.
1771N/A *
1771N/A * @param runnable the runnable action
1771N/A * @param result the result upon completion
1771N/A * @return the task
1771N/A */
1771N/A public static <T> ForkJoinTask<T> adapt(Runnable runnable, T result) {
1771N/A return new AdaptedRunnable<T>(runnable, result);
1771N/A }
1771N/A
1771N/A /**
1771N/A * Returns a new {@code ForkJoinTask} that performs the {@code call}
1771N/A * method of the given {@code Callable} as its action, and returns
1771N/A * its result upon {@link #join}, translating any checked exceptions
1771N/A * encountered into {@code RuntimeException}.
1771N/A *
1771N/A * @param callable the callable action
1771N/A * @return the task
1771N/A */
1771N/A public static <T> ForkJoinTask<T> adapt(Callable<? extends T> callable) {
1771N/A return new AdaptedCallable<T>(callable);
1771N/A }
1771N/A
1771N/A // Serialization support
1771N/A
1771N/A private static final long serialVersionUID = -7721805057305804111L;
1771N/A
1771N/A /**
2754N/A * Saves the state to a stream (that is, serializes it).
1771N/A *
1771N/A * @serialData the current run status and the exception thrown
1771N/A * during execution, or {@code null} if none
1771N/A * @param s the stream
1771N/A */
1771N/A private void writeObject(java.io.ObjectOutputStream s)
1771N/A throws java.io.IOException {
1771N/A s.defaultWriteObject();
1771N/A s.writeObject(getException());
1771N/A }
1771N/A
1771N/A /**
2754N/A * Reconstitutes the instance from a stream (that is, deserializes it).
1771N/A *
1771N/A * @param s the stream
1771N/A */
1771N/A private void readObject(java.io.ObjectInputStream s)
1771N/A throws java.io.IOException, ClassNotFoundException {
1771N/A s.defaultReadObject();
1771N/A Object ex = s.readObject();
1771N/A if (ex != null)
2754N/A setExceptionalCompletion((Throwable) ex);
1771N/A }
1771N/A
1771N/A // Unsafe mechanics
1771N/A
1771N/A private static final sun.misc.Unsafe UNSAFE = sun.misc.Unsafe.getUnsafe();
1771N/A private static final long statusOffset =
1771N/A objectFieldOffset("status", ForkJoinTask.class);
1771N/A
1771N/A private static long objectFieldOffset(String field, Class<?> klazz) {
1771N/A try {
1771N/A return UNSAFE.objectFieldOffset(klazz.getDeclaredField(field));
1771N/A } catch (NoSuchFieldException e) {
1771N/A // Convert Exception to corresponding Error
1771N/A NoSuchFieldError error = new NoSuchFieldError(field);
1771N/A error.initCause(e);
1771N/A throw error;
1771N/A }
1771N/A }
1771N/A}