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