rt/emul/compact/src/main/java/java/util/concurrent/ForkJoinTask.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Sat, 19 Mar 2016 13:15:11 +0100
changeset 1896 9984d9a62bc0
parent 1890 212417b74b72
permissions -rw-r--r--
Making java.util.concurrent compilable without references to sun.misc.Unsafe and co.
     1 /*
     2  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     3  *
     4  * This code is free software; you can redistribute it and/or modify it
     5  * under the terms of the GNU General Public License version 2 only, as
     6  * published by the Free Software Foundation.  Oracle designates this
     7  * particular file as subject to the "Classpath" exception as provided
     8  * by Oracle in the LICENSE file that accompanied this code.
     9  *
    10  * This code is distributed in the hope that it will be useful, but WITHOUT
    11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    13  * version 2 for more details (a copy is included in the LICENSE file that
    14  * accompanied this code).
    15  *
    16  * You should have received a copy of the GNU General Public License version
    17  * 2 along with this work; if not, write to the Free Software Foundation,
    18  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    19  *
    20  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    21  * or visit www.oracle.com if you need additional information or have any
    22  * questions.
    23  */
    24 
    25 /*
    26  * This file is available under and governed by the GNU General Public
    27  * License version 2 only, as published by the Free Software Foundation.
    28  * However, the following notice accompanied the original version of this
    29  * file:
    30  *
    31  * Written by Doug Lea with assistance from members of JCP JSR-166
    32  * Expert Group and released to the public domain, as explained at
    33  * http://creativecommons.org/publicdomain/zero/1.0/
    34  */
    35 
    36 package java.util.concurrent;
    37 
    38 import java.io.Serializable;
    39 import java.util.Collection;
    40 import java.util.List;
    41 import java.util.RandomAccess;
    42 import java.lang.ref.WeakReference;
    43 import java.lang.ref.ReferenceQueue;
    44 import java.util.concurrent.Callable;
    45 import java.util.concurrent.CancellationException;
    46 import java.util.concurrent.ExecutionException;
    47 import java.util.concurrent.Future;
    48 import java.util.concurrent.RejectedExecutionException;
    49 import java.util.concurrent.RunnableFuture;
    50 import java.util.concurrent.TimeUnit;
    51 import java.util.concurrent.TimeoutException;
    52 import java.util.concurrent.locks.ReentrantLock;
    53 import java.lang.reflect.Constructor;
    54 
    55 /**
    56  * Abstract base class for tasks that run within a {@link ForkJoinPool}.
    57  * A {@code ForkJoinTask} is a thread-like entity that is much
    58  * lighter weight than a normal thread.  Huge numbers of tasks and
    59  * subtasks may be hosted by a small number of actual threads in a
    60  * ForkJoinPool, at the price of some usage limitations.
    61  *
    62  * <p>A "main" {@code ForkJoinTask} begins execution when submitted
    63  * to a {@link ForkJoinPool}.  Once started, it will usually in turn
    64  * start other subtasks.  As indicated by the name of this class,
    65  * many programs using {@code ForkJoinTask} employ only methods
    66  * {@link #fork} and {@link #join}, or derivatives such as {@link
    67  * #invokeAll(ForkJoinTask...) invokeAll}.  However, this class also
    68  * provides a number of other methods that can come into play in
    69  * advanced usages, as well as extension mechanics that allow
    70  * support of new forms of fork/join processing.
    71  *
    72  * <p>A {@code ForkJoinTask} is a lightweight form of {@link Future}.
    73  * The efficiency of {@code ForkJoinTask}s stems from a set of
    74  * restrictions (that are only partially statically enforceable)
    75  * reflecting their intended use as computational tasks calculating
    76  * pure functions or operating on purely isolated objects.  The
    77  * primary coordination mechanisms are {@link #fork}, that arranges
    78  * asynchronous execution, and {@link #join}, that doesn't proceed
    79  * until the task's result has been computed.  Computations should
    80  * avoid {@code synchronized} methods or blocks, and should minimize
    81  * other blocking synchronization apart from joining other tasks or
    82  * using synchronizers such as Phasers that are advertised to
    83  * cooperate with fork/join scheduling. Tasks should also not perform
    84  * blocking IO, and should ideally access variables that are
    85  * completely independent of those accessed by other running
    86  * tasks. Minor breaches of these restrictions, for example using
    87  * shared output streams, may be tolerable in practice, but frequent
    88  * use may result in poor performance, and the potential to
    89  * indefinitely stall if the number of threads not waiting for IO or
    90  * other external synchronization becomes exhausted. This usage
    91  * restriction is in part enforced by not permitting checked
    92  * exceptions such as {@code IOExceptions} to be thrown. However,
    93  * computations may still encounter unchecked exceptions, that are
    94  * rethrown to callers attempting to join them. These exceptions may
    95  * additionally include {@link RejectedExecutionException} stemming
    96  * from internal resource exhaustion, such as failure to allocate
    97  * internal task queues. Rethrown exceptions behave in the same way as
    98  * regular exceptions, but, when possible, contain stack traces (as
    99  * displayed for example using {@code ex.printStackTrace()}) of both
   100  * the thread that initiated the computation as well as the thread
   101  * actually encountering the exception; minimally only the latter.
   102  *
   103  * <p>The primary method for awaiting completion and extracting
   104  * results of a task is {@link #join}, but there are several variants:
   105  * The {@link Future#get} methods support interruptible and/or timed
   106  * waits for completion and report results using {@code Future}
   107  * conventions. Method {@link #invoke} is semantically
   108  * equivalent to {@code fork(); join()} but always attempts to begin
   109  * execution in the current thread. The "<em>quiet</em>" forms of
   110  * these methods do not extract results or report exceptions. These
   111  * may be useful when a set of tasks are being executed, and you need
   112  * to delay processing of results or exceptions until all complete.
   113  * Method {@code invokeAll} (available in multiple versions)
   114  * performs the most common form of parallel invocation: forking a set
   115  * of tasks and joining them all.
   116  *
   117  * <p>The execution status of tasks may be queried at several levels
   118  * of detail: {@link #isDone} is true if a task completed in any way
   119  * (including the case where a task was cancelled without executing);
   120  * {@link #isCompletedNormally} is true if a task completed without
   121  * cancellation or encountering an exception; {@link #isCancelled} is
   122  * true if the task was cancelled (in which case {@link #getException}
   123  * returns a {@link java.util.concurrent.CancellationException}); and
   124  * {@link #isCompletedAbnormally} is true if a task was either
   125  * cancelled or encountered an exception, in which case {@link
   126  * #getException} will return either the encountered exception or
   127  * {@link java.util.concurrent.CancellationException}.
   128  *
   129  * <p>The ForkJoinTask class is not usually directly subclassed.
   130  * Instead, you subclass one of the abstract classes that support a
   131  * particular style of fork/join processing, typically {@link
   132  * RecursiveAction} for computations that do not return results, or
   133  * {@link RecursiveTask} for those that do.  Normally, a concrete
   134  * ForkJoinTask subclass declares fields comprising its parameters,
   135  * established in a constructor, and then defines a {@code compute}
   136  * method that somehow uses the control methods supplied by this base
   137  * class. While these methods have {@code public} access (to allow
   138  * instances of different task subclasses to call each other's
   139  * methods), some of them may only be called from within other
   140  * ForkJoinTasks (as may be determined using method {@link
   141  * #inForkJoinPool}).  Attempts to invoke them in other contexts
   142  * result in exceptions or errors, possibly including
   143  * {@code ClassCastException}.
   144  *
   145  * <p>Method {@link #join} and its variants are appropriate for use
   146  * only when completion dependencies are acyclic; that is, the
   147  * parallel computation can be described as a directed acyclic graph
   148  * (DAG). Otherwise, executions may encounter a form of deadlock as
   149  * tasks cyclically wait for each other.  However, this framework
   150  * supports other methods and techniques (for example the use of
   151  * {@link Phaser}, {@link #helpQuiesce}, and {@link #complete}) that
   152  * may be of use in constructing custom subclasses for problems that
   153  * are not statically structured as DAGs.
   154  *
   155  * <p>Most base support methods are {@code final}, to prevent
   156  * overriding of implementations that are intrinsically tied to the
   157  * underlying lightweight task scheduling framework.  Developers
   158  * creating new basic styles of fork/join processing should minimally
   159  * implement {@code protected} methods {@link #exec}, {@link
   160  * #setRawResult}, and {@link #getRawResult}, while also introducing
   161  * an abstract computational method that can be implemented in its
   162  * subclasses, possibly relying on other {@code protected} methods
   163  * provided by this class.
   164  *
   165  * <p>ForkJoinTasks should perform relatively small amounts of
   166  * computation. Large tasks should be split into smaller subtasks,
   167  * usually via recursive decomposition. As a very rough rule of thumb,
   168  * a task should perform more than 100 and less than 10000 basic
   169  * computational steps, and should avoid indefinite looping. If tasks
   170  * are too big, then parallelism cannot improve throughput. If too
   171  * small, then memory and internal task maintenance overhead may
   172  * overwhelm processing.
   173  *
   174  * <p>This class provides {@code adapt} methods for {@link Runnable}
   175  * and {@link Callable}, that may be of use when mixing execution of
   176  * {@code ForkJoinTasks} with other kinds of tasks. When all tasks are
   177  * of this form, consider using a pool constructed in <em>asyncMode</em>.
   178  *
   179  * <p>ForkJoinTasks are {@code Serializable}, which enables them to be
   180  * used in extensions such as remote execution frameworks. It is
   181  * sensible to serialize tasks only before or after, but not during,
   182  * execution. Serialization is not relied on during execution itself.
   183  *
   184  * @since 1.7
   185  * @author Doug Lea
   186  */
   187 public abstract class ForkJoinTask<V> implements Future<V>, Serializable {
   188 
   189     /*
   190      * See the internal documentation of class ForkJoinPool for a
   191      * general implementation overview.  ForkJoinTasks are mainly
   192      * responsible for maintaining their "status" field amidst relays
   193      * to methods in ForkJoinWorkerThread and ForkJoinPool. The
   194      * methods of this class are more-or-less layered into (1) basic
   195      * status maintenance (2) execution and awaiting completion (3)
   196      * user-level methods that additionally report results. This is
   197      * sometimes hard to see because this file orders exported methods
   198      * in a way that flows well in javadocs.
   199      */
   200 
   201     /*
   202      * The status field holds run control status bits packed into a
   203      * single int to minimize footprint and to ensure atomicity (via
   204      * CAS).  Status is initially zero, and takes on nonnegative
   205      * values until completed, upon which status holds value
   206      * NORMAL, CANCELLED, or EXCEPTIONAL. Tasks undergoing blocking
   207      * waits by other threads have the SIGNAL bit set.  Completion of
   208      * a stolen task with SIGNAL set awakens any waiters via
   209      * notifyAll. Even though suboptimal for some purposes, we use
   210      * basic builtin wait/notify to take advantage of "monitor
   211      * inflation" in JVMs that we would otherwise need to emulate to
   212      * avoid adding further per-task bookkeeping overhead.  We want
   213      * these monitors to be "fat", i.e., not use biasing or thin-lock
   214      * techniques, so use some odd coding idioms that tend to avoid
   215      * them.
   216      */
   217 
   218     /** The run status of this task */
   219     volatile int status; // accessed directly by pool and workers
   220     private static final int NORMAL      = -1;
   221     private static final int CANCELLED   = -2;
   222     private static final int EXCEPTIONAL = -3;
   223     private static final int SIGNAL      =  1;
   224 
   225     /**
   226      * Marks completion and wakes up threads waiting to join this task,
   227      * also clearing signal request bits.
   228      *
   229      * @param completion one of NORMAL, CANCELLED, EXCEPTIONAL
   230      * @return completion status on exit
   231      */
   232     private int setCompletion(int completion) {
   233         for (int s;;) {
   234             if ((s = status) < 0)
   235                 return s;
   236             if (UNSAFE.compareAndSwapInt(this, statusOffset, s, completion)) {
   237                 if (s != 0)
   238                     synchronized (this) { notifyAll(); }
   239                 return completion;
   240             }
   241         }
   242     }
   243 
   244     /**
   245      * Tries to block a worker thread until completed or timed out.
   246      * Uses Object.wait time argument conventions.
   247      * May fail on contention or interrupt.
   248      *
   249      * @param millis if > 0, wait time.
   250      */
   251     final void tryAwaitDone(long millis) {
   252         int s;
   253         try {
   254             if (((s = status) > 0 ||
   255                  (s == 0 &&
   256                   UNSAFE.compareAndSwapInt(this, statusOffset, 0, SIGNAL))) &&
   257                 status > 0) {
   258                 synchronized (this) {
   259                     if (status > 0)
   260                         wait(millis);
   261                 }
   262             }
   263         } catch (InterruptedException ie) {
   264             // caller must check termination
   265         }
   266     }
   267 
   268     /**
   269      * Blocks a non-worker-thread until completion.
   270      * @return status upon completion
   271      */
   272     private int externalAwaitDone() {
   273         int s;
   274         if ((s = status) >= 0) {
   275             boolean interrupted = false;
   276             synchronized (this) {
   277                 while ((s = status) >= 0) {
   278                     if (s == 0)
   279                         UNSAFE.compareAndSwapInt(this, statusOffset,
   280                                                  0, SIGNAL);
   281                     else {
   282                         try {
   283                             wait();
   284                         } catch (InterruptedException ie) {
   285                             interrupted = true;
   286                         }
   287                     }
   288                 }
   289             }
   290             if (interrupted)
   291                 Thread.currentThread().interrupt();
   292         }
   293         return s;
   294     }
   295 
   296     /**
   297      * Blocks a non-worker-thread until completion or interruption or timeout.
   298      */
   299     private int externalInterruptibleAwaitDone(long millis)
   300         throws InterruptedException {
   301         int s;
   302         if (Thread.interrupted())
   303             throw new InterruptedException();
   304         if ((s = status) >= 0) {
   305             synchronized (this) {
   306                 while ((s = status) >= 0) {
   307                     if (s == 0)
   308                         UNSAFE.compareAndSwapInt(this, statusOffset,
   309                                                  0, SIGNAL);
   310                     else {
   311                         wait(millis);
   312                         if (millis > 0L)
   313                             break;
   314                     }
   315                 }
   316             }
   317         }
   318         return s;
   319     }
   320 
   321     /**
   322      * Primary execution method for stolen tasks. Unless done, calls
   323      * exec and records status if completed, but doesn't wait for
   324      * completion otherwise.
   325      */
   326     final void doExec() {
   327         if (status >= 0) {
   328             boolean completed;
   329             try {
   330                 completed = exec();
   331             } catch (Throwable rex) {
   332                 setExceptionalCompletion(rex);
   333                 return;
   334             }
   335             if (completed)
   336                 setCompletion(NORMAL); // must be outside try block
   337         }
   338     }
   339 
   340     /**
   341      * Primary mechanics for join, get, quietlyJoin.
   342      * @return status upon completion
   343      */
   344     private int doJoin() {
   345         Thread t; ForkJoinWorkerThread w; int s; boolean completed;
   346         if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) {
   347             if ((s = status) < 0)
   348                 return s;
   349             if ((w = (ForkJoinWorkerThread)t).unpushTask(this)) {
   350                 try {
   351                     completed = exec();
   352                 } catch (Throwable rex) {
   353                     return setExceptionalCompletion(rex);
   354                 }
   355                 if (completed)
   356                     return setCompletion(NORMAL);
   357             }
   358             return w.joinTask(this);
   359         }
   360         else
   361             return externalAwaitDone();
   362     }
   363 
   364     /**
   365      * Primary mechanics for invoke, quietlyInvoke.
   366      * @return status upon completion
   367      */
   368     private int doInvoke() {
   369         int s; boolean completed;
   370         if ((s = status) < 0)
   371             return s;
   372         try {
   373             completed = exec();
   374         } catch (Throwable rex) {
   375             return setExceptionalCompletion(rex);
   376         }
   377         if (completed)
   378             return setCompletion(NORMAL);
   379         else
   380             return doJoin();
   381     }
   382 
   383     // Exception table support
   384 
   385     /**
   386      * Table of exceptions thrown by tasks, to enable reporting by
   387      * callers. Because exceptions are rare, we don't directly keep
   388      * them with task objects, but instead use a weak ref table.  Note
   389      * that cancellation exceptions don't appear in the table, but are
   390      * instead recorded as status values.
   391      *
   392      * Note: These statics are initialized below in static block.
   393      */
   394     private static final ExceptionNode[] exceptionTable;
   395     private static final ReentrantLock exceptionTableLock;
   396     private static final ReferenceQueue<Object> exceptionTableRefQueue;
   397 
   398     /**
   399      * Fixed capacity for exceptionTable.
   400      */
   401     private static final int EXCEPTION_MAP_CAPACITY = 32;
   402 
   403     /**
   404      * Key-value nodes for exception table.  The chained hash table
   405      * uses identity comparisons, full locking, and weak references
   406      * for keys. The table has a fixed capacity because it only
   407      * maintains task exceptions long enough for joiners to access
   408      * them, so should never become very large for sustained
   409      * periods. However, since we do not know when the last joiner
   410      * completes, we must use weak references and expunge them. We do
   411      * so on each operation (hence full locking). Also, some thread in
   412      * any ForkJoinPool will call helpExpungeStaleExceptions when its
   413      * pool becomes isQuiescent.
   414      */
   415     static final class ExceptionNode extends WeakReference<ForkJoinTask<?>>{
   416         final Throwable ex;
   417         ExceptionNode next;
   418         final long thrower;  // use id not ref to avoid weak cycles
   419         ExceptionNode(ForkJoinTask<?> task, Throwable ex, ExceptionNode next) {
   420             super(task, exceptionTableRefQueue);
   421             this.ex = ex;
   422             this.next = next;
   423             this.thrower = Thread.currentThread().getId();
   424         }
   425     }
   426 
   427     /**
   428      * Records exception and sets exceptional completion.
   429      *
   430      * @return status on exit
   431      */
   432     private int setExceptionalCompletion(Throwable ex) {
   433         int h = System.identityHashCode(this);
   434         final ReentrantLock lock = exceptionTableLock;
   435         lock.lock();
   436         try {
   437             expungeStaleExceptions();
   438             ExceptionNode[] t = exceptionTable;
   439             int i = h & (t.length - 1);
   440             for (ExceptionNode e = t[i]; ; e = e.next) {
   441                 if (e == null) {
   442                     t[i] = new ExceptionNode(this, ex, t[i]);
   443                     break;
   444                 }
   445                 if (e.get() == this) // already present
   446                     break;
   447             }
   448         } finally {
   449             lock.unlock();
   450         }
   451         return setCompletion(EXCEPTIONAL);
   452     }
   453 
   454     /**
   455      * Removes exception node and clears status
   456      */
   457     private void clearExceptionalCompletion() {
   458         int h = System.identityHashCode(this);
   459         final ReentrantLock lock = exceptionTableLock;
   460         lock.lock();
   461         try {
   462             ExceptionNode[] t = exceptionTable;
   463             int i = h & (t.length - 1);
   464             ExceptionNode e = t[i];
   465             ExceptionNode pred = null;
   466             while (e != null) {
   467                 ExceptionNode next = e.next;
   468                 if (e.get() == this) {
   469                     if (pred == null)
   470                         t[i] = next;
   471                     else
   472                         pred.next = next;
   473                     break;
   474                 }
   475                 pred = e;
   476                 e = next;
   477             }
   478             expungeStaleExceptions();
   479             status = 0;
   480         } finally {
   481             lock.unlock();
   482         }
   483     }
   484 
   485     /**
   486      * Returns a rethrowable exception for the given task, if
   487      * available. To provide accurate stack traces, if the exception
   488      * was not thrown by the current thread, we try to create a new
   489      * exception of the same type as the one thrown, but with the
   490      * recorded exception as its cause. If there is no such
   491      * constructor, we instead try to use a no-arg constructor,
   492      * followed by initCause, to the same effect. If none of these
   493      * apply, or any fail due to other exceptions, we return the
   494      * recorded exception, which is still correct, although it may
   495      * contain a misleading stack trace.
   496      *
   497      * @return the exception, or null if none
   498      */
   499     private Throwable getThrowableException() {
   500         if (status != EXCEPTIONAL)
   501             return null;
   502         int h = System.identityHashCode(this);
   503         ExceptionNode e;
   504         final ReentrantLock lock = exceptionTableLock;
   505         lock.lock();
   506         try {
   507             expungeStaleExceptions();
   508             ExceptionNode[] t = exceptionTable;
   509             e = t[h & (t.length - 1)];
   510             while (e != null && e.get() != this)
   511                 e = e.next;
   512         } finally {
   513             lock.unlock();
   514         }
   515         Throwable ex;
   516         if (e == null || (ex = e.ex) == null)
   517             return null;
   518         if (e.thrower != Thread.currentThread().getId()) {
   519             Class ec = ex.getClass();
   520             try {
   521                 Constructor<?> noArgCtor = null;
   522                 Constructor<?>[] cs = ec.getConstructors();// public ctors only
   523                 for (int i = 0; i < cs.length; ++i) {
   524                     Constructor<?> c = cs[i];
   525                     Class<?>[] ps = c.getParameterTypes();
   526                     if (ps.length == 0)
   527                         noArgCtor = c;
   528                     else if (ps.length == 1 && ps[0] == Throwable.class)
   529                         return (Throwable)(c.newInstance(ex));
   530                 }
   531                 if (noArgCtor != null) {
   532                     Throwable wx = (Throwable)(noArgCtor.newInstance());
   533                     wx.initCause(ex);
   534                     return wx;
   535                 }
   536             } catch (Exception ignore) {
   537             }
   538         }
   539         return ex;
   540     }
   541 
   542     /**
   543      * Poll stale refs and remove them. Call only while holding lock.
   544      */
   545     private static void expungeStaleExceptions() {
   546         for (Object x; (x = exceptionTableRefQueue.poll()) != null;) {
   547             if (x instanceof ExceptionNode) {
   548                 ForkJoinTask<?> key = ((ExceptionNode)x).get();
   549                 ExceptionNode[] t = exceptionTable;
   550                 int i = System.identityHashCode(key) & (t.length - 1);
   551                 ExceptionNode e = t[i];
   552                 ExceptionNode pred = null;
   553                 while (e != null) {
   554                     ExceptionNode next = e.next;
   555                     if (e == x) {
   556                         if (pred == null)
   557                             t[i] = next;
   558                         else
   559                             pred.next = next;
   560                         break;
   561                     }
   562                     pred = e;
   563                     e = next;
   564                 }
   565             }
   566         }
   567     }
   568 
   569     /**
   570      * If lock is available, poll stale refs and remove them.
   571      * Called from ForkJoinPool when pools become quiescent.
   572      */
   573     static final void helpExpungeStaleExceptions() {
   574         final ReentrantLock lock = exceptionTableLock;
   575         if (lock.tryLock()) {
   576             try {
   577                 expungeStaleExceptions();
   578             } finally {
   579                 lock.unlock();
   580             }
   581         }
   582     }
   583 
   584     /**
   585      * Report the result of invoke or join; called only upon
   586      * non-normal return of internal versions.
   587      */
   588     private V reportResult() {
   589         int s; Throwable ex;
   590         if ((s = status) == CANCELLED)
   591             throw new CancellationException();
   592         if (s == EXCEPTIONAL && (ex = getThrowableException()) != null)
   593             UNSAFE.throwException(ex);
   594         return getRawResult();
   595     }
   596 
   597     // public methods
   598 
   599     /**
   600      * Arranges to asynchronously execute this task.  While it is not
   601      * necessarily enforced, it is a usage error to fork a task more
   602      * than once unless it has completed and been reinitialized.
   603      * Subsequent modifications to the state of this task or any data
   604      * it operates on are not necessarily consistently observable by
   605      * any thread other than the one executing it unless preceded by a
   606      * call to {@link #join} or related methods, or a call to {@link
   607      * #isDone} returning {@code true}.
   608      *
   609      * <p>This method may be invoked only from within {@code
   610      * ForkJoinPool} computations (as may be determined using method
   611      * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
   612      * result in exceptions or errors, possibly including {@code
   613      * ClassCastException}.
   614      *
   615      * @return {@code this}, to simplify usage
   616      */
   617     public final ForkJoinTask<V> fork() {
   618         ((ForkJoinWorkerThread) Thread.currentThread())
   619             .pushTask(this);
   620         return this;
   621     }
   622 
   623     /**
   624      * Returns the result of the computation when it {@link #isDone is
   625      * done}.  This method differs from {@link #get()} in that
   626      * abnormal completion results in {@code RuntimeException} or
   627      * {@code Error}, not {@code ExecutionException}, and that
   628      * interrupts of the calling thread do <em>not</em> cause the
   629      * method to abruptly return by throwing {@code
   630      * InterruptedException}.
   631      *
   632      * @return the computed result
   633      */
   634     public final V join() {
   635         if (doJoin() != NORMAL)
   636             return reportResult();
   637         else
   638             return getRawResult();
   639     }
   640 
   641     /**
   642      * Commences performing this task, awaits its completion if
   643      * necessary, and returns its result, or throws an (unchecked)
   644      * {@code RuntimeException} or {@code Error} if the underlying
   645      * computation did so.
   646      *
   647      * @return the computed result
   648      */
   649     public final V invoke() {
   650         if (doInvoke() != NORMAL)
   651             return reportResult();
   652         else
   653             return getRawResult();
   654     }
   655 
   656     /**
   657      * Forks the given tasks, returning when {@code isDone} holds for
   658      * each task or an (unchecked) exception is encountered, in which
   659      * case the exception is rethrown. If more than one task
   660      * encounters an exception, then this method throws any one of
   661      * these exceptions. If any task encounters an exception, the
   662      * other may be cancelled. However, the execution status of
   663      * individual tasks is not guaranteed upon exceptional return. The
   664      * status of each task may be obtained using {@link
   665      * #getException()} and related methods to check if they have been
   666      * cancelled, completed normally or exceptionally, or left
   667      * unprocessed.
   668      *
   669      * <p>This method may be invoked only from within {@code
   670      * ForkJoinPool} computations (as may be determined using method
   671      * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
   672      * result in exceptions or errors, possibly including {@code
   673      * ClassCastException}.
   674      *
   675      * @param t1 the first task
   676      * @param t2 the second task
   677      * @throws NullPointerException if any task is null
   678      */
   679     public static void invokeAll(ForkJoinTask<?> t1, ForkJoinTask<?> t2) {
   680         t2.fork();
   681         t1.invoke();
   682         t2.join();
   683     }
   684 
   685     /**
   686      * Forks the given tasks, returning when {@code isDone} holds for
   687      * each task or an (unchecked) exception is encountered, in which
   688      * case the exception is rethrown. If more than one task
   689      * encounters an exception, then this method throws any one of
   690      * these exceptions. If any task encounters an exception, others
   691      * may be cancelled. However, the execution status of individual
   692      * tasks is not guaranteed upon exceptional return. The status of
   693      * each task may be obtained using {@link #getException()} and
   694      * related methods to check if they have been cancelled, completed
   695      * normally or exceptionally, or left unprocessed.
   696      *
   697      * <p>This method may be invoked only from within {@code
   698      * ForkJoinPool} computations (as may be determined using method
   699      * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
   700      * result in exceptions or errors, possibly including {@code
   701      * ClassCastException}.
   702      *
   703      * @param tasks the tasks
   704      * @throws NullPointerException if any task is null
   705      */
   706     public static void invokeAll(ForkJoinTask<?>... tasks) {
   707         Throwable ex = null;
   708         int last = tasks.length - 1;
   709         for (int i = last; i >= 0; --i) {
   710             ForkJoinTask<?> t = tasks[i];
   711             if (t == null) {
   712                 if (ex == null)
   713                     ex = new NullPointerException();
   714             }
   715             else if (i != 0)
   716                 t.fork();
   717             else if (t.doInvoke() < NORMAL && ex == null)
   718                 ex = t.getException();
   719         }
   720         for (int i = 1; i <= last; ++i) {
   721             ForkJoinTask<?> t = tasks[i];
   722             if (t != null) {
   723                 if (ex != null)
   724                     t.cancel(false);
   725                 else if (t.doJoin() < NORMAL && ex == null)
   726                     ex = t.getException();
   727             }
   728         }
   729         if (ex != null)
   730             UNSAFE.throwException(ex);
   731     }
   732 
   733     /**
   734      * Forks all tasks in the specified collection, returning when
   735      * {@code isDone} holds for each task or an (unchecked) exception
   736      * is encountered, in which case the exception is rethrown. If
   737      * more than one task encounters an exception, then this method
   738      * throws any one of these exceptions. If any task encounters an
   739      * exception, others may be cancelled. However, the execution
   740      * status of individual tasks is not guaranteed upon exceptional
   741      * return. The status of each task may be obtained using {@link
   742      * #getException()} and related methods to check if they have been
   743      * cancelled, completed normally or exceptionally, or left
   744      * unprocessed.
   745      *
   746      * <p>This method may be invoked only from within {@code
   747      * ForkJoinPool} computations (as may be determined using method
   748      * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
   749      * result in exceptions or errors, possibly including {@code
   750      * ClassCastException}.
   751      *
   752      * @param tasks the collection of tasks
   753      * @return the tasks argument, to simplify usage
   754      * @throws NullPointerException if tasks or any element are null
   755      */
   756     public static <T extends ForkJoinTask<?>> Collection<T> invokeAll(Collection<T> tasks) {
   757         if (!(tasks instanceof RandomAccess) || !(tasks instanceof List<?>)) {
   758             invokeAll(tasks.toArray(new ForkJoinTask<?>[tasks.size()]));
   759             return tasks;
   760         }
   761         @SuppressWarnings("unchecked")
   762         List<? extends ForkJoinTask<?>> ts =
   763             (List<? extends ForkJoinTask<?>>) tasks;
   764         Throwable ex = null;
   765         int last = ts.size() - 1;
   766         for (int i = last; i >= 0; --i) {
   767             ForkJoinTask<?> t = ts.get(i);
   768             if (t == null) {
   769                 if (ex == null)
   770                     ex = new NullPointerException();
   771             }
   772             else if (i != 0)
   773                 t.fork();
   774             else if (t.doInvoke() < NORMAL && ex == null)
   775                 ex = t.getException();
   776         }
   777         for (int i = 1; i <= last; ++i) {
   778             ForkJoinTask<?> t = ts.get(i);
   779             if (t != null) {
   780                 if (ex != null)
   781                     t.cancel(false);
   782                 else if (t.doJoin() < NORMAL && ex == null)
   783                     ex = t.getException();
   784             }
   785         }
   786         if (ex != null)
   787             UNSAFE.throwException(ex);
   788         return tasks;
   789     }
   790 
   791     /**
   792      * Attempts to cancel execution of this task. This attempt will
   793      * fail if the task has already completed or could not be
   794      * cancelled for some other reason. If successful, and this task
   795      * has not started when {@code cancel} is called, execution of
   796      * this task is suppressed. After this method returns
   797      * successfully, unless there is an intervening call to {@link
   798      * #reinitialize}, subsequent calls to {@link #isCancelled},
   799      * {@link #isDone}, and {@code cancel} will return {@code true}
   800      * and calls to {@link #join} and related methods will result in
   801      * {@code CancellationException}.
   802      *
   803      * <p>This method may be overridden in subclasses, but if so, must
   804      * still ensure that these properties hold. In particular, the
   805      * {@code cancel} method itself must not throw exceptions.
   806      *
   807      * <p>This method is designed to be invoked by <em>other</em>
   808      * tasks. To terminate the current task, you can just return or
   809      * throw an unchecked exception from its computation method, or
   810      * invoke {@link #completeExceptionally}.
   811      *
   812      * @param mayInterruptIfRunning this value has no effect in the
   813      * default implementation because interrupts are not used to
   814      * control cancellation.
   815      *
   816      * @return {@code true} if this task is now cancelled
   817      */
   818     public boolean cancel(boolean mayInterruptIfRunning) {
   819         return setCompletion(CANCELLED) == CANCELLED;
   820     }
   821 
   822     /**
   823      * Cancels, ignoring any exceptions thrown by cancel. Used during
   824      * worker and pool shutdown. Cancel is spec'ed not to throw any
   825      * exceptions, but if it does anyway, we have no recourse during
   826      * shutdown, so guard against this case.
   827      */
   828     final void cancelIgnoringExceptions() {
   829         try {
   830             cancel(false);
   831         } catch (Throwable ignore) {
   832         }
   833     }
   834 
   835     public final boolean isDone() {
   836         return status < 0;
   837     }
   838 
   839     public final boolean isCancelled() {
   840         return status == CANCELLED;
   841     }
   842 
   843     /**
   844      * Returns {@code true} if this task threw an exception or was cancelled.
   845      *
   846      * @return {@code true} if this task threw an exception or was cancelled
   847      */
   848     public final boolean isCompletedAbnormally() {
   849         return status < NORMAL;
   850     }
   851 
   852     /**
   853      * Returns {@code true} if this task completed without throwing an
   854      * exception and was not cancelled.
   855      *
   856      * @return {@code true} if this task completed without throwing an
   857      * exception and was not cancelled
   858      */
   859     public final boolean isCompletedNormally() {
   860         return status == NORMAL;
   861     }
   862 
   863     /**
   864      * Returns the exception thrown by the base computation, or a
   865      * {@code CancellationException} if cancelled, or {@code null} if
   866      * none or if the method has not yet completed.
   867      *
   868      * @return the exception, or {@code null} if none
   869      */
   870     public final Throwable getException() {
   871         int s = status;
   872         return ((s >= NORMAL)    ? null :
   873                 (s == CANCELLED) ? new CancellationException() :
   874                 getThrowableException());
   875     }
   876 
   877     /**
   878      * Completes this task abnormally, and if not already aborted or
   879      * cancelled, causes it to throw the given exception upon
   880      * {@code join} and related operations. This method may be used
   881      * to induce exceptions in asynchronous tasks, or to force
   882      * completion of tasks that would not otherwise complete.  Its use
   883      * in other situations is discouraged.  This method is
   884      * overridable, but overridden versions must invoke {@code super}
   885      * implementation to maintain guarantees.
   886      *
   887      * @param ex the exception to throw. If this exception is not a
   888      * {@code RuntimeException} or {@code Error}, the actual exception
   889      * thrown will be a {@code RuntimeException} with cause {@code ex}.
   890      */
   891     public void completeExceptionally(Throwable ex) {
   892         setExceptionalCompletion((ex instanceof RuntimeException) ||
   893                                  (ex instanceof Error) ? ex :
   894                                  new RuntimeException(ex));
   895     }
   896 
   897     /**
   898      * Completes this task, and if not already aborted or cancelled,
   899      * returning the given value as the result of subsequent
   900      * invocations of {@code join} and related operations. This method
   901      * may be used to provide results for asynchronous tasks, or to
   902      * provide alternative handling for tasks that would not otherwise
   903      * complete normally. Its use in other situations is
   904      * discouraged. This method is overridable, but overridden
   905      * versions must invoke {@code super} implementation to maintain
   906      * guarantees.
   907      *
   908      * @param value the result value for this task
   909      */
   910     public void complete(V value) {
   911         try {
   912             setRawResult(value);
   913         } catch (Throwable rex) {
   914             setExceptionalCompletion(rex);
   915             return;
   916         }
   917         setCompletion(NORMAL);
   918     }
   919 
   920     /**
   921      * Waits if necessary for the computation to complete, and then
   922      * retrieves its result.
   923      *
   924      * @return the computed result
   925      * @throws CancellationException if the computation was cancelled
   926      * @throws ExecutionException if the computation threw an
   927      * exception
   928      * @throws InterruptedException if the current thread is not a
   929      * member of a ForkJoinPool and was interrupted while waiting
   930      */
   931     public final V get() throws InterruptedException, ExecutionException {
   932         int s = (Thread.currentThread() instanceof ForkJoinWorkerThread) ?
   933             doJoin() : externalInterruptibleAwaitDone(0L);
   934         Throwable ex;
   935         if (s == CANCELLED)
   936             throw new CancellationException();
   937         if (s == EXCEPTIONAL && (ex = getThrowableException()) != null)
   938             throw new ExecutionException(ex);
   939         return getRawResult();
   940     }
   941 
   942     /**
   943      * Waits if necessary for at most the given time for the computation
   944      * to complete, and then retrieves its result, if available.
   945      *
   946      * @param timeout the maximum time to wait
   947      * @param unit the time unit of the timeout argument
   948      * @return the computed result
   949      * @throws CancellationException if the computation was cancelled
   950      * @throws ExecutionException if the computation threw an
   951      * exception
   952      * @throws InterruptedException if the current thread is not a
   953      * member of a ForkJoinPool and was interrupted while waiting
   954      * @throws TimeoutException if the wait timed out
   955      */
   956     public final V get(long timeout, TimeUnit unit)
   957         throws InterruptedException, ExecutionException, TimeoutException {
   958         Thread t = Thread.currentThread();
   959         if (t instanceof ForkJoinWorkerThread) {
   960             ForkJoinWorkerThread w = (ForkJoinWorkerThread) t;
   961             long nanos = unit.toNanos(timeout);
   962             if (status >= 0) {
   963                 boolean completed = false;
   964                 if (w.unpushTask(this)) {
   965                     try {
   966                         completed = exec();
   967                     } catch (Throwable rex) {
   968                         setExceptionalCompletion(rex);
   969                     }
   970                 }
   971                 if (completed)
   972                     setCompletion(NORMAL);
   973                 else if (status >= 0 && nanos > 0)
   974                     w.pool.timedAwaitJoin(this, nanos);
   975             }
   976         }
   977         else {
   978             long millis = unit.toMillis(timeout);
   979             if (millis > 0)
   980                 externalInterruptibleAwaitDone(millis);
   981         }
   982         int s = status;
   983         if (s != NORMAL) {
   984             Throwable ex;
   985             if (s == CANCELLED)
   986                 throw new CancellationException();
   987             if (s != EXCEPTIONAL)
   988                 throw new TimeoutException();
   989             if ((ex = getThrowableException()) != null)
   990                 throw new ExecutionException(ex);
   991         }
   992         return getRawResult();
   993     }
   994 
   995     /**
   996      * Joins this task, without returning its result or throwing its
   997      * exception. This method may be useful when processing
   998      * collections of tasks when some have been cancelled or otherwise
   999      * known to have aborted.
  1000      */
  1001     public final void quietlyJoin() {
  1002         doJoin();
  1003     }
  1004 
  1005     /**
  1006      * Commences performing this task and awaits its completion if
  1007      * necessary, without returning its result or throwing its
  1008      * exception.
  1009      */
  1010     public final void quietlyInvoke() {
  1011         doInvoke();
  1012     }
  1013 
  1014     /**
  1015      * Possibly executes tasks until the pool hosting the current task
  1016      * {@link ForkJoinPool#isQuiescent is quiescent}. This method may
  1017      * be of use in designs in which many tasks are forked, but none
  1018      * are explicitly joined, instead executing them until all are
  1019      * processed.
  1020      *
  1021      * <p>This method may be invoked only from within {@code
  1022      * ForkJoinPool} computations (as may be determined using method
  1023      * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
  1024      * result in exceptions or errors, possibly including {@code
  1025      * ClassCastException}.
  1026      */
  1027     public static void helpQuiesce() {
  1028         ((ForkJoinWorkerThread) Thread.currentThread())
  1029             .helpQuiescePool();
  1030     }
  1031 
  1032     /**
  1033      * Resets the internal bookkeeping state of this task, allowing a
  1034      * subsequent {@code fork}. This method allows repeated reuse of
  1035      * this task, but only if reuse occurs when this task has either
  1036      * never been forked, or has been forked, then completed and all
  1037      * outstanding joins of this task have also completed. Effects
  1038      * under any other usage conditions are not guaranteed.
  1039      * This method may be useful when executing
  1040      * pre-constructed trees of subtasks in loops.
  1041      *
  1042      * <p>Upon completion of this method, {@code isDone()} reports
  1043      * {@code false}, and {@code getException()} reports {@code
  1044      * null}. However, the value returned by {@code getRawResult} is
  1045      * unaffected. To clear this value, you can invoke {@code
  1046      * setRawResult(null)}.
  1047      */
  1048     public void reinitialize() {
  1049         if (status == EXCEPTIONAL)
  1050             clearExceptionalCompletion();
  1051         else
  1052             status = 0;
  1053     }
  1054 
  1055     /**
  1056      * Returns the pool hosting the current task execution, or null
  1057      * if this task is executing outside of any ForkJoinPool.
  1058      *
  1059      * @see #inForkJoinPool
  1060      * @return the pool, or {@code null} if none
  1061      */
  1062     public static ForkJoinPool getPool() {
  1063         Thread t = Thread.currentThread();
  1064         return (t instanceof ForkJoinWorkerThread) ?
  1065             ((ForkJoinWorkerThread) t).pool : null;
  1066     }
  1067 
  1068     /**
  1069      * Returns {@code true} if the current thread is a {@link
  1070      * ForkJoinWorkerThread} executing as a ForkJoinPool computation.
  1071      *
  1072      * @return {@code true} if the current thread is a {@link
  1073      * ForkJoinWorkerThread} executing as a ForkJoinPool computation,
  1074      * or {@code false} otherwise
  1075      */
  1076     public static boolean inForkJoinPool() {
  1077         return Thread.currentThread() instanceof ForkJoinWorkerThread;
  1078     }
  1079 
  1080     /**
  1081      * Tries to unschedule this task for execution. This method will
  1082      * typically succeed if this task is the most recently forked task
  1083      * by the current thread, and has not commenced executing in
  1084      * another thread.  This method may be useful when arranging
  1085      * alternative local processing of tasks that could have been, but
  1086      * were not, stolen.
  1087      *
  1088      * <p>This method may be invoked only from within {@code
  1089      * ForkJoinPool} computations (as may be determined using method
  1090      * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
  1091      * result in exceptions or errors, possibly including {@code
  1092      * ClassCastException}.
  1093      *
  1094      * @return {@code true} if unforked
  1095      */
  1096     public boolean tryUnfork() {
  1097         return ((ForkJoinWorkerThread) Thread.currentThread())
  1098             .unpushTask(this);
  1099     }
  1100 
  1101     /**
  1102      * Returns an estimate of the number of tasks that have been
  1103      * forked by the current worker thread but not yet executed. This
  1104      * value may be useful for heuristic decisions about whether to
  1105      * fork other tasks.
  1106      *
  1107      * <p>This method may be invoked only from within {@code
  1108      * ForkJoinPool} computations (as may be determined using method
  1109      * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
  1110      * result in exceptions or errors, possibly including {@code
  1111      * ClassCastException}.
  1112      *
  1113      * @return the number of tasks
  1114      */
  1115     public static int getQueuedTaskCount() {
  1116         return ((ForkJoinWorkerThread) Thread.currentThread())
  1117             .getQueueSize();
  1118     }
  1119 
  1120     /**
  1121      * Returns an estimate of how many more locally queued tasks are
  1122      * held by the current worker thread than there are other worker
  1123      * threads that might steal them.  This value may be useful for
  1124      * heuristic decisions about whether to fork other tasks. In many
  1125      * usages of ForkJoinTasks, at steady state, each worker should
  1126      * aim to maintain a small constant surplus (for example, 3) of
  1127      * tasks, and to process computations locally if this threshold is
  1128      * exceeded.
  1129      *
  1130      * <p>This method may be invoked only from within {@code
  1131      * ForkJoinPool} computations (as may be determined using method
  1132      * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
  1133      * result in exceptions or errors, possibly including {@code
  1134      * ClassCastException}.
  1135      *
  1136      * @return the surplus number of tasks, which may be negative
  1137      */
  1138     public static int getSurplusQueuedTaskCount() {
  1139         return ((ForkJoinWorkerThread) Thread.currentThread())
  1140             .getEstimatedSurplusTaskCount();
  1141     }
  1142 
  1143     // Extension methods
  1144 
  1145     /**
  1146      * Returns the result that would be returned by {@link #join}, even
  1147      * if this task completed abnormally, or {@code null} if this task
  1148      * is not known to have been completed.  This method is designed
  1149      * to aid debugging, as well as to support extensions. Its use in
  1150      * any other context is discouraged.
  1151      *
  1152      * @return the result, or {@code null} if not completed
  1153      */
  1154     public abstract V getRawResult();
  1155 
  1156     /**
  1157      * Forces the given value to be returned as a result.  This method
  1158      * is designed to support extensions, and should not in general be
  1159      * called otherwise.
  1160      *
  1161      * @param value the value
  1162      */
  1163     protected abstract void setRawResult(V value);
  1164 
  1165     /**
  1166      * Immediately performs the base action of this task.  This method
  1167      * is designed to support extensions, and should not in general be
  1168      * called otherwise. The return value controls whether this task
  1169      * is considered to be done normally. It may return false in
  1170      * asynchronous actions that require explicit invocations of
  1171      * {@link #complete} to become joinable. It may also throw an
  1172      * (unchecked) exception to indicate abnormal exit.
  1173      *
  1174      * @return {@code true} if completed normally
  1175      */
  1176     protected abstract boolean exec();
  1177 
  1178     /**
  1179      * Returns, but does not unschedule or execute, a task queued by
  1180      * the current thread but not yet executed, if one is immediately
  1181      * available. There is no guarantee that this task will actually
  1182      * be polled or executed next. Conversely, this method may return
  1183      * null even if a task exists but cannot be accessed without
  1184      * contention with other threads.  This method is designed
  1185      * primarily to support extensions, and is unlikely to be useful
  1186      * otherwise.
  1187      *
  1188      * <p>This method may be invoked only from within {@code
  1189      * ForkJoinPool} computations (as may be determined using method
  1190      * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
  1191      * result in exceptions or errors, possibly including {@code
  1192      * ClassCastException}.
  1193      *
  1194      * @return the next task, or {@code null} if none are available
  1195      */
  1196     protected static ForkJoinTask<?> peekNextLocalTask() {
  1197         return ((ForkJoinWorkerThread) Thread.currentThread())
  1198             .peekTask();
  1199     }
  1200 
  1201     /**
  1202      * Unschedules and returns, without executing, the next task
  1203      * queued by the current thread but not yet executed.  This method
  1204      * is designed primarily to support extensions, and is unlikely to
  1205      * be useful otherwise.
  1206      *
  1207      * <p>This method may be invoked only from within {@code
  1208      * ForkJoinPool} computations (as may be determined using method
  1209      * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
  1210      * result in exceptions or errors, possibly including {@code
  1211      * ClassCastException}.
  1212      *
  1213      * @return the next task, or {@code null} if none are available
  1214      */
  1215     protected static ForkJoinTask<?> pollNextLocalTask() {
  1216         return ((ForkJoinWorkerThread) Thread.currentThread())
  1217             .pollLocalTask();
  1218     }
  1219 
  1220     /**
  1221      * Unschedules and returns, without executing, the next task
  1222      * queued by the current thread but not yet executed, if one is
  1223      * available, or if not available, a task that was forked by some
  1224      * other thread, if available. Availability may be transient, so a
  1225      * {@code null} result does not necessarily imply quiescence
  1226      * of the pool this task is operating in.  This method is designed
  1227      * primarily to support extensions, and is unlikely to be useful
  1228      * otherwise.
  1229      *
  1230      * <p>This method may be invoked only from within {@code
  1231      * ForkJoinPool} computations (as may be determined using method
  1232      * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
  1233      * result in exceptions or errors, possibly including {@code
  1234      * ClassCastException}.
  1235      *
  1236      * @return a task, or {@code null} if none are available
  1237      */
  1238     protected static ForkJoinTask<?> pollTask() {
  1239         return ((ForkJoinWorkerThread) Thread.currentThread())
  1240             .pollTask();
  1241     }
  1242 
  1243     /**
  1244      * Adaptor for Runnables. This implements RunnableFuture
  1245      * to be compliant with AbstractExecutorService constraints
  1246      * when used in ForkJoinPool.
  1247      */
  1248     static final class AdaptedRunnable<T> extends ForkJoinTask<T>
  1249         implements RunnableFuture<T> {
  1250         final Runnable runnable;
  1251         final T resultOnCompletion;
  1252         T result;
  1253         AdaptedRunnable(Runnable runnable, T result) {
  1254             if (runnable == null) throw new NullPointerException();
  1255             this.runnable = runnable;
  1256             this.resultOnCompletion = result;
  1257         }
  1258         public T getRawResult() { return result; }
  1259         public void setRawResult(T v) { result = v; }
  1260         public boolean exec() {
  1261             runnable.run();
  1262             result = resultOnCompletion;
  1263             return true;
  1264         }
  1265         public void run() { invoke(); }
  1266         private static final long serialVersionUID = 5232453952276885070L;
  1267     }
  1268 
  1269     /**
  1270      * Adaptor for Callables
  1271      */
  1272     static final class AdaptedCallable<T> extends ForkJoinTask<T>
  1273         implements RunnableFuture<T> {
  1274         final Callable<? extends T> callable;
  1275         T result;
  1276         AdaptedCallable(Callable<? extends T> callable) {
  1277             if (callable == null) throw new NullPointerException();
  1278             this.callable = callable;
  1279         }
  1280         public T getRawResult() { return result; }
  1281         public void setRawResult(T v) { result = v; }
  1282         public boolean exec() {
  1283             try {
  1284                 result = callable.call();
  1285                 return true;
  1286             } catch (Error err) {
  1287                 throw err;
  1288             } catch (RuntimeException rex) {
  1289                 throw rex;
  1290             } catch (Exception ex) {
  1291                 throw new RuntimeException(ex);
  1292             }
  1293         }
  1294         public void run() { invoke(); }
  1295         private static final long serialVersionUID = 2838392045355241008L;
  1296     }
  1297 
  1298     /**
  1299      * Returns a new {@code ForkJoinTask} that performs the {@code run}
  1300      * method of the given {@code Runnable} as its action, and returns
  1301      * a null result upon {@link #join}.
  1302      *
  1303      * @param runnable the runnable action
  1304      * @return the task
  1305      */
  1306     public static ForkJoinTask<?> adapt(Runnable runnable) {
  1307         return new AdaptedRunnable<Void>(runnable, null);
  1308     }
  1309 
  1310     /**
  1311      * Returns a new {@code ForkJoinTask} that performs the {@code run}
  1312      * method of the given {@code Runnable} as its action, and returns
  1313      * the given result upon {@link #join}.
  1314      *
  1315      * @param runnable the runnable action
  1316      * @param result the result upon completion
  1317      * @return the task
  1318      */
  1319     public static <T> ForkJoinTask<T> adapt(Runnable runnable, T result) {
  1320         return new AdaptedRunnable<T>(runnable, result);
  1321     }
  1322 
  1323     /**
  1324      * Returns a new {@code ForkJoinTask} that performs the {@code call}
  1325      * method of the given {@code Callable} as its action, and returns
  1326      * its result upon {@link #join}, translating any checked exceptions
  1327      * encountered into {@code RuntimeException}.
  1328      *
  1329      * @param callable the callable action
  1330      * @return the task
  1331      */
  1332     public static <T> ForkJoinTask<T> adapt(Callable<? extends T> callable) {
  1333         return new AdaptedCallable<T>(callable);
  1334     }
  1335 
  1336     // Serialization support
  1337 
  1338     private static final long serialVersionUID = -7721805057305804111L;
  1339 
  1340     /**
  1341      * Saves the state to a stream (that is, serializes it).
  1342      *
  1343      * @serialData the current run status and the exception thrown
  1344      * during execution, or {@code null} if none
  1345      * @param s the stream
  1346      */
  1347     private void writeObject(java.io.ObjectOutputStream s)
  1348         throws java.io.IOException {
  1349         s.defaultWriteObject();
  1350         s.writeObject(getException());
  1351     }
  1352 
  1353     /**
  1354      * Reconstitutes the instance from a stream (that is, deserializes it).
  1355      *
  1356      * @param s the stream
  1357      */
  1358     private void readObject(java.io.ObjectInputStream s)
  1359         throws java.io.IOException, ClassNotFoundException {
  1360         s.defaultReadObject();
  1361         Object ex = s.readObject();
  1362         if (ex != null)
  1363             setExceptionalCompletion((Throwable)ex);
  1364     }
  1365 
  1366     // Unsafe mechanics
  1367     private static final Unsafe UNSAFE;
  1368     private static final long statusOffset;
  1369     static {
  1370         exceptionTableLock = new ReentrantLock();
  1371         exceptionTableRefQueue = new ReferenceQueue<Object>();
  1372         exceptionTable = new ExceptionNode[EXCEPTION_MAP_CAPACITY];
  1373         try {
  1374             UNSAFE = Unsafe.getUnsafe();
  1375             statusOffset = UNSAFE.objectFieldOffset
  1376                 (ForkJoinTask.class.getDeclaredField("status"));
  1377         } catch (Exception e) {
  1378             throw new Error(e);
  1379         }
  1380     }
  1381 
  1382 }