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