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
3984N/A * http://creativecommons.org/publicdomain/zero/1.0/
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;
3736N/Aimport java.lang.ref.WeakReference;
3736N/Aimport java.lang.ref.ReferenceQueue;
3387N/Aimport java.util.concurrent.Callable;
3387N/Aimport java.util.concurrent.CancellationException;
3387N/Aimport java.util.concurrent.ExecutionException;
3387N/Aimport java.util.concurrent.Executor;
3387N/Aimport java.util.concurrent.ExecutorService;
3387N/Aimport java.util.concurrent.Future;
3387N/Aimport java.util.concurrent.RejectedExecutionException;
3387N/Aimport java.util.concurrent.RunnableFuture;
3387N/Aimport java.util.concurrent.TimeUnit;
3387N/Aimport java.util.concurrent.TimeoutException;
3736N/Aimport java.util.concurrent.locks.ReentrantLock;
3736N/Aimport java.lang.reflect.Constructor;
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
3736N/A * internal task queues. Rethrown exceptions behave in the same way as
3736N/A * regular exceptions, but, when possible, contain stack traces (as
3736N/A * displayed for example using {@code ex.printStackTrace()}) of both
3736N/A * the thread that initiated the computation as well as the thread
3736N/A * actually encountering the exception; minimally only the latter.
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 *
3387N/A * <p>Method {@link #join} and its variants are appropriate for use
3387N/A * only when completion dependencies are acyclic; that is, the
3387N/A * parallel computation can be described as a directed acyclic graph
3387N/A * (DAG). Otherwise, executions may encounter a form of deadlock as
3387N/A * tasks cyclically wait for each other. However, this framework
3387N/A * supports other methods and techniques (for example the use of
3387N/A * {@link Phaser}, {@link #helpQuiesce}, and {@link #complete}) that
3387N/A * may be of use in constructing custom subclasses for problems that
3387N/A * are not statically structured as DAGs.
3387N/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
3387N/A * computational steps, and should avoid indefinite looping. If tasks
3387N/A * are too big, then parallelism cannot improve throughput. If too
3387N/A * small, then memory and internal task maintenance overhead may
3387N/A * 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
3736N/A * in a way that flows well in javadocs.
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
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 /**
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
3736N/A * @return completion status on exit
1771N/A */
3736N/A private int setCompletion(int completion) {
3736N/A for (int s;;) {
3736N/A if ((s = status) < 0)
3736N/A return s;
2754N/A if (UNSAFE.compareAndSwapInt(this, statusOffset, s, completion)) {
2754N/A if (s != 0)
2754N/A synchronized (this) { notifyAll(); }
3736N/A return completion;
2754N/A }
1771N/A }
1771N/A }
1771N/A
1771N/A /**
3736N/A * Tries to block a worker thread until completed or timed out.
3736N/A * Uses Object.wait time argument conventions.
3736N/A * May fail on contention or interrupt.
2754N/A *
3736N/A * @param millis if > 0, wait time.
1771N/A */
3736N/A final void tryAwaitDone(long millis) {
3736N/A int s;
3736N/A try {
3736N/A if (((s = status) > 0 ||
3736N/A (s == 0 &&
3736N/A UNSAFE.compareAndSwapInt(this, statusOffset, 0, SIGNAL))) &&
3736N/A status > 0) {
2805N/A synchronized (this) {
3387N/A if (status > 0)
3736N/A wait(millis);
1771N/A }
1771N/A }
3736N/A } catch (InterruptedException ie) {
3736N/A // caller must check termination
1771N/A }
1771N/A }
1771N/A
1771N/A /**
2754N/A * Blocks a non-worker-thread until completion.
3736N/A * @return status upon completion
1771N/A */
3736N/A private int externalAwaitDone() {
3736N/A int s;
3736N/A if ((s = status) >= 0) {
3387N/A boolean interrupted = false;
2805N/A synchronized (this) {
3736N/A while ((s = status) >= 0) {
3387N/A if (s == 0)
3387N/A UNSAFE.compareAndSwapInt(this, statusOffset,
3387N/A 0, SIGNAL);
3387N/A else {
2754N/A try {
2754N/A wait();
2754N/A } catch (InterruptedException ie) {
2754N/A interrupted = true;
2754N/A }
2754N/A }
3387N/A }
3387N/A }
3387N/A if (interrupted)
3387N/A Thread.currentThread().interrupt();
3387N/A }
3736N/A return s;
3387N/A }
3387N/A
3387N/A /**
3387N/A * Blocks a non-worker-thread until completion or interruption or timeout.
3387N/A */
3736N/A private int externalInterruptibleAwaitDone(long millis)
3387N/A throws InterruptedException {
3736N/A int s;
3387N/A if (Thread.interrupted())
3387N/A throw new InterruptedException();
3736N/A if ((s = status) >= 0) {
3387N/A synchronized (this) {
3736N/A while ((s = status) >= 0) {
3387N/A if (s == 0)
3387N/A UNSAFE.compareAndSwapInt(this, statusOffset,
3387N/A 0, SIGNAL);
3736N/A else {
3736N/A wait(millis);
3736N/A if (millis > 0L)
3736N/A break;
3736N/A }
3736N/A }
3736N/A }
3736N/A }
3736N/A return s;
3736N/A }
3736N/A
3736N/A /**
3736N/A * Primary execution method for stolen tasks. Unless done, calls
3736N/A * exec and records status if completed, but doesn't wait for
3736N/A * completion otherwise.
3736N/A */
3736N/A final void doExec() {
3736N/A if (status >= 0) {
3736N/A boolean completed;
3736N/A try {
3736N/A completed = exec();
3736N/A } catch (Throwable rex) {
3736N/A setExceptionalCompletion(rex);
3736N/A return;
3736N/A }
3736N/A if (completed)
3736N/A setCompletion(NORMAL); // must be outside try block
3736N/A }
3736N/A }
3736N/A
3736N/A /**
3736N/A * Primary mechanics for join, get, quietlyJoin.
3736N/A * @return status upon completion
3736N/A */
3736N/A private int doJoin() {
3736N/A Thread t; ForkJoinWorkerThread w; int s; boolean completed;
3736N/A if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) {
3736N/A if ((s = status) < 0)
3736N/A return s;
3736N/A if ((w = (ForkJoinWorkerThread)t).unpushTask(this)) {
3736N/A try {
3736N/A completed = exec();
3736N/A } catch (Throwable rex) {
3736N/A return setExceptionalCompletion(rex);
3736N/A }
3736N/A if (completed)
3736N/A return setCompletion(NORMAL);
3736N/A }
3736N/A return w.joinTask(this);
3736N/A }
3736N/A else
3736N/A return externalAwaitDone();
3736N/A }
3736N/A
3736N/A /**
3736N/A * Primary mechanics for invoke, quietlyInvoke.
3736N/A * @return status upon completion
3736N/A */
3736N/A private int doInvoke() {
3736N/A int s; boolean completed;
3736N/A if ((s = status) < 0)
3736N/A return s;
3736N/A try {
3736N/A completed = exec();
3736N/A } catch (Throwable rex) {
3736N/A return setExceptionalCompletion(rex);
3736N/A }
3736N/A if (completed)
3736N/A return setCompletion(NORMAL);
3736N/A else
3736N/A return doJoin();
3736N/A }
3736N/A
3736N/A // Exception table support
3736N/A
3736N/A /**
3736N/A * Table of exceptions thrown by tasks, to enable reporting by
3736N/A * callers. Because exceptions are rare, we don't directly keep
3736N/A * them with task objects, but instead use a weak ref table. Note
3736N/A * that cancellation exceptions don't appear in the table, but are
3736N/A * instead recorded as status values.
3736N/A *
3736N/A * Note: These statics are initialized below in static block.
3736N/A */
3736N/A private static final ExceptionNode[] exceptionTable;
3736N/A private static final ReentrantLock exceptionTableLock;
3736N/A private static final ReferenceQueue<Object> exceptionTableRefQueue;
3736N/A
3736N/A /**
3736N/A * Fixed capacity for exceptionTable.
3736N/A */
3736N/A private static final int EXCEPTION_MAP_CAPACITY = 32;
3736N/A
3736N/A /**
3736N/A * Key-value nodes for exception table. The chained hash table
3736N/A * uses identity comparisons, full locking, and weak references
3736N/A * for keys. The table has a fixed capacity because it only
3736N/A * maintains task exceptions long enough for joiners to access
3736N/A * them, so should never become very large for sustained
3736N/A * periods. However, since we do not know when the last joiner
3736N/A * completes, we must use weak references and expunge them. We do
3736N/A * so on each operation (hence full locking). Also, some thread in
3736N/A * any ForkJoinPool will call helpExpungeStaleExceptions when its
3736N/A * pool becomes isQuiescent.
3736N/A */
3736N/A static final class ExceptionNode extends WeakReference<ForkJoinTask<?>>{
3736N/A final Throwable ex;
3736N/A ExceptionNode next;
3736N/A final long thrower; // use id not ref to avoid weak cycles
3736N/A ExceptionNode(ForkJoinTask<?> task, Throwable ex, ExceptionNode next) {
3736N/A super(task, exceptionTableRefQueue);
3736N/A this.ex = ex;
3736N/A this.next = next;
3736N/A this.thrower = Thread.currentThread().getId();
3736N/A }
3736N/A }
3736N/A
3736N/A /**
3736N/A * Records exception and sets exceptional completion.
3736N/A *
3736N/A * @return status on exit
3736N/A */
3736N/A private int setExceptionalCompletion(Throwable ex) {
3736N/A int h = System.identityHashCode(this);
3736N/A final ReentrantLock lock = exceptionTableLock;
3736N/A lock.lock();
3736N/A try {
3736N/A expungeStaleExceptions();
3736N/A ExceptionNode[] t = exceptionTable;
3736N/A int i = h & (t.length - 1);
3736N/A for (ExceptionNode e = t[i]; ; e = e.next) {
3736N/A if (e == null) {
3736N/A t[i] = new ExceptionNode(this, ex, t[i]);
3736N/A break;
3736N/A }
3736N/A if (e.get() == this) // already present
3736N/A break;
3736N/A }
3736N/A } finally {
3736N/A lock.unlock();
3736N/A }
3736N/A return setCompletion(EXCEPTIONAL);
3736N/A }
3736N/A
3736N/A /**
3736N/A * Removes exception node and clears status
3736N/A */
3736N/A private void clearExceptionalCompletion() {
3736N/A int h = System.identityHashCode(this);
3736N/A final ReentrantLock lock = exceptionTableLock;
3736N/A lock.lock();
3736N/A try {
3736N/A ExceptionNode[] t = exceptionTable;
3736N/A int i = h & (t.length - 1);
3736N/A ExceptionNode e = t[i];
3736N/A ExceptionNode pred = null;
3736N/A while (e != null) {
3736N/A ExceptionNode next = e.next;
3736N/A if (e.get() == this) {
3736N/A if (pred == null)
3736N/A t[i] = next;
3736N/A else
3736N/A pred.next = next;
3736N/A break;
3736N/A }
3736N/A pred = e;
3736N/A e = next;
3736N/A }
3736N/A expungeStaleExceptions();
3736N/A status = 0;
3736N/A } finally {
3736N/A lock.unlock();
3736N/A }
3736N/A }
3736N/A
3736N/A /**
3736N/A * Returns a rethrowable exception for the given task, if
3736N/A * available. To provide accurate stack traces, if the exception
3736N/A * was not thrown by the current thread, we try to create a new
3736N/A * exception of the same type as the one thrown, but with the
3736N/A * recorded exception as its cause. If there is no such
3736N/A * constructor, we instead try to use a no-arg constructor,
3736N/A * followed by initCause, to the same effect. If none of these
3736N/A * apply, or any fail due to other exceptions, we return the
3736N/A * recorded exception, which is still correct, although it may
3736N/A * contain a misleading stack trace.
3736N/A *
3736N/A * @return the exception, or null if none
3736N/A */
3736N/A private Throwable getThrowableException() {
3736N/A if (status != EXCEPTIONAL)
3736N/A return null;
3736N/A int h = System.identityHashCode(this);
3736N/A ExceptionNode e;
3736N/A final ReentrantLock lock = exceptionTableLock;
3736N/A lock.lock();
3736N/A try {
3736N/A expungeStaleExceptions();
3736N/A ExceptionNode[] t = exceptionTable;
3736N/A e = t[h & (t.length - 1)];
3736N/A while (e != null && e.get() != this)
3736N/A e = e.next;
3736N/A } finally {
3736N/A lock.unlock();
3736N/A }
3736N/A Throwable ex;
3736N/A if (e == null || (ex = e.ex) == null)
3736N/A return null;
3736N/A if (e.thrower != Thread.currentThread().getId()) {
3736N/A Class ec = ex.getClass();
3736N/A try {
3736N/A Constructor<?> noArgCtor = null;
3736N/A Constructor<?>[] cs = ec.getConstructors();// public ctors only
3736N/A for (int i = 0; i < cs.length; ++i) {
3736N/A Constructor<?> c = cs[i];
3736N/A Class<?>[] ps = c.getParameterTypes();
3736N/A if (ps.length == 0)
3736N/A noArgCtor = c;
3736N/A else if (ps.length == 1 && ps[0] == Throwable.class)
3736N/A return (Throwable)(c.newInstance(ex));
3736N/A }
3736N/A if (noArgCtor != null) {
3736N/A Throwable wx = (Throwable)(noArgCtor.newInstance());
3736N/A wx.initCause(ex);
3736N/A return wx;
3736N/A }
3736N/A } catch (Exception ignore) {
3736N/A }
3736N/A }
3736N/A return ex;
3736N/A }
3736N/A
3736N/A /**
3736N/A * Poll stale refs and remove them. Call only while holding lock.
3736N/A */
3736N/A private static void expungeStaleExceptions() {
3736N/A for (Object x; (x = exceptionTableRefQueue.poll()) != null;) {
3736N/A if (x instanceof ExceptionNode) {
3736N/A ForkJoinTask<?> key = ((ExceptionNode)x).get();
3736N/A ExceptionNode[] t = exceptionTable;
3736N/A int i = System.identityHashCode(key) & (t.length - 1);
3736N/A ExceptionNode e = t[i];
3736N/A ExceptionNode pred = null;
3736N/A while (e != null) {
3736N/A ExceptionNode next = e.next;
3736N/A if (e == x) {
3736N/A if (pred == null)
3736N/A t[i] = next;
3736N/A else
3736N/A pred.next = next;
3387N/A break;
3387N/A }
3736N/A pred = e;
3736N/A e = next;
1771N/A }
1771N/A }
1771N/A }
1771N/A }
1771N/A
1771N/A /**
3736N/A * If lock is available, poll stale refs and remove them.
3736N/A * Called from ForkJoinPool when pools become quiescent.
1771N/A */
3736N/A static final void helpExpungeStaleExceptions() {
3736N/A final ReentrantLock lock = exceptionTableLock;
3736N/A if (lock.tryLock()) {
3736N/A try {
3736N/A expungeStaleExceptions();
3736N/A } finally {
3736N/A lock.unlock();
3736N/A }
1771N/A }
3736N/A }
3736N/A
3736N/A /**
3736N/A * Report the result of invoke or join; called only upon
3736N/A * non-normal return of internal versions.
3736N/A */
3736N/A private V reportResult() {
3736N/A int s; Throwable ex;
3736N/A if ((s = status) == CANCELLED)
3736N/A throw new CancellationException();
3736N/A if (s == EXCEPTIONAL && (ex = getThrowableException()) != null)
3736N/A UNSAFE.throwException(ex);
3736N/A return getRawResult();
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
3387N/A * ForkJoinPool} 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 /**
3387N/A * Returns the result of the computation when it {@link #isDone is
3387N/A * done}. This method differs from {@link #get()} in that
1771N/A * abnormal completion results in {@code RuntimeException} or
3387N/A * {@code Error}, not {@code ExecutionException}, and that
3387N/A * interrupts of the calling thread do <em>not</em> cause the
3387N/A * method to abruptly return by throwing {@code
3387N/A * InterruptedException}.
1771N/A *
1771N/A * @return the computed result
1771N/A */
1771N/A public final V join() {
3736N/A if (doJoin() != NORMAL)
3736N/A return reportResult();
3736N/A else
3736N/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() {
3736N/A if (doInvoke() != NORMAL)
3736N/A return reportResult();
3736N/A else
3736N/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
3387N/A * ForkJoinPool} 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
3387N/A * ForkJoinPool} 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();
3736N/A else if (t.doInvoke() < NORMAL && ex == null)
3736N/A ex = t.getException();
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);
3736N/A else if (t.doJoin() < NORMAL && ex == null)
3736N/A ex = t.getException();
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
3387N/A * ForkJoinPool} 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();
3736N/A else if (t.doInvoke() < NORMAL && ex == null)
3736N/A ex = t.getException();
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);
3736N/A else if (t.doJoin() < NORMAL && ex == null)
3736N/A ex = t.getException();
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
3387N/A * fail if the task has already completed or could not be
3387N/A * cancelled for some other reason. If successful, and this task
3387N/A * has not started when {@code cancel} is called, execution of
3387N/A * this task is suppressed. After this method returns
3387N/A * successfully, unless there is an intervening call to {@link
3387N/A * #reinitialize}, subsequent calls to {@link #isCancelled},
3387N/A * {@link #isDone}, and {@code cancel} will return {@code true}
3387N/A * and calls to {@link #join} and related methods will result in
3387N/A * {@code CancellationException}.
1771N/A *
1771N/A * <p>This method may be overridden in subclasses, but if so, must
3387N/A * still ensure that these properties hold. In particular, the
3387N/A * {@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 *
3387N/A * @param mayInterruptIfRunning this value has no effect in the
3387N/A * default implementation because interrupts are not used to
3387N/A * control cancellation.
1771N/A *
1771N/A * @return {@code true} if this task is now cancelled
1771N/A */
1771N/A public boolean cancel(boolean mayInterruptIfRunning) {
3736N/A return setCompletion(CANCELLED) == 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
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() :
3736N/A getThrowableException());
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 {
3736N/A int s = (Thread.currentThread() instanceof ForkJoinWorkerThread) ?
3736N/A doJoin() : externalInterruptibleAwaitDone(0L);
3736N/A Throwable ex;
3736N/A if (s == CANCELLED)
3736N/A throw new CancellationException();
3736N/A if (s == EXCEPTIONAL && (ex = getThrowableException()) != null)
3736N/A throw new ExecutionException(ex);
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();
3736N/A if (t instanceof ForkJoinWorkerThread) {
3736N/A ForkJoinWorkerThread w = (ForkJoinWorkerThread) t;
3736N/A long nanos = unit.toNanos(timeout);
3736N/A if (status >= 0) {
3736N/A boolean completed = false;
3736N/A if (w.unpushTask(this)) {
3736N/A try {
3736N/A completed = exec();
3736N/A } catch (Throwable rex) {
3736N/A setExceptionalCompletion(rex);
3736N/A }
3736N/A }
3736N/A if (completed)
3736N/A setCompletion(NORMAL);
3736N/A else if (status >= 0 && nanos > 0)
3736N/A w.pool.timedAwaitJoin(this, nanos);
3736N/A }
3736N/A }
3736N/A else {
3736N/A long millis = unit.toMillis(timeout);
3736N/A if (millis > 0)
3736N/A externalInterruptibleAwaitDone(millis);
3736N/A }
3387N/A int s = status;
3387N/A if (s != NORMAL) {
2754N/A Throwable ex;
3387N/A if (s == CANCELLED)
2754N/A throw new CancellationException();
3736N/A if (s != EXCEPTIONAL)
3736N/A throw new TimeoutException();
3736N/A if ((ex = getThrowableException()) != null)
2754N/A throw new ExecutionException(ex);
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() {
3736N/A doJoin();
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() {
3736N/A doInvoke();
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
3387N/A * ForkJoinPool} 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.
3387N/A *
3387N/A * <p>Upon completion of this method, {@code isDone()} reports
3387N/A * {@code false}, and {@code getException()} reports {@code
3387N/A * null}. However, the value returned by {@code getRawResult} is
3387N/A * unaffected. To clear this value, you can invoke {@code
3387N/A * setRawResult(null)}.
1771N/A */
1771N/A public void reinitialize() {
2754N/A if (status == EXCEPTIONAL)
3736N/A clearExceptionalCompletion();
3736N/A else
3736N/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 /**
3387N/A * Returns {@code true} if the current thread is a {@link
3387N/A * ForkJoinWorkerThread} executing as a ForkJoinPool computation.
1771N/A *
3387N/A * @return {@code true} if the current thread is a {@link
3387N/A * ForkJoinWorkerThread} executing as a ForkJoinPool computation,
3387N/A * or {@code 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
3387N/A * ForkJoinPool} 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
3387N/A * ForkJoinPool} 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
3387N/A * ForkJoinPool} 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
3387N/A * ForkJoinPool} 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
3387N/A * ForkJoinPool} 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
3387N/A * ForkJoinPool} 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)
3736N/A setExceptionalCompletion((Throwable)ex);
1771N/A }
1771N/A
1771N/A // Unsafe mechanics
3736N/A private static final sun.misc.Unsafe UNSAFE;
3736N/A private static final long statusOffset;
3736N/A static {
3736N/A exceptionTableLock = new ReentrantLock();
3736N/A exceptionTableRefQueue = new ReferenceQueue<Object>();
3736N/A exceptionTable = new ExceptionNode[EXCEPTION_MAP_CAPACITY];
1771N/A try {
3736N/A UNSAFE = sun.misc.Unsafe.getUnsafe();
3736N/A statusOffset = UNSAFE.objectFieldOffset
3736N/A (ForkJoinTask.class.getDeclaredField("status"));
3736N/A } catch (Exception e) {
3736N/A throw new Error(e);
1771N/A }
1771N/A }
3736N/A
1771N/A}