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.lang.Thread.UncaughtExceptionHandler;
  39 import java.security.AccessControlContext;
  40 import java.security.Permissions;
  41 import java.security.ProtectionDomain;
  42 import java.util.ArrayList;
  43 import java.util.Arrays;
  44 import java.util.Collection;
  45 import java.util.Collections;
  46 import java.util.List;
  47 import java.util.concurrent.locks.ReentrantLock;
  48 import java.util.concurrent.locks.LockSupport;
  49 
  50 /**
  51  * An {@link ExecutorService} for running {@link ForkJoinTask}s.
  52  * A {@code ForkJoinPool} provides the entry point for submissions
  53  * from non-{@code ForkJoinTask} clients, as well as management and
  54  * monitoring operations.
  55  *
  56  * <p>A {@code ForkJoinPool} differs from other kinds of {@link
  57  * ExecutorService} mainly by virtue of employing
  58  * <em>work-stealing</em>: all threads in the pool attempt to find and
  59  * execute tasks submitted to the pool and/or created by other active
  60  * tasks (eventually blocking waiting for work if none exist). This
  61  * enables efficient processing when most tasks spawn other subtasks
  62  * (as do most {@code ForkJoinTask}s), as well as when many small
  63  * tasks are submitted to the pool from external clients.  Especially
  64  * when setting <em>asyncMode</em> to true in constructors, {@code
  65  * ForkJoinPool}s may also be appropriate for use with event-style
  66  * tasks that are never joined.
  67  *
  68  * <p>A static {@link #commonPool()} is available and appropriate for
  69  * most applications. The common pool is used by any ForkJoinTask that
  70  * is not explicitly submitted to a specified pool. Using the common
  71  * pool normally reduces resource usage (its threads are slowly
  72  * reclaimed during periods of non-use, and reinstated upon subsequent
  73  * use).
  74  *
  75  * <p>For applications that require separate or custom pools, a {@code
  76  * ForkJoinPool} may be constructed with a given target parallelism
  77  * level; by default, equal to the number of available processors.
  78  * The pool attempts to maintain enough active (or available) threads
  79  * by dynamically adding, suspending, or resuming internal worker
  80  * threads, even if some tasks are stalled waiting to join others.
  81  * However, no such adjustments are guaranteed in the face of blocked
  82  * I/O or other unmanaged synchronization. The nested {@link
  83  * ManagedBlocker} interface enables extension of the kinds of
  84  * synchronization accommodated.
  85  *
  86  * <p>In addition to execution and lifecycle control methods, this
  87  * class provides status check methods (for example
  88  * {@link #getStealCount}) that are intended to aid in developing,
  89  * tuning, and monitoring fork/join applications. Also, method
  90  * {@link #toString} returns indications of pool state in a
  91  * convenient form for informal monitoring.
  92  *
  93  * <p>As is the case with other ExecutorServices, there are three
  94  * main task execution methods summarized in the following table.
  95  * These are designed to be used primarily by clients not already
  96  * engaged in fork/join computations in the current pool.  The main
  97  * forms of these methods accept instances of {@code ForkJoinTask},
  98  * but overloaded forms also allow mixed execution of plain {@code
  99  * Runnable}- or {@code Callable}- based activities as well.  However,
 100  * tasks that are already executing in a pool should normally instead
 101  * use the within-computation forms listed in the table unless using
 102  * async event-style tasks that are not usually joined, in which case
 103  * there is little difference among choice of methods.
 104  *
 105  * <table BORDER CELLPADDING=3 CELLSPACING=1>
 106  * <caption>Summary of task execution methods</caption>
 107  *  <tr>
 108  *    <td></td>
 109  *    <td ALIGN=CENTER> <b>Call from non-fork/join clients</b></td>
 110  *    <td ALIGN=CENTER> <b>Call from within fork/join computations</b></td>
 111  *  </tr>
 112  *  <tr>
 113  *    <td> <b>Arrange async execution</b></td>
 114  *    <td> {@link #execute(ForkJoinTask)}</td>
 115  *    <td> {@link ForkJoinTask#fork}</td>
 116  *  </tr>
 117  *  <tr>
 118  *    <td> <b>Await and obtain result</b></td>
 119  *    <td> {@link #invoke(ForkJoinTask)}</td>
 120  *    <td> {@link ForkJoinTask#invoke}</td>
 121  *  </tr>
 122  *  <tr>
 123  *    <td> <b>Arrange exec and obtain Future</b></td>
 124  *    <td> {@link #submit(ForkJoinTask)}</td>
 125  *    <td> {@link ForkJoinTask#fork} (ForkJoinTasks <em>are</em> Futures)</td>
 126  *  </tr>
 127  * </table>
 128  *
 129  * <p>The common pool is by default constructed with default
 130  * parameters, but these may be controlled by setting three
 131  * {@linkplain System#getProperty system properties}:
 132  * <ul>
 133  * <li>{@code java.util.concurrent.ForkJoinPool.common.parallelism}
 134  * - the parallelism level, a non-negative integer
 135  * <li>{@code java.util.concurrent.ForkJoinPool.common.threadFactory}
 136  * - the class name of a {@link ForkJoinWorkerThreadFactory}
 137  * <li>{@code java.util.concurrent.ForkJoinPool.common.exceptionHandler}
 138  * - the class name of a {@link UncaughtExceptionHandler}
 139  * <li>{@code java.util.concurrent.ForkJoinPool.common.maximumSpares}
 140  * - the maximum number of allowed extra threads to maintain target
 141  * parallelism (default 256).
 142  * </ul>
 143  * If a {@link SecurityManager} is present and no factory is
 144  * specified, then the default pool uses a factory supplying
 145  * threads that have no {@link Permissions} enabled.
 146  * The system class loader is used to load these classes.
 147  * Upon any error in establishing these settings, default parameters
 148  * are used. It is possible to disable or limit the use of threads in
 149  * the common pool by setting the parallelism property to zero, and/or
 150  * using a factory that may return {@code null}. However doing so may
 151  * cause unjoined tasks to never be executed.
 152  *
 153  * <p><b>Implementation notes</b>: This implementation restricts the
 154  * maximum number of running threads to 32767. Attempts to create
 155  * pools with greater than the maximum number result in
 156  * {@code IllegalArgumentException}.
 157  *
 158  * <p>This implementation rejects submitted tasks (that is, by throwing
 159  * {@link RejectedExecutionException}) only when the pool is shut down
 160  * or internal resources have been exhausted.
 161  *
 162  * @since 1.7
 163  * @author Doug Lea
 164  */
 165 @sun.misc.Contended
 166 public class ForkJoinPool extends AbstractExecutorService {
 167 
 168     /*
 169      * Implementation Overview
 170      *
 171      * This class and its nested classes provide the main
 172      * functionality and control for a set of worker threads:
 173      * Submissions from non-FJ threads enter into submission queues.
 174      * Workers take these tasks and typically split them into subtasks
 175      * that may be stolen by other workers.  Preference rules give
 176      * first priority to processing tasks from their own queues (LIFO
 177      * or FIFO, depending on mode), then to randomized FIFO steals of
 178      * tasks in other queues.  This framework began as vehicle for
 179      * supporting tree-structured parallelism using work-stealing.
 180      * Over time, its scalability advantages led to extensions and
 181      * changes to better support more diverse usage contexts.  Because
 182      * most internal methods and nested classes are interrelated,
 183      * their main rationale and descriptions are presented here;
 184      * individual methods and nested classes contain only brief
 185      * comments about details.
 186      *
 187      * WorkQueues
 188      * ==========
 189      *
 190      * Most operations occur within work-stealing queues (in nested
 191      * class WorkQueue).  These are special forms of Deques that
 192      * support only three of the four possible end-operations -- push,
 193      * pop, and poll (aka steal), under the further constraints that
 194      * push and pop are called only from the owning thread (or, as
 195      * extended here, under a lock), while poll may be called from
 196      * other threads.  (If you are unfamiliar with them, you probably
 197      * want to read Herlihy and Shavit's book "The Art of
 198      * Multiprocessor programming", chapter 16 describing these in
 199      * more detail before proceeding.)  The main work-stealing queue
 200      * design is roughly similar to those in the papers "Dynamic
 201      * Circular Work-Stealing Deque" by Chase and Lev, SPAA 2005
 202      * (http://research.sun.com/scalable/pubs/index.html) and
 203      * "Idempotent work stealing" by Michael, Saraswat, and Vechev,
 204      * PPoPP 2009 (http://portal.acm.org/citation.cfm?id=1504186).
 205      * The main differences ultimately stem from GC requirements that
 206      * we null out taken slots as soon as we can, to maintain as small
 207      * a footprint as possible even in programs generating huge
 208      * numbers of tasks. To accomplish this, we shift the CAS
 209      * arbitrating pop vs poll (steal) from being on the indices
 210      * ("base" and "top") to the slots themselves.
 211      *
 212      * Adding tasks then takes the form of a classic array push(task)
 213      * in a circular buffer:
 214      *    q.array[q.top++ % length] = task;
 215      *
 216      * (The actual code needs to null-check and size-check the array,
 217      * uses masking, not mod, for indexing a power-of-two-sized array,
 218      * properly fences accesses, and possibly signals waiting workers
 219      * to start scanning -- see below.)  Both a successful pop and
 220      * poll mainly entail a CAS of a slot from non-null to null.
 221      *
 222      * The pop operation (always performed by owner) is:
 223      *   if ((the task at top slot is not null) and
 224      *        (CAS slot to null))
 225      *           decrement top and return task;
 226      *
 227      * And the poll operation (usually by a stealer) is
 228      *    if ((the task at base slot is not null) and
 229      *        (CAS slot to null))
 230      *           increment base and return task;
 231      *
 232      * There are several variants of each of these; for example most
 233      * versions of poll pre-screen the CAS by rechecking that the base
 234      * has not changed since reading the slot, and most methods only
 235      * attempt the CAS if base appears not to be equal to top.
 236      *
 237      * Memory ordering.  See "Correct and Efficient Work-Stealing for
 238      * Weak Memory Models" by Le, Pop, Cohen, and Nardelli, PPoPP 2013
 239      * (http://www.di.ens.fr/~zappa/readings/ppopp13.pdf) for an
 240      * analysis of memory ordering requirements in work-stealing
 241      * algorithms similar to (but different than) the one used here.
 242      * Extracting tasks in array slots via (fully fenced) CAS provides
 243      * primary synchronization. The base and top indices imprecisely
 244      * guide where to extract from. We do not always require strict
 245      * orderings of array and index updates, so sometimes let them be
 246      * subject to compiler and processor reorderings. However, the
 247      * volatile "base" index also serves as a basis for memory
 248      * ordering: Slot accesses are preceded by a read of base,
 249      * ensuring happens-before ordering with respect to stealers (so
 250      * the slots themselves can be read via plain array reads.)  The
 251      * only other memory orderings relied on are maintained in the
 252      * course of signalling and activation (see below).  A check that
 253      * base == top indicates (momentary) emptiness, but otherwise may
 254      * err on the side of possibly making the queue appear nonempty
 255      * when a push, pop, or poll have not fully committed, or making
 256      * it appear empty when an update of top has not yet been visibly
 257      * written.  (Method isEmpty() checks the case of a partially
 258      * completed removal of the last element.)  Because of this, the
 259      * poll operation, considered individually, is not wait-free. One
 260      * thief cannot successfully continue until another in-progress
 261      * one (or, if previously empty, a push) visibly completes.
 262      * However, in the aggregate, we ensure at least probabilistic
 263      * non-blockingness.  If an attempted steal fails, a scanning
 264      * thief chooses a different random victim target to try next. So,
 265      * in order for one thief to progress, it suffices for any
 266      * in-progress poll or new push on any empty queue to
 267      * complete. (This is why we normally use method pollAt and its
 268      * variants that try once at the apparent base index, else
 269      * consider alternative actions, rather than method poll, which
 270      * retries.)
 271      *
 272      * This approach also enables support of a user mode in which
 273      * local task processing is in FIFO, not LIFO order, simply by
 274      * using poll rather than pop.  This can be useful in
 275      * message-passing frameworks in which tasks are never joined.
 276      *
 277      * WorkQueues are also used in a similar way for tasks submitted
 278      * to the pool. We cannot mix these tasks in the same queues used
 279      * by workers. Instead, we randomly associate submission queues
 280      * with submitting threads, using a form of hashing.  The
 281      * ThreadLocalRandom probe value serves as a hash code for
 282      * choosing existing queues, and may be randomly repositioned upon
 283      * contention with other submitters.  In essence, submitters act
 284      * like workers except that they are restricted to executing local
 285      * tasks that they submitted (or in the case of CountedCompleters,
 286      * others with the same root task).  Insertion of tasks in shared
 287      * mode requires a lock but we use only a simple spinlock (using
 288      * field qlock), because submitters encountering a busy queue move
 289      * on to try or create other queues -- they block only when
 290      * creating and registering new queues. Because it is used only as
 291      * a spinlock, unlocking requires only a "releasing" store (using
 292      * putOrderedInt).  The qlock is also used during termination
 293      * detection, in which case it is forced to a negative
 294      * non-lockable value.
 295      *
 296      * Management
 297      * ==========
 298      *
 299      * The main throughput advantages of work-stealing stem from
 300      * decentralized control -- workers mostly take tasks from
 301      * themselves or each other, at rates that can exceed a billion
 302      * per second.  The pool itself creates, activates (enables
 303      * scanning for and running tasks), deactivates, blocks, and
 304      * terminates threads, all with minimal central information.
 305      * There are only a few properties that we can globally track or
 306      * maintain, so we pack them into a small number of variables,
 307      * often maintaining atomicity without blocking or locking.
 308      * Nearly all essentially atomic control state is held in two
 309      * volatile variables that are by far most often read (not
 310      * written) as status and consistency checks. (Also, field
 311      * "config" holds unchanging configuration state.)
 312      *
 313      * Field "ctl" contains 64 bits holding information needed to
 314      * atomically decide to add, inactivate, enqueue (on an event
 315      * queue), dequeue, and/or re-activate workers.  To enable this
 316      * packing, we restrict maximum parallelism to (1<<15)-1 (which is
 317      * far in excess of normal operating range) to allow ids, counts,
 318      * and their negations (used for thresholding) to fit into 16bit
 319      * subfields.
 320      *
 321      * Field "runState" holds lifetime status, atomically and
 322      * monotonically setting STARTED, SHUTDOWN, STOP, and finally
 323      * TERMINATED bits.
 324      *
 325      * Field "auxState" is a ReentrantLock subclass that also
 326      * opportunistically holds some other bookkeeping fields accessed
 327      * only when locked.  It is mainly used to lock (infrequent)
 328      * updates to workQueues.  The auxState instance is itself lazily
 329      * constructed (see tryInitialize), requiring a double-check-style
 330      * bootstrapping use of field runState, and locking a private
 331      * static.
 332      *
 333      * Field "workQueues" holds references to WorkQueues.  It is
 334      * updated (only during worker creation and termination) under the
 335      * lock, but is otherwise concurrently readable, and accessed
 336      * directly. We also ensure that reads of the array reference
 337      * itself never become too stale (for example, re-reading before
 338      * each scan). To simplify index-based operations, the array size
 339      * is always a power of two, and all readers must tolerate null
 340      * slots. Worker queues are at odd indices. Shared (submission)
 341      * queues are at even indices, up to a maximum of 64 slots, to
 342      * limit growth even if array needs to expand to add more
 343      * workers. Grouping them together in this way simplifies and
 344      * speeds up task scanning.
 345      *
 346      * All worker thread creation is on-demand, triggered by task
 347      * submissions, replacement of terminated workers, and/or
 348      * compensation for blocked workers. However, all other support
 349      * code is set up to work with other policies.  To ensure that we
 350      * do not hold on to worker references that would prevent GC, all
 351      * accesses to workQueues are via indices into the workQueues
 352      * array (which is one source of some of the messy code
 353      * constructions here). In essence, the workQueues array serves as
 354      * a weak reference mechanism. Thus for example the stack top
 355      * subfield of ctl stores indices, not references.
 356      *
 357      * Queuing Idle Workers. Unlike HPC work-stealing frameworks, we
 358      * cannot let workers spin indefinitely scanning for tasks when
 359      * none can be found immediately, and we cannot start/resume
 360      * workers unless there appear to be tasks available.  On the
 361      * other hand, we must quickly prod them into action when new
 362      * tasks are submitted or generated. In many usages, ramp-up time
 363      * to activate workers is the main limiting factor in overall
 364      * performance, which is compounded at program start-up by JIT
 365      * compilation and allocation. So we streamline this as much as
 366      * possible.
 367      *
 368      * The "ctl" field atomically maintains active and total worker
 369      * counts as well as a queue to place waiting threads so they can
 370      * be located for signalling. Active counts also play the role of
 371      * quiescence indicators, so are decremented when workers believe
 372      * that there are no more tasks to execute. The "queue" is
 373      * actually a form of Treiber stack.  A stack is ideal for
 374      * activating threads in most-recently used order. This improves
 375      * performance and locality, outweighing the disadvantages of
 376      * being prone to contention and inability to release a worker
 377      * unless it is topmost on stack.  We block/unblock workers after
 378      * pushing on the idle worker stack (represented by the lower
 379      * 32bit subfield of ctl) when they cannot find work.  The top
 380      * stack state holds the value of the "scanState" field of the
 381      * worker: its index and status, plus a version counter that, in
 382      * addition to the count subfields (also serving as version
 383      * stamps) provide protection against Treiber stack ABA effects.
 384      *
 385      * Creating workers. To create a worker, we pre-increment total
 386      * count (serving as a reservation), and attempt to construct a
 387      * ForkJoinWorkerThread via its factory. Upon construction, the
 388      * new thread invokes registerWorker, where it constructs a
 389      * WorkQueue and is assigned an index in the workQueues array
 390      * (expanding the array if necessary). The thread is then started.
 391      * Upon any exception across these steps, or null return from
 392      * factory, deregisterWorker adjusts counts and records
 393      * accordingly.  If a null return, the pool continues running with
 394      * fewer than the target number workers. If exceptional, the
 395      * exception is propagated, generally to some external caller.
 396      * Worker index assignment avoids the bias in scanning that would
 397      * occur if entries were sequentially packed starting at the front
 398      * of the workQueues array. We treat the array as a simple
 399      * power-of-two hash table, expanding as needed. The seedIndex
 400      * increment ensures no collisions until a resize is needed or a
 401      * worker is deregistered and replaced, and thereafter keeps
 402      * probability of collision low. We cannot use
 403      * ThreadLocalRandom.getProbe() for similar purposes here because
 404      * the thread has not started yet, but do so for creating
 405      * submission queues for existing external threads (see
 406      * externalPush).
 407      *
 408      * WorkQueue field scanState is used by both workers and the pool
 409      * to manage and track whether a worker is UNSIGNALLED (possibly
 410      * blocked waiting for a signal).  When a worker is inactivated,
 411      * its scanState field is set, and is prevented from executing
 412      * tasks, even though it must scan once for them to avoid queuing
 413      * races. Note that scanState updates lag queue CAS releases so
 414      * usage requires care. When queued, the lower 16 bits of
 415      * scanState must hold its pool index. So we place the index there
 416      * upon initialization (see registerWorker) and otherwise keep it
 417      * there or restore it when necessary.
 418      *
 419      * The ctl field also serves as the basis for memory
 420      * synchronization surrounding activation. This uses a more
 421      * efficient version of a Dekker-like rule that task producers and
 422      * consumers sync with each other by both writing/CASing ctl (even
 423      * if to its current value).  This would be extremely costly. So
 424      * we relax it in several ways: (1) Producers only signal when
 425      * their queue is empty. Other workers propagate this signal (in
 426      * method scan) when they find tasks. (2) Workers only enqueue
 427      * after scanning (see below) and not finding any tasks.  (3)
 428      * Rather than CASing ctl to its current value in the common case
 429      * where no action is required, we reduce write contention by
 430      * equivalently prefacing signalWork when called by an external
 431      * task producer using a memory access with full-volatile
 432      * semantics or a "fullFence". (4) For internal task producers we
 433      * rely on the fact that even if no other workers awaken, the
 434      * producer itself will eventually see the task and execute it.
 435      *
 436      * Almost always, too many signals are issued. A task producer
 437      * cannot in general tell if some existing worker is in the midst
 438      * of finishing one task (or already scanning) and ready to take
 439      * another without being signalled. So the producer might instead
 440      * activate a different worker that does not find any work, and
 441      * then inactivates. This scarcely matters in steady-state
 442      * computations involving all workers, but can create contention
 443      * and bookkeeping bottlenecks during ramp-up, ramp-down, and small
 444      * computations involving only a few workers.
 445      *
 446      * Scanning. Method scan() performs top-level scanning for tasks.
 447      * Each scan traverses (and tries to poll from) each queue in
 448      * pseudorandom permutation order by randomly selecting an origin
 449      * index and a step value.  (The pseudorandom generator need not
 450      * have high-quality statistical properties in the long term, but
 451      * just within computations; We use 64bit and 32bit Marsaglia
 452      * XorShifts, which are cheap and suffice here.)  Scanning also
 453      * employs contention reduction: When scanning workers fail a CAS
 454      * polling for work, they soon restart with a different
 455      * pseudorandom scan order (thus likely retrying at different
 456      * intervals). This improves throughput when many threads are
 457      * trying to take tasks from few queues.  Scans do not otherwise
 458      * explicitly take into account core affinities, loads, cache
 459      * localities, etc, However, they do exploit temporal locality
 460      * (which usually approximates these) by preferring to re-poll (up
 461      * to POLL_LIMIT times) from the same queue after a successful
 462      * poll before trying others.  Restricted forms of scanning occur
 463      * in methods helpComplete and findNonEmptyStealQueue, and take
 464      * similar but simpler forms.
 465      *
 466      * Deactivation and waiting. Queuing encounters several intrinsic
 467      * races; most notably that an inactivating scanning worker can
 468      * miss seeing a task produced during a scan.  So when a worker
 469      * cannot find a task to steal, it inactivates and enqueues, and
 470      * then rescans to ensure that it didn't miss one, reactivating
 471      * upon seeing one with probability approximately proportional to
 472      * probability of a miss.  (In most cases, the worker will be
 473      * signalled before self-signalling, avoiding cascades of multiple
 474      * signals for the same task).
 475      *
 476      * Workers block (in method awaitWork) using park/unpark;
 477      * advertising the need for signallers to unpark by setting their
 478      * "parker" fields.
 479      *
 480      * Trimming workers. To release resources after periods of lack of
 481      * use, a worker starting to wait when the pool is quiescent will
 482      * time out and terminate (see awaitWork) if the pool has remained
 483      * quiescent for period given by IDLE_TIMEOUT_MS, increasing the
 484      * period as the number of threads decreases, eventually removing
 485      * all workers.
 486      *
 487      * Shutdown and Termination. A call to shutdownNow invokes
 488      * tryTerminate to atomically set a runState bit. The calling
 489      * thread, as well as every other worker thereafter terminating,
 490      * helps terminate others by setting their (qlock) status,
 491      * cancelling their unprocessed tasks, and waking them up, doing
 492      * so repeatedly until stable. Calls to non-abrupt shutdown()
 493      * preface this by checking whether termination should commence.
 494      * This relies primarily on the active count bits of "ctl"
 495      * maintaining consensus -- tryTerminate is called from awaitWork
 496      * whenever quiescent. However, external submitters do not take
 497      * part in this consensus.  So, tryTerminate sweeps through queues
 498      * (until stable) to ensure lack of in-flight submissions and
 499      * workers about to process them before triggering the "STOP"
 500      * phase of termination. (Note: there is an intrinsic conflict if
 501      * helpQuiescePool is called when shutdown is enabled. Both wait
 502      * for quiescence, but tryTerminate is biased to not trigger until
 503      * helpQuiescePool completes.)
 504      *
 505      * Joining Tasks
 506      * =============
 507      *
 508      * Any of several actions may be taken when one worker is waiting
 509      * to join a task stolen (or always held) by another.  Because we
 510      * are multiplexing many tasks on to a pool of workers, we can't
 511      * just let them block (as in Thread.join).  We also cannot just
 512      * reassign the joiner's run-time stack with another and replace
 513      * it later, which would be a form of "continuation", that even if
 514      * possible is not necessarily a good idea since we may need both
 515      * an unblocked task and its continuation to progress.  Instead we
 516      * combine two tactics:
 517      *
 518      *   Helping: Arranging for the joiner to execute some task that it
 519      *      would be running if the steal had not occurred.
 520      *
 521      *   Compensating: Unless there are already enough live threads,
 522      *      method tryCompensate() may create or re-activate a spare
 523      *      thread to compensate for blocked joiners until they unblock.
 524      *
 525      * A third form (implemented in tryRemoveAndExec) amounts to
 526      * helping a hypothetical compensator: If we can readily tell that
 527      * a possible action of a compensator is to steal and execute the
 528      * task being joined, the joining thread can do so directly,
 529      * without the need for a compensation thread (although at the
 530      * expense of larger run-time stacks, but the tradeoff is
 531      * typically worthwhile).
 532      *
 533      * The ManagedBlocker extension API can't use helping so relies
 534      * only on compensation in method awaitBlocker.
 535      *
 536      * The algorithm in helpStealer entails a form of "linear
 537      * helping".  Each worker records (in field currentSteal) the most
 538      * recent task it stole from some other worker (or a submission).
 539      * It also records (in field currentJoin) the task it is currently
 540      * actively joining. Method helpStealer uses these markers to try
 541      * to find a worker to help (i.e., steal back a task from and
 542      * execute it) that could hasten completion of the actively joined
 543      * task.  Thus, the joiner executes a task that would be on its
 544      * own local deque had the to-be-joined task not been stolen. This
 545      * is a conservative variant of the approach described in Wagner &
 546      * Calder "Leapfrogging: a portable technique for implementing
 547      * efficient futures" SIGPLAN Notices, 1993
 548      * (http://portal.acm.org/citation.cfm?id=155354). It differs in
 549      * that: (1) We only maintain dependency links across workers upon
 550      * steals, rather than use per-task bookkeeping.  This sometimes
 551      * requires a linear scan of workQueues array to locate stealers,
 552      * but often doesn't because stealers leave hints (that may become
 553      * stale/wrong) of where to locate them.  It is only a hint
 554      * because a worker might have had multiple steals and the hint
 555      * records only one of them (usually the most current).  Hinting
 556      * isolates cost to when it is needed, rather than adding to
 557      * per-task overhead.  (2) It is "shallow", ignoring nesting and
 558      * potentially cyclic mutual steals.  (3) It is intentionally
 559      * racy: field currentJoin is updated only while actively joining,
 560      * which means that we miss links in the chain during long-lived
 561      * tasks, GC stalls etc (which is OK since blocking in such cases
 562      * is usually a good idea).  (4) We bound the number of attempts
 563      * to find work using checksums and fall back to suspending the
 564      * worker and if necessary replacing it with another.
 565      *
 566      * Helping actions for CountedCompleters do not require tracking
 567      * currentJoins: Method helpComplete takes and executes any task
 568      * with the same root as the task being waited on (preferring
 569      * local pops to non-local polls). However, this still entails
 570      * some traversal of completer chains, so is less efficient than
 571      * using CountedCompleters without explicit joins.
 572      *
 573      * Compensation does not aim to keep exactly the target
 574      * parallelism number of unblocked threads running at any given
 575      * time. Some previous versions of this class employed immediate
 576      * compensations for any blocked join. However, in practice, the
 577      * vast majority of blockages are transient byproducts of GC and
 578      * other JVM or OS activities that are made worse by replacement.
 579      * Currently, compensation is attempted only after validating that
 580      * all purportedly active threads are processing tasks by checking
 581      * field WorkQueue.scanState, which eliminates most false
 582      * positives.  Also, compensation is bypassed (tolerating fewer
 583      * threads) in the most common case in which it is rarely
 584      * beneficial: when a worker with an empty queue (thus no
 585      * continuation tasks) blocks on a join and there still remain
 586      * enough threads to ensure liveness.
 587      *
 588      * Spare threads are removed as soon as they notice that the
 589      * target parallelism level has been exceeded, in method
 590      * tryDropSpare. (Method scan arranges returns for rechecks upon
 591      * each probe via the "bound" parameter.)
 592      *
 593      * The compensation mechanism may be bounded.  Bounds for the
 594      * commonPool (see COMMON_MAX_SPARES) better enable JVMs to cope
 595      * with programming errors and abuse before running out of
 596      * resources to do so. In other cases, users may supply factories
 597      * that limit thread construction. The effects of bounding in this
 598      * pool (like all others) is imprecise.  Total worker counts are
 599      * decremented when threads deregister, not when they exit and
 600      * resources are reclaimed by the JVM and OS. So the number of
 601      * simultaneously live threads may transiently exceed bounds.
 602      *
 603      * Common Pool
 604      * ===========
 605      *
 606      * The static common pool always exists after static
 607      * initialization.  Since it (or any other created pool) need
 608      * never be used, we minimize initial construction overhead and
 609      * footprint to the setup of about a dozen fields, with no nested
 610      * allocation. Most bootstrapping occurs within method
 611      * externalSubmit during the first submission to the pool.
 612      *
 613      * When external threads submit to the common pool, they can
 614      * perform subtask processing (see externalHelpComplete and
 615      * related methods) upon joins.  This caller-helps policy makes it
 616      * sensible to set common pool parallelism level to one (or more)
 617      * less than the total number of available cores, or even zero for
 618      * pure caller-runs.  We do not need to record whether external
 619      * submissions are to the common pool -- if not, external help
 620      * methods return quickly. These submitters would otherwise be
 621      * blocked waiting for completion, so the extra effort (with
 622      * liberally sprinkled task status checks) in inapplicable cases
 623      * amounts to an odd form of limited spin-wait before blocking in
 624      * ForkJoinTask.join.
 625      *
 626      * As a more appropriate default in managed environments, unless
 627      * overridden by system properties, we use workers of subclass
 628      * InnocuousForkJoinWorkerThread when there is a SecurityManager
 629      * present. These workers have no permissions set, do not belong
 630      * to any user-defined ThreadGroup, and erase all ThreadLocals
 631      * after executing any top-level task (see WorkQueue.runTask).
 632      * The associated mechanics (mainly in ForkJoinWorkerThread) may
 633      * be JVM-dependent and must access particular Thread class fields
 634      * to achieve this effect.
 635      *
 636      * Style notes
 637      * ===========
 638      *
 639      * Memory ordering relies mainly on Unsafe intrinsics that carry
 640      * the further responsibility of explicitly performing null- and
 641      * bounds- checks otherwise carried out implicitly by JVMs.  This
 642      * can be awkward and ugly, but also reflects the need to control
 643      * outcomes across the unusual cases that arise in very racy code
 644      * with very few invariants. So these explicit checks would exist
 645      * in some form anyway.  All fields are read into locals before
 646      * use, and null-checked if they are references.  This is usually
 647      * done in a "C"-like style of listing declarations at the heads
 648      * of methods or blocks, and using inline assignments on first
 649      * encounter.  Array bounds-checks are usually performed by
 650      * masking with array.length-1, which relies on the invariant that
 651      * these arrays are created with positive lengths, which is itself
 652      * paranoically checked. Nearly all explicit checks lead to
 653      * bypass/return, not exception throws, because they may
 654      * legitimately arise due to cancellation/revocation during
 655      * shutdown.
 656      *
 657      * There is a lot of representation-level coupling among classes
 658      * ForkJoinPool, ForkJoinWorkerThread, and ForkJoinTask.  The
 659      * fields of WorkQueue maintain data structures managed by
 660      * ForkJoinPool, so are directly accessed.  There is little point
 661      * trying to reduce this, since any associated future changes in
 662      * representations will need to be accompanied by algorithmic
 663      * changes anyway. Several methods intrinsically sprawl because
 664      * they must accumulate sets of consistent reads of fields held in
 665      * local variables.  There are also other coding oddities
 666      * (including several unnecessary-looking hoisted null checks)
 667      * that help some methods perform reasonably even when interpreted
 668      * (not compiled).
 669      *
 670      * The order of declarations in this file is (with a few exceptions):
 671      * (1) Static utility functions
 672      * (2) Nested (static) classes
 673      * (3) Static fields
 674      * (4) Fields, along with constants used when unpacking some of them
 675      * (5) Internal control methods
 676      * (6) Callbacks and other support for ForkJoinTask methods
 677      * (7) Exported methods
 678      * (8) Static block initializing statics in minimally dependent order
 679      */
 680 
 681     // Static utilities
 682 
 683     /**
 684      * If there is a security manager, makes sure caller has
 685      * permission to modify threads.
 686      */
 687     private static void checkPermission() {
 688         SecurityManager security = System.getSecurityManager();
 689         if (security != null)
 690             security.checkPermission(modifyThreadPermission);
 691     }
 692 
 693     // Nested classes
 694 
 695     /**
 696      * Factory for creating new {@link ForkJoinWorkerThread}s.
 697      * A {@code ForkJoinWorkerThreadFactory} must be defined and used
 698      * for {@code ForkJoinWorkerThread} subclasses that extend base
 699      * functionality or initialize threads with different contexts.
 700      */
 701     public static interface ForkJoinWorkerThreadFactory {
 702         /**
 703          * Returns a new worker thread operating in the given pool.
 704          *
 705          * @param pool the pool this thread works in
 706          * @return the new worker thread
 707          * @throws NullPointerException if the pool is null
 708          */
 709         public ForkJoinWorkerThread newThread(ForkJoinPool pool);
 710     }
 711 
 712     /**
 713      * Default ForkJoinWorkerThreadFactory implementation; creates a
 714      * new ForkJoinWorkerThread.
 715      */
 716     private static final class DefaultForkJoinWorkerThreadFactory
 717         implements ForkJoinWorkerThreadFactory {
 718         public final ForkJoinWorkerThread newThread(ForkJoinPool pool) {
 719             return new ForkJoinWorkerThread(pool);
 720         }
 721     }
 722 
 723     /**
 724      * Class for artificial tasks that are used to replace the target
 725      * of local joins if they are removed from an interior queue slot
 726      * in WorkQueue.tryRemoveAndExec. We don't need the proxy to
 727      * actually do anything beyond having a unique identity.
 728      */
 729     private static final class EmptyTask extends ForkJoinTask<Void> {
 730         private static final long serialVersionUID = -7721805057305804111L;
 731         EmptyTask() { status = ForkJoinTask.NORMAL; } // force done
 732         public final Void getRawResult() { return null; }
 733         public final void setRawResult(Void x) {}
 734         public final boolean exec() { return true; }
 735     }
 736 
 737     /**
 738      * Additional fields and lock created upon initialization.
 739      */
 740     private static final class AuxState extends ReentrantLock {
 741         private static final long serialVersionUID = -6001602636862214147L;
 742         volatile long stealCount;     // cumulative steal count
 743         long indexSeed;               // index bits for registerWorker
 744         AuxState() {}
 745     }
 746 
 747     // Constants shared across ForkJoinPool and WorkQueue
 748 
 749     // Bounds
 750     static final int SMASK        = 0xffff;        // short bits == max index
 751     static final int MAX_CAP      = 0x7fff;        // max #workers - 1
 752     static final int EVENMASK     = 0xfffe;        // even short bits
 753     static final int SQMASK       = 0x007e;        // max 64 (even) slots
 754 
 755     // Masks and units for WorkQueue.scanState and ctl sp subfield
 756     static final int UNSIGNALLED  = 1 << 31;       // must be negative
 757     static final int SS_SEQ       = 1 << 16;       // version count
 758 
 759     // Mode bits for ForkJoinPool.config and WorkQueue.config
 760     static final int MODE_MASK    = 0xffff << 16;  // top half of int
 761     static final int SPARE_WORKER = 1 << 17;       // set if tc > 0 on creation
 762     static final int UNREGISTERED = 1 << 18;       // to skip some of deregister
 763     static final int FIFO_QUEUE   = 1 << 31;       // must be negative
 764     static final int LIFO_QUEUE   = 0;             // for clarity
 765     static final int IS_OWNED     = 1;             // low bit 0 if shared
 766 
 767     /**
 768      * The maximum number of task executions from the same queue
 769      * before checking other queues, bounding unfairness and impact of
 770      * infinite user task recursion.  Must be a power of two minus 1.
 771      */
 772     static final int POLL_LIMIT = (1 << 10) - 1;
 773 
 774     /**
 775      * Queues supporting work-stealing as well as external task
 776      * submission. See above for descriptions and algorithms.
 777      * Performance on most platforms is very sensitive to placement of
 778      * instances of both WorkQueues and their arrays -- we absolutely
 779      * do not want multiple WorkQueue instances or multiple queue
 780      * arrays sharing cache lines. The @Contended annotation alerts
 781      * JVMs to try to keep instances apart.
 782      */
 783     @sun.misc.Contended
 784     static final class WorkQueue {
 785 
 786         /**
 787          * Capacity of work-stealing queue array upon initialization.
 788          * Must be a power of two; at least 4, but should be larger to
 789          * reduce or eliminate cacheline sharing among queues.
 790          * Currently, it is much larger, as a partial workaround for
 791          * the fact that JVMs often place arrays in locations that
 792          * share GC bookkeeping (especially cardmarks) such that
 793          * per-write accesses encounter serious memory contention.
 794          */
 795         static final int INITIAL_QUEUE_CAPACITY = 1 << 13;
 796 
 797         /**
 798          * Maximum size for queue arrays. Must be a power of two less
 799          * than or equal to 1 << (31 - width of array entry) to ensure
 800          * lack of wraparound of index calculations, but defined to a
 801          * value a bit less than this to help users trap runaway
 802          * programs before saturating systems.
 803          */
 804         static final int MAXIMUM_QUEUE_CAPACITY = 1 << 26; // 64M
 805 
 806         // Instance fields
 807 
 808         volatile int scanState;    // versioned, negative if inactive
 809         int stackPred;             // pool stack (ctl) predecessor
 810         int nsteals;               // number of steals
 811         int hint;                  // randomization and stealer index hint
 812         int config;                // pool index and mode
 813         volatile int qlock;        // 1: locked, < 0: terminate; else 0
 814         volatile int base;         // index of next slot for poll
 815         int top;                   // index of next slot for push
 816         ForkJoinTask<?>[] array;   // the elements (initially unallocated)
 817         final ForkJoinPool pool;   // the containing pool (may be null)
 818         final ForkJoinWorkerThread owner; // owning thread or null if shared
 819         volatile Thread parker;    // == owner during call to park; else null
 820         volatile ForkJoinTask<?> currentJoin;  // task being joined in awaitJoin
 821         @sun.misc.Contended("group2") // separate from other fields
 822         volatile ForkJoinTask<?> currentSteal; // nonnull when running some task
 823 
 824         WorkQueue(ForkJoinPool pool, ForkJoinWorkerThread owner) {
 825             this.pool = pool;
 826             this.owner = owner;
 827             // Place indices in the center of array (that is not yet allocated)
 828             base = top = INITIAL_QUEUE_CAPACITY >>> 1;
 829         }
 830 
 831         /**
 832          * Returns an exportable index (used by ForkJoinWorkerThread).
 833          */
 834         final int getPoolIndex() {
 835             return (config & 0xffff) >>> 1; // ignore odd/even tag bit
 836         }
 837 
 838         /**
 839          * Returns the approximate number of tasks in the queue.
 840          */
 841         final int queueSize() {
 842             int n = base - top;       // read base first
 843             return (n >= 0) ? 0 : -n; // ignore transient negative
 844         }
 845 
 846         /**
 847          * Provides a more accurate estimate of whether this queue has
 848          * any tasks than does queueSize, by checking whether a
 849          * near-empty queue has at least one unclaimed task.
 850          */
 851         final boolean isEmpty() {
 852             ForkJoinTask<?>[] a; int n, al, s;
 853             return ((n = base - (s = top)) >= 0 || // possibly one task
 854                     (n == -1 && ((a = array) == null ||
 855                                  (al = a.length) == 0 ||
 856                                  a[(al - 1) & (s - 1)] == null)));
 857         }
 858 
 859         /**
 860          * Pushes a task. Call only by owner in unshared queues.
 861          *
 862          * @param task the task. Caller must ensure non-null.
 863          * @throws RejectedExecutionException if array cannot be resized
 864          */
 865         final void push(ForkJoinTask<?> task) {
 866             U.storeFence();              // ensure safe publication
 867             int s = top, al, d; ForkJoinTask<?>[] a;
 868             if ((a = array) != null && (al = a.length) > 0) {
 869                 a[(al - 1) & s] = task;  // relaxed writes OK
 870                 top = s + 1;
 871                 ForkJoinPool p = pool;
 872                 if ((d = base - s) == 0 && p != null) {
 873                     U.fullFence();
 874                     p.signalWork();
 875                 }
 876                 else if (al + d == 1)
 877                     growArray();
 878             }
 879         }
 880 
 881         /**
 882          * Initializes or doubles the capacity of array. Call either
 883          * by owner or with lock held -- it is OK for base, but not
 884          * top, to move while resizings are in progress.
 885          */
 886         final ForkJoinTask<?>[] growArray() {
 887             ForkJoinTask<?>[] oldA = array;
 888             int size = oldA != null ? oldA.length << 1 : INITIAL_QUEUE_CAPACITY;
 889             if (size < INITIAL_QUEUE_CAPACITY || size > MAXIMUM_QUEUE_CAPACITY)
 890                 throw new RejectedExecutionException("Queue capacity exceeded");
 891             int oldMask, t, b;
 892             ForkJoinTask<?>[] a = array = new ForkJoinTask<?>[size];
 893             if (oldA != null && (oldMask = oldA.length - 1) > 0 &&
 894                 (t = top) - (b = base) > 0) {
 895                 int mask = size - 1;
 896                 do { // emulate poll from old array, push to new array
 897                     int index = b & oldMask;
 898                     long offset = ((long)index << ASHIFT) + ABASE;
 899                     ForkJoinTask<?> x = (ForkJoinTask<?>)
 900                         U.getObjectVolatile(oldA, offset);
 901                     if (x != null &&
 902                         U.compareAndSwapObject(oldA, offset, x, null))
 903                         a[b & mask] = x;
 904                 } while (++b != t);
 905                 U.storeFence();
 906             }
 907             return a;
 908         }
 909 
 910         /**
 911          * Takes next task, if one exists, in LIFO order.  Call only
 912          * by owner in unshared queues.
 913          */
 914         final ForkJoinTask<?> pop() {
 915             int b = base, s = top, al, i; ForkJoinTask<?>[] a;
 916             if ((a = array) != null && b != s && (al = a.length) > 0) {
 917                 int index = (al - 1) & --s;
 918                 long offset = ((long)index << ASHIFT) + ABASE;
 919                 ForkJoinTask<?> t = (ForkJoinTask<?>)
 920                     U.getObject(a, offset);
 921                 if (t != null &&
 922                     U.compareAndSwapObject(a, offset, t, null)) {
 923                     top = s;
 924                     return t;
 925                 }
 926             }
 927             return null;
 928         }
 929 
 930         /**
 931          * Takes a task in FIFO order if b is base of queue and a task
 932          * can be claimed without contention. Specialized versions
 933          * appear in ForkJoinPool methods scan and helpStealer.
 934          */
 935         final ForkJoinTask<?> pollAt(int b) {
 936             ForkJoinTask<?>[] a; int al;
 937             if ((a = array) != null && (al = a.length) > 0) {
 938                 int index = (al - 1) & b;
 939                 long offset = ((long)index << ASHIFT) + ABASE;
 940                 ForkJoinTask<?> t = (ForkJoinTask<?>)
 941                     U.getObjectVolatile(a, offset);
 942                 if (t != null && b++ == base &&
 943                     U.compareAndSwapObject(a, offset, t, null)) {
 944                     base = b;
 945                     return t;
 946                 }
 947             }
 948             return null;
 949         }
 950 
 951         /**
 952          * Takes next task, if one exists, in FIFO order.
 953          */
 954         final ForkJoinTask<?> poll() {
 955             for (;;) {
 956                 int b = base, s = top, d, al; ForkJoinTask<?>[] a;
 957                 if ((a = array) != null && (d = b - s) < 0 &&
 958                     (al = a.length) > 0) {
 959                     int index = (al - 1) & b;
 960                     long offset = ((long)index << ASHIFT) + ABASE;
 961                     ForkJoinTask<?> t = (ForkJoinTask<?>)
 962                         U.getObjectVolatile(a, offset);
 963                     if (b++ == base) {
 964                         if (t != null) {
 965                             if (U.compareAndSwapObject(a, offset, t, null)) {
 966                                 base = b;
 967                                 return t;
 968                             }
 969                         }
 970                         else if (d == -1)
 971                             break; // now empty
 972                     }
 973                 }
 974                 else
 975                     break;
 976             }
 977             return null;
 978         }
 979 
 980         /**
 981          * Takes next task, if one exists, in order specified by mode.
 982          */
 983         final ForkJoinTask<?> nextLocalTask() {
 984             return (config < 0) ? poll() : pop();
 985         }
 986 
 987         /**
 988          * Returns next task, if one exists, in order specified by mode.
 989          */
 990         final ForkJoinTask<?> peek() {
 991             int al; ForkJoinTask<?>[] a;
 992             return ((a = array) != null && (al = a.length) > 0) ?
 993                 a[(al - 1) & (config < 0 ? base : top - 1)] : null;
 994         }
 995 
 996         /**
 997          * Pops the given task only if it is at the current top.
 998          */
 999         final boolean tryUnpush(ForkJoinTask<?> task) {
1000             int b = base, s = top, al; ForkJoinTask<?>[] a;
1001             if ((a = array) != null && b != s && (al = a.length) > 0) {
1002                 int index = (al - 1) & --s;
1003                 long offset = ((long)index << ASHIFT) + ABASE;
1004                 if (U.compareAndSwapObject(a, offset, task, null)) {
1005                     top = s;
1006                     return true;
1007                 }
1008             }
1009             return false;
1010         }
1011 
1012         /**
1013          * Shared version of push. Fails if already locked.
1014          *
1015          * @return status: > 0 locked, 0 possibly was empty, < 0 was nonempty
1016          */
1017         final int sharedPush(ForkJoinTask<?> task) {
1018             int stat;
1019             if (U.compareAndSwapInt(this, QLOCK, 0, 1)) {
1020                 int b = base, s = top, al, d; ForkJoinTask<?>[] a;
1021                 if ((a = array) != null && (al = a.length) > 0 &&
1022                     al - 1 + (d = b - s) > 0) {
1023                     a[(al - 1) & s] = task;
1024                     top = s + 1;                 // relaxed writes OK here
1025                     qlock = 0;
1026                     stat = (d < 0 && b == base) ? d : 0;
1027                 }
1028                 else {
1029                     growAndSharedPush(task);
1030                     stat = 0;
1031                 }
1032             }
1033             else
1034                 stat = 1;
1035             return stat;
1036         }
1037 
1038         /**
1039          * Helper for sharedPush; called only when locked and resize
1040          * needed.
1041          */
1042         private void growAndSharedPush(ForkJoinTask<?> task) {
1043             try {
1044                 growArray();
1045                 int s = top, al; ForkJoinTask<?>[] a;
1046                 if ((a = array) != null && (al = a.length) > 0) {
1047                     a[(al - 1) & s] = task;
1048                     top = s + 1;
1049                 }
1050             } finally {
1051                 qlock = 0;
1052             }
1053         }
1054 
1055         /**
1056          * Shared version of pop.
1057          */
1058         final boolean trySharedUnpush(ForkJoinTask<?> task) {
1059             boolean popped = false;
1060             int s = top - 1, al; ForkJoinTask<?>[] a;
1061             if ((a = array) != null && (al = a.length) > 0) {
1062                 int index = (al - 1) & s;
1063                 long offset = ((long)index << ASHIFT) + ABASE;
1064                 ForkJoinTask<?> t = (ForkJoinTask<?>) U.getObject(a, offset);
1065                 if (t == task &&
1066                     U.compareAndSwapInt(this, QLOCK, 0, 1)) {
1067                     if (U.compareAndSwapObject(a, offset, task, null)) {
1068                         popped = true;
1069                         top = s;
1070                     }
1071                     U.putOrderedInt(this, QLOCK, 0);
1072                 }
1073             }
1074             return popped;
1075         }
1076 
1077         /**
1078          * Removes and cancels all known tasks, ignoring any exceptions.
1079          */
1080         final void cancelAll() {
1081             ForkJoinTask<?> t;
1082             if ((t = currentJoin) != null) {
1083                 currentJoin = null;
1084                 ForkJoinTask.cancelIgnoringExceptions(t);
1085             }
1086             if ((t = currentSteal) != null) {
1087                 currentSteal = null;
1088                 ForkJoinTask.cancelIgnoringExceptions(t);
1089             }
1090             while ((t = poll()) != null)
1091                 ForkJoinTask.cancelIgnoringExceptions(t);
1092         }
1093 
1094         // Specialized execution methods
1095 
1096         /**
1097          * Pops and executes up to POLL_LIMIT tasks or until empty.
1098          */
1099         final void localPopAndExec() {
1100             for (int nexec = 0;;) {
1101                 int b = base, s = top, al; ForkJoinTask<?>[] a;
1102                 if ((a = array) != null && b != s && (al = a.length) > 0) {
1103                     int index = (al - 1) & --s;
1104                     long offset = ((long)index << ASHIFT) + ABASE;
1105                     ForkJoinTask<?> t = (ForkJoinTask<?>)
1106                         U.getAndSetObject(a, offset, null);
1107                     if (t != null) {
1108                         top = s;
1109                         (currentSteal = t).doExec();
1110                         if (++nexec > POLL_LIMIT)
1111                             break;
1112                     }
1113                     else
1114                         break;
1115                 }
1116                 else
1117                     break;
1118             }
1119         }
1120 
1121         /**
1122          * Polls and executes up to POLL_LIMIT tasks or until empty.
1123          */
1124         final void localPollAndExec() {
1125             for (int nexec = 0;;) {
1126                 int b = base, s = top, al; ForkJoinTask<?>[] a;
1127                 if ((a = array) != null && b != s && (al = a.length) > 0) {
1128                     int index = (al - 1) & b++;
1129                     long offset = ((long)index << ASHIFT) + ABASE;
1130                     ForkJoinTask<?> t = (ForkJoinTask<?>)
1131                         U.getAndSetObject(a, offset, null);
1132                     if (t != null) {
1133                         base = b;
1134                         t.doExec();
1135                         if (++nexec > POLL_LIMIT)
1136                             break;
1137                     }
1138                 }
1139                 else
1140                     break;
1141             }
1142         }
1143 
1144         /**
1145          * Executes the given task and (some) remaining local tasks.
1146          */
1147         final void runTask(ForkJoinTask<?> task) {
1148             if (task != null) {
1149                 task.doExec();
1150                 if (config < 0)
1151                     localPollAndExec();
1152                 else
1153                     localPopAndExec();
1154                 int ns = ++nsteals;
1155                 ForkJoinWorkerThread thread = owner;
1156                 currentSteal = null;
1157                 if (ns < 0)           // collect on overflow
1158                     transferStealCount(pool);
1159                 if (thread != null)
1160                     thread.afterTopLevelExec();
1161             }
1162         }
1163 
1164         /**
1165          * Adds steal count to pool steal count if it exists, and resets.
1166          */
1167         final void transferStealCount(ForkJoinPool p) {
1168             AuxState aux;
1169             if (p != null && (aux = p.auxState) != null) {
1170                 long s = nsteals;
1171                 nsteals = 0;            // if negative, correct for overflow
1172                 if (s < 0) s = Integer.MAX_VALUE;
1173                 aux.lock();
1174                 try {
1175                     aux.stealCount += s;
1176                 } finally {
1177                     aux.unlock();
1178                 }
1179             }
1180         }
1181 
1182         /**
1183          * If present, removes from queue and executes the given task,
1184          * or any other cancelled task. Used only by awaitJoin.
1185          *
1186          * @return true if queue empty and task not known to be done
1187          */
1188         final boolean tryRemoveAndExec(ForkJoinTask<?> task) {
1189             if (task != null && task.status >= 0) {
1190                 int b, s, d, al; ForkJoinTask<?>[] a;
1191                 while ((d = (b = base) - (s = top)) < 0 &&
1192                        (a = array) != null && (al = a.length) > 0) {
1193                     for (;;) {      // traverse from s to b
1194                         int index = --s & (al - 1);
1195                         long offset = (index << ASHIFT) + ABASE;
1196                         ForkJoinTask<?> t = (ForkJoinTask<?>)
1197                             U.getObjectVolatile(a, offset);
1198                         if (t == null)
1199                             break;                   // restart
1200                         else if (t == task) {
1201                             boolean removed = false;
1202                             if (s + 1 == top) {      // pop
1203                                 if (U.compareAndSwapObject(a, offset, t, null)) {
1204                                     top = s;
1205                                     removed = true;
1206                                 }
1207                             }
1208                             else if (base == b)      // replace with proxy
1209                                 removed = U.compareAndSwapObject(a, offset, t,
1210                                                                  new EmptyTask());
1211                             if (removed) {
1212                                 ForkJoinTask<?> ps = currentSteal;
1213                                 (currentSteal = task).doExec();
1214                                 currentSteal = ps;
1215                             }
1216                             break;
1217                         }
1218                         else if (t.status < 0 && s + 1 == top) {
1219                             if (U.compareAndSwapObject(a, offset, t, null)) {
1220                                 top = s;
1221                             }
1222                             break;                  // was cancelled
1223                         }
1224                         else if (++d == 0) {
1225                             if (base != b)          // rescan
1226                                 break;
1227                             return false;
1228                         }
1229                     }
1230                     if (task.status < 0)
1231                         return false;
1232                 }
1233             }
1234             return true;
1235         }
1236 
1237         /**
1238          * Pops task if in the same CC computation as the given task,
1239          * in either shared or owned mode. Used only by helpComplete.
1240          */
1241         final CountedCompleter<?> popCC(CountedCompleter<?> task, int mode) {
1242             int b = base, s = top, al; ForkJoinTask<?>[] a;
1243             if ((a = array) != null && b != s && (al = a.length) > 0) {
1244                 int index = (al - 1) & (s - 1);
1245                 long offset = ((long)index << ASHIFT) + ABASE;
1246                 ForkJoinTask<?> o = (ForkJoinTask<?>)
1247                     U.getObjectVolatile(a, offset);
1248                 if (o instanceof CountedCompleter) {
1249                     CountedCompleter<?> t = (CountedCompleter<?>)o;
1250                     for (CountedCompleter<?> r = t;;) {
1251                         if (r == task) {
1252                             if ((mode & IS_OWNED) == 0) {
1253                                 boolean popped;
1254                                 if (U.compareAndSwapInt(this, QLOCK, 0, 1)) {
1255                                     if (popped =
1256                                         U.compareAndSwapObject(a, offset,
1257                                                                t, null))
1258                                         top = s - 1;
1259                                     U.putOrderedInt(this, QLOCK, 0);
1260                                     if (popped)
1261                                         return t;
1262                                 }
1263                             }
1264                             else if (U.compareAndSwapObject(a, offset,
1265                                                             t, null)) {
1266                                 top = s - 1;
1267                                 return t;
1268                             }
1269                             break;
1270                         }
1271                         else if ((r = r.completer) == null) // try parent
1272                             break;
1273                     }
1274                 }
1275             }
1276             return null;
1277         }
1278 
1279         /**
1280          * Steals and runs a task in the same CC computation as the
1281          * given task if one exists and can be taken without
1282          * contention. Otherwise returns a checksum/control value for
1283          * use by method helpComplete.
1284          *
1285          * @return 1 if successful, 2 if retryable (lost to another
1286          * stealer), -1 if non-empty but no matching task found, else
1287          * the base index, forced negative.
1288          */
1289         final int pollAndExecCC(CountedCompleter<?> task) {
1290             ForkJoinTask<?>[] a;
1291             int b = base, s = top, al, h;
1292             if ((a = array) != null && b != s && (al = a.length) > 0) {
1293                 int index = (al - 1) & b;
1294                 long offset = ((long)index << ASHIFT) + ABASE;
1295                 ForkJoinTask<?> o = (ForkJoinTask<?>)
1296                     U.getObjectVolatile(a, offset);
1297                 if (o == null)
1298                     h = 2;                      // retryable
1299                 else if (!(o instanceof CountedCompleter))
1300                     h = -1;                     // unmatchable
1301                 else {
1302                     CountedCompleter<?> t = (CountedCompleter<?>)o;
1303                     for (CountedCompleter<?> r = t;;) {
1304                         if (r == task) {
1305                             if (b++ == base &&
1306                                 U.compareAndSwapObject(a, offset, t, null)) {
1307                                 base = b;
1308                                 t.doExec();
1309                                 h = 1;          // success
1310                             }
1311                             else
1312                                 h = 2;          // lost CAS
1313                             break;
1314                         }
1315                         else if ((r = r.completer) == null) {
1316                             h = -1;             // unmatched
1317                             break;
1318                         }
1319                     }
1320                 }
1321             }
1322             else
1323                 h = b | Integer.MIN_VALUE;      // to sense movement on re-poll
1324             return h;
1325         }
1326 
1327         /**
1328          * Returns true if owned and not known to be blocked.
1329          */
1330         final boolean isApparentlyUnblocked() {
1331             Thread wt; Thread.State s;
1332             return (scanState >= 0 &&
1333                     (wt = owner) != null &&
1334                     (s = wt.getState()) != Thread.State.BLOCKED &&
1335                     s != Thread.State.WAITING &&
1336                     s != Thread.State.TIMED_WAITING);
1337         }
1338 
1339         // Unsafe mechanics. Note that some are (and must be) the same as in FJP
1340         private static final sun.misc.Unsafe U = sun.misc.Unsafe.getUnsafe();
1341         private static final long QLOCK;
1342         private static final int ABASE;
1343         private static final int ASHIFT;
1344         static {
1345             try {
1346                 QLOCK = U.objectFieldOffset
1347                     (WorkQueue.class.getDeclaredField("qlock"));
1348                 ABASE = U.arrayBaseOffset(ForkJoinTask[].class);
1349                 int scale = U.arrayIndexScale(ForkJoinTask[].class);
1350                 if ((scale & (scale - 1)) != 0)
1351                     throw new Error("array index scale not a power of two");
1352                 ASHIFT = 31 - Integer.numberOfLeadingZeros(scale);
1353             } catch (ReflectiveOperationException e) {
1354                 throw new Error(e);
1355             }
1356         }
1357     }
1358 
1359     // static fields (initialized in static initializer below)
1360 
1361     /**
1362      * Creates a new ForkJoinWorkerThread. This factory is used unless
1363      * overridden in ForkJoinPool constructors.
1364      */
1365     public static final ForkJoinWorkerThreadFactory
1366         defaultForkJoinWorkerThreadFactory;
1367 
1368     /**
1369      * Permission required for callers of methods that may start or
1370      * kill threads.  Also used as a static lock in tryInitialize.
1371      */
1372     static final RuntimePermission modifyThreadPermission;
1373 
1374     /**
1375      * Common (static) pool. Non-null for public use unless a static
1376      * construction exception, but internal usages null-check on use
1377      * to paranoically avoid potential initialization circularities
1378      * as well as to simplify generated code.
1379      */
1380     static final ForkJoinPool common;
1381 
1382     /**
1383      * Common pool parallelism. To allow simpler use and management
1384      * when common pool threads are disabled, we allow the underlying
1385      * common.parallelism field to be zero, but in that case still report
1386      * parallelism as 1 to reflect resulting caller-runs mechanics.
1387      */
1388     static final int COMMON_PARALLELISM;
1389 
1390     /**
1391      * Limit on spare thread construction in tryCompensate.
1392      */
1393     private static final int COMMON_MAX_SPARES;
1394 
1395     /**
1396      * Sequence number for creating workerNamePrefix.
1397      */
1398     private static int poolNumberSequence;
1399 
1400     /**
1401      * Returns the next sequence number. We don't expect this to
1402      * ever contend, so use simple builtin sync.
1403      */
1404     private static final synchronized int nextPoolId() {
1405         return ++poolNumberSequence;
1406     }
1407 
1408     // static configuration constants
1409 
1410     /**
1411      * Initial timeout value (in milliseconds) for the thread
1412      * triggering quiescence to park waiting for new work. On timeout,
1413      * the thread will instead try to shrink the number of workers.
1414      * The value should be large enough to avoid overly aggressive
1415      * shrinkage during most transient stalls (long GCs etc).
1416      */
1417     private static final long IDLE_TIMEOUT_MS = 2000L; // 2sec
1418 
1419     /**
1420      * Tolerance for idle timeouts, to cope with timer undershoots.
1421      */
1422     private static final long TIMEOUT_SLOP_MS =   20L; // 20ms
1423 
1424     /**
1425      * The default value for COMMON_MAX_SPARES.  Overridable using the
1426      * "java.util.concurrent.ForkJoinPool.common.maximumSpares" system
1427      * property.  The default value is far in excess of normal
1428      * requirements, but also far short of MAX_CAP and typical OS
1429      * thread limits, so allows JVMs to catch misuse/abuse before
1430      * running out of resources needed to do so.
1431      */
1432     private static final int DEFAULT_COMMON_MAX_SPARES = 256;
1433 
1434     /**
1435      * Increment for seed generators. See class ThreadLocal for
1436      * explanation.
1437      */
1438     private static final int SEED_INCREMENT = 0x9e3779b9;
1439 
1440     /*
1441      * Bits and masks for field ctl, packed with 4 16 bit subfields:
1442      * AC: Number of active running workers minus target parallelism
1443      * TC: Number of total workers minus target parallelism
1444      * SS: version count and status of top waiting thread
1445      * ID: poolIndex of top of Treiber stack of waiters
1446      *
1447      * When convenient, we can extract the lower 32 stack top bits
1448      * (including version bits) as sp=(int)ctl.  The offsets of counts
1449      * by the target parallelism and the positionings of fields makes
1450      * it possible to perform the most common checks via sign tests of
1451      * fields: When ac is negative, there are not enough active
1452      * workers, when tc is negative, there are not enough total
1453      * workers.  When sp is non-zero, there are waiting workers.  To
1454      * deal with possibly negative fields, we use casts in and out of
1455      * "short" and/or signed shifts to maintain signedness.
1456      *
1457      * Because it occupies uppermost bits, we can add one active count
1458      * using getAndAddLong of AC_UNIT, rather than CAS, when returning
1459      * from a blocked join.  Other updates entail multiple subfields
1460      * and masking, requiring CAS.
1461      */
1462 
1463     // Lower and upper word masks
1464     private static final long SP_MASK    = 0xffffffffL;
1465     private static final long UC_MASK    = ~SP_MASK;
1466 
1467     // Active counts
1468     private static final int  AC_SHIFT   = 48;
1469     private static final long AC_UNIT    = 0x0001L << AC_SHIFT;
1470     private static final long AC_MASK    = 0xffffL << AC_SHIFT;
1471 
1472     // Total counts
1473     private static final int  TC_SHIFT   = 32;
1474     private static final long TC_UNIT    = 0x0001L << TC_SHIFT;
1475     private static final long TC_MASK    = 0xffffL << TC_SHIFT;
1476     private static final long ADD_WORKER = 0x0001L << (TC_SHIFT + 15); // sign
1477 
1478     // runState bits: SHUTDOWN must be negative, others arbitrary powers of two
1479     private static final int  STARTED    = 1;
1480     private static final int  STOP       = 1 << 1;
1481     private static final int  TERMINATED = 1 << 2;
1482     private static final int  SHUTDOWN   = 1 << 31;
1483 
1484     // Instance fields
1485     volatile long ctl;                   // main pool control
1486     volatile int runState;
1487     final int config;                    // parallelism, mode
1488     AuxState auxState;                   // lock, steal counts
1489     volatile WorkQueue[] workQueues;     // main registry
1490     final String workerNamePrefix;       // to create worker name string
1491     final ForkJoinWorkerThreadFactory factory;
1492     final UncaughtExceptionHandler ueh;  // per-worker UEH
1493 
1494     /**
1495      * Instantiates fields upon first submission, or upon shutdown if
1496      * no submissions. If checkTermination true, also responds to
1497      * termination by external calls submitting tasks.
1498      */
1499     private void tryInitialize(boolean checkTermination) {
1500         if (runState == 0) { // bootstrap by locking static field
1501             int p = config & SMASK;
1502             int n = (p > 1) ? p - 1 : 1; // ensure at least 2 slots
1503             n |= n >>> 1;    // create workQueues array with size a power of two
1504             n |= n >>> 2;
1505             n |= n >>> 4;
1506             n |= n >>> 8;
1507             n |= n >>> 16;
1508             n = ((n + 1) << 1) & SMASK;
1509             AuxState aux = new AuxState();
1510             WorkQueue[] ws = new WorkQueue[n];
1511             synchronized (modifyThreadPermission) { // double-check
1512                 if (runState == 0) {
1513                     workQueues = ws;
1514                     auxState = aux;
1515                     runState = STARTED;
1516                 }
1517             }
1518         }
1519         if (checkTermination && runState < 0) {
1520             tryTerminate(false, false); // help terminate
1521             throw new RejectedExecutionException();
1522         }
1523     }
1524 
1525     // Creating, registering and deregistering workers
1526 
1527     /**
1528      * Tries to construct and start one worker. Assumes that total
1529      * count has already been incremented as a reservation.  Invokes
1530      * deregisterWorker on any failure.
1531      *
1532      * @param isSpare true if this is a spare thread
1533      * @return true if successful
1534      */
1535     private boolean createWorker(boolean isSpare) {
1536         ForkJoinWorkerThreadFactory fac = factory;
1537         Throwable ex = null;
1538         ForkJoinWorkerThread wt = null;
1539         WorkQueue q;
1540         try {
1541             if (fac != null && (wt = fac.newThread(this)) != null) {
1542                 if (isSpare && (q = wt.workQueue) != null)
1543                     q.config |= SPARE_WORKER;
1544                 wt.start();
1545                 return true;
1546             }
1547         } catch (Throwable rex) {
1548             ex = rex;
1549         }
1550         deregisterWorker(wt, ex);
1551         return false;
1552     }
1553 
1554     /**
1555      * Tries to add one worker, incrementing ctl counts before doing
1556      * so, relying on createWorker to back out on failure.
1557      *
1558      * @param c incoming ctl value, with total count negative and no
1559      * idle workers.  On CAS failure, c is refreshed and retried if
1560      * this holds (otherwise, a new worker is not needed).
1561      */
1562     private void tryAddWorker(long c) {
1563         do {
1564             long nc = ((AC_MASK & (c + AC_UNIT)) |
1565                        (TC_MASK & (c + TC_UNIT)));
1566             if (ctl == c && U.compareAndSwapLong(this, CTL, c, nc)) {
1567                 createWorker(false);
1568                 break;
1569             }
1570         } while (((c = ctl) & ADD_WORKER) != 0L && (int)c == 0);
1571     }
1572 
1573     /**
1574      * Callback from ForkJoinWorkerThread constructor to establish and
1575      * record its WorkQueue.
1576      *
1577      * @param wt the worker thread
1578      * @return the worker's queue
1579      */
1580     final WorkQueue registerWorker(ForkJoinWorkerThread wt) {
1581         UncaughtExceptionHandler handler;
1582         AuxState aux;
1583         wt.setDaemon(true);                           // configure thread
1584         if ((handler = ueh) != null)
1585             wt.setUncaughtExceptionHandler(handler);
1586         WorkQueue w = new WorkQueue(this, wt);
1587         int i = 0;                                    // assign a pool index
1588         int mode = config & MODE_MASK;
1589         if ((aux = auxState) != null) {
1590             aux.lock();
1591             try {
1592                 int s = (int)(aux.indexSeed += SEED_INCREMENT), n, m;
1593                 WorkQueue[] ws = workQueues;
1594                 if (ws != null && (n = ws.length) > 0) {
1595                     i = (m = n - 1) & ((s << 1) | 1); // odd-numbered indices
1596                     if (ws[i] != null) {              // collision
1597                         int probes = 0;               // step by approx half n
1598                         int step = (n <= 4) ? 2 : ((n >>> 1) & EVENMASK) + 2;
1599                         while (ws[i = (i + step) & m] != null) {
1600                             if (++probes >= n) {
1601                                 workQueues = ws = Arrays.copyOf(ws, n <<= 1);
1602                                 m = n - 1;
1603                                 probes = 0;
1604                             }
1605                         }
1606                     }
1607                     w.hint = s;                       // use as random seed
1608                     w.config = i | mode;
1609                     w.scanState = i | (s & 0x7fff0000); // random seq bits
1610                     ws[i] = w;
1611                 }
1612             } finally {
1613                 aux.unlock();
1614             }
1615         }
1616         wt.setName(workerNamePrefix.concat(Integer.toString(i >>> 1)));
1617         return w;
1618     }
1619 
1620     /**
1621      * Final callback from terminating worker, as well as upon failure
1622      * to construct or start a worker.  Removes record of worker from
1623      * array, and adjusts counts. If pool is shutting down, tries to
1624      * complete termination.
1625      *
1626      * @param wt the worker thread, or null if construction failed
1627      * @param ex the exception causing failure, or null if none
1628      */
1629     final void deregisterWorker(ForkJoinWorkerThread wt, Throwable ex) {
1630         WorkQueue w = null;
1631         if (wt != null && (w = wt.workQueue) != null) {
1632             AuxState aux; WorkQueue[] ws;          // remove index from array
1633             int idx = w.config & SMASK;
1634             int ns = w.nsteals;
1635             if ((aux = auxState) != null) {
1636                 aux.lock();
1637                 try {
1638                     if ((ws = workQueues) != null && ws.length > idx &&
1639                         ws[idx] == w)
1640                         ws[idx] = null;
1641                     aux.stealCount += ns;
1642                 } finally {
1643                     aux.unlock();
1644                 }
1645             }
1646         }
1647         if (w == null || (w.config & UNREGISTERED) == 0) { // else pre-adjusted
1648             long c;                                   // decrement counts
1649             do {} while (!U.compareAndSwapLong
1650                          (this, CTL, c = ctl, ((AC_MASK & (c - AC_UNIT)) |
1651                                                (TC_MASK & (c - TC_UNIT)) |
1652                                                (SP_MASK & c))));
1653         }
1654         if (w != null) {
1655             w.currentSteal = null;
1656             w.qlock = -1;                             // ensure set
1657             w.cancelAll();                            // cancel remaining tasks
1658         }
1659         while (tryTerminate(false, false) >= 0) {     // possibly replace
1660             WorkQueue[] ws; int wl, sp; long c;
1661             if (w == null || w.array == null ||
1662                 (ws = workQueues) == null || (wl = ws.length) <= 0)
1663                 break;
1664             else if ((sp = (int)(c = ctl)) != 0) {    // wake up replacement
1665                 if (tryRelease(c, ws[(wl - 1) & sp], AC_UNIT))
1666                     break;
1667             }
1668             else if (ex != null && (c & ADD_WORKER) != 0L) {
1669                 tryAddWorker(c);                      // create replacement
1670                 break;
1671             }
1672             else                                      // don't need replacement
1673                 break;
1674         }
1675         if (ex == null)                               // help clean on way out
1676             ForkJoinTask.helpExpungeStaleExceptions();
1677         else                                          // rethrow
1678             ForkJoinTask.rethrow(ex);
1679     }
1680 
1681     // Signalling
1682 
1683     /**
1684      * Tries to create or activate a worker if too few are active.
1685      */
1686     final void signalWork() {
1687         for (;;) {
1688             long c; int sp, i; WorkQueue v; WorkQueue[] ws;
1689             if ((c = ctl) >= 0L)                      // enough workers
1690                 break;
1691             else if ((sp = (int)c) == 0) {            // no idle workers
1692                 if ((c & ADD_WORKER) != 0L)           // too few workers
1693                     tryAddWorker(c);
1694                 break;
1695             }
1696             else if ((ws = workQueues) == null)
1697                 break;                                // unstarted/terminated
1698             else if (ws.length <= (i = sp & SMASK))
1699                 break;                                // terminated
1700             else if ((v = ws[i]) == null)
1701                 break;                                // terminating
1702             else {
1703                 int ns = sp & ~UNSIGNALLED;
1704                 int vs = v.scanState;
1705                 long nc = (v.stackPred & SP_MASK) | (UC_MASK & (c + AC_UNIT));
1706                 if (sp == vs && U.compareAndSwapLong(this, CTL, c, nc)) {
1707                     v.scanState = ns;
1708                     LockSupport.unpark(v.parker);
1709                     break;
1710                 }
1711             }
1712         }
1713     }
1714 
1715     /**
1716      * Signals and releases worker v if it is top of idle worker
1717      * stack.  This performs a one-shot version of signalWork only if
1718      * there is (apparently) at least one idle worker.
1719      *
1720      * @param c incoming ctl value
1721      * @param v if non-null, a worker
1722      * @param inc the increment to active count (zero when compensating)
1723      * @return true if successful
1724      */
1725     private boolean tryRelease(long c, WorkQueue v, long inc) {
1726         int sp = (int)c, ns = sp & ~UNSIGNALLED;
1727         if (v != null) {
1728             int vs = v.scanState;
1729             long nc = (v.stackPred & SP_MASK) | (UC_MASK & (c + inc));
1730             if (sp == vs && U.compareAndSwapLong(this, CTL, c, nc)) {
1731                 v.scanState = ns;
1732                 LockSupport.unpark(v.parker);
1733                 return true;
1734             }
1735         }
1736         return false;
1737     }
1738 
1739     /**
1740      * With approx probability of a missed signal, tries (once) to
1741      * reactivate worker w (or some other worker), failing if stale or
1742      * known to be already active.
1743      *
1744      * @param w the worker
1745      * @param ws the workQueue array to use
1746      * @param r random seed
1747      */
1748     private void tryReactivate(WorkQueue w, WorkQueue[] ws, int r) {
1749         long c; int sp, wl; WorkQueue v;
1750         if ((sp = (int)(c = ctl)) != 0 && w != null &&
1751             ws != null && (wl = ws.length) > 0 &&
1752             ((sp ^ r) & SS_SEQ) == 0 &&
1753             (v = ws[(wl - 1) & sp]) != null) {
1754             long nc = (v.stackPred & SP_MASK) | (UC_MASK & (c + AC_UNIT));
1755             int ns = sp & ~UNSIGNALLED;
1756             if (w.scanState < 0 &&
1757                 v.scanState == sp &&
1758                 U.compareAndSwapLong(this, CTL, c, nc)) {
1759                 v.scanState = ns;
1760                 LockSupport.unpark(v.parker);
1761             }
1762         }
1763     }
1764 
1765     /**
1766      * If worker w exists and is active, enqueues and sets status to inactive.
1767      *
1768      * @param w the worker
1769      * @param ss current (non-negative) scanState
1770      */
1771     private void inactivate(WorkQueue w, int ss) {
1772         int ns = (ss + SS_SEQ) | UNSIGNALLED;
1773         long lc = ns & SP_MASK, nc, c;
1774         if (w != null) {
1775             w.scanState = ns;
1776             do {
1777                 nc = lc | (UC_MASK & ((c = ctl) - AC_UNIT));
1778                 w.stackPred = (int)c;
1779             } while (!U.compareAndSwapLong(this, CTL, c, nc));
1780         }
1781     }
1782 
1783     /**
1784      * Possibly blocks worker w waiting for signal, or returns
1785      * negative status if the worker should terminate. May return
1786      * without status change if multiple stale unparks and/or
1787      * interrupts occur.
1788      *
1789      * @param w the calling worker
1790      * @return negative if w should terminate
1791      */
1792     private int awaitWork(WorkQueue w) {
1793         int stat = 0;
1794         if (w != null && w.scanState < 0) {
1795             long c = ctl;
1796             if ((int)(c >> AC_SHIFT) + (config & SMASK) <= 0)
1797                 stat = timedAwaitWork(w, c);     // possibly quiescent
1798             else if ((runState & STOP) != 0)
1799                 stat = w.qlock = -1;             // pool terminating
1800             else if (w.scanState < 0) {
1801                 w.parker = Thread.currentThread();
1802                 if (w.scanState < 0)             // recheck after write
1803                     LockSupport.park(this);
1804                 w.parker = null;
1805                 if ((runState & STOP) != 0)
1806                     stat = w.qlock = -1;         // recheck
1807                 else if (w.scanState < 0)
1808                     Thread.interrupted();        // clear status
1809             }
1810         }
1811         return stat;
1812     }
1813 
1814     /**
1815      * Possibly triggers shutdown and tries (once) to block worker
1816      * when pool is (or may be) quiescent. Waits up to a duration
1817      * determined by number of workers.  On timeout, if ctl has not
1818      * changed, terminates the worker, which will in turn wake up
1819      * another worker to possibly repeat this process.
1820      *
1821      * @param w the calling worker
1822      * @return negative if w should terminate
1823      */
1824     private int timedAwaitWork(WorkQueue w, long c) {
1825         int stat = 0;
1826         int scale = 1 - (short)(c >>> TC_SHIFT);
1827         long deadline = (((scale <= 0) ? 1 : scale) * IDLE_TIMEOUT_MS +
1828                          System.currentTimeMillis());
1829         if ((runState >= 0 || (stat = tryTerminate(false, false)) > 0) &&
1830             w != null && w.scanState < 0) {
1831             int ss; AuxState aux;
1832             w.parker = Thread.currentThread();
1833             if (w.scanState < 0)
1834                 LockSupport.parkUntil(this, deadline);
1835             w.parker = null;
1836             if ((runState & STOP) != 0)
1837                 stat = w.qlock = -1;         // pool terminating
1838             else if ((ss = w.scanState) < 0 && !Thread.interrupted() &&
1839                      (int)c == ss && (aux = auxState) != null && ctl == c &&
1840                      deadline - System.currentTimeMillis() <= TIMEOUT_SLOP_MS) {
1841                 aux.lock();
1842                 try {                        // pre-deregister
1843                     WorkQueue[] ws;
1844                     int cfg = w.config, idx = cfg & SMASK;
1845                     long nc = ((UC_MASK & (c - TC_UNIT)) |
1846                                (SP_MASK & w.stackPred));
1847                     if ((runState & STOP) == 0 &&
1848                         (ws = workQueues) != null &&
1849                         idx < ws.length && idx >= 0 && ws[idx] == w &&
1850                         U.compareAndSwapLong(this, CTL, c, nc)) {
1851                         ws[idx] = null;
1852                         w.config = cfg | UNREGISTERED;
1853                         stat = w.qlock = -1;
1854                     }
1855                 } finally {
1856                     aux.unlock();
1857                 }
1858             }
1859         }
1860         return stat;
1861     }
1862 
1863     /**
1864      * If the given worker is a spare with no queued tasks, and there
1865      * are enough existing workers, drops it from ctl counts and sets
1866      * its state to terminated.
1867      *
1868      * @param w the calling worker -- must be a spare
1869      * @return true if dropped (in which case it must not process more tasks)
1870      */
1871     private boolean tryDropSpare(WorkQueue w) {
1872         if (w != null && w.isEmpty()) {           // no local tasks
1873             long c; int sp, wl; WorkQueue[] ws; WorkQueue v;
1874             while ((short)((c = ctl) >> TC_SHIFT) > 0 &&
1875                    ((sp = (int)c) != 0 || (int)(c >> AC_SHIFT) > 0) &&
1876                    (ws = workQueues) != null && (wl = ws.length) > 0) {
1877                 boolean dropped, canDrop;
1878                 if (sp == 0) {                    // no queued workers
1879                     long nc = ((AC_MASK & (c - AC_UNIT)) |
1880                                (TC_MASK & (c - TC_UNIT)) | (SP_MASK & c));
1881                     dropped = U.compareAndSwapLong(this, CTL, c, nc);
1882                 }
1883                 else if (
1884                     (v = ws[(wl - 1) & sp]) == null || v.scanState != sp)
1885                     dropped = false;              // stale; retry
1886                 else {
1887                     long nc = v.stackPred & SP_MASK;
1888                     if (w == v || w.scanState >= 0) {
1889                         canDrop = true;           // w unqueued or topmost
1890                         nc |= ((AC_MASK & c) |    // ensure replacement
1891                                (TC_MASK & (c - TC_UNIT)));
1892                     }
1893                     else {                        // w may be queued
1894                         canDrop = false;          // help uncover
1895                         nc |= ((AC_MASK & (c + AC_UNIT)) |
1896                                (TC_MASK & c));
1897                     }
1898                     if (U.compareAndSwapLong(this, CTL, c, nc)) {
1899                         v.scanState = sp & ~UNSIGNALLED;
1900                         LockSupport.unpark(v.parker);
1901                         dropped = canDrop;
1902                     }
1903                     else
1904                         dropped = false;
1905                 }
1906                 if (dropped) {                    // pre-deregister
1907                     int cfg = w.config, idx = cfg & SMASK;
1908                     if (idx >= 0 && idx < ws.length && ws[idx] == w)
1909                         ws[idx] = null;
1910                     w.config = cfg | UNREGISTERED;
1911                     w.qlock = -1;
1912                     return true;
1913                 }
1914             }
1915         }
1916         return false;
1917     }
1918 
1919     /**
1920      * Top-level runloop for workers, called by ForkJoinWorkerThread.run.
1921      */
1922     final void runWorker(WorkQueue w) {
1923         w.growArray();                                  // allocate queue
1924         int bound = (w.config & SPARE_WORKER) != 0 ? 0 : POLL_LIMIT;
1925         long seed = w.hint * 0xdaba0b6eb09322e3L;       // initial random seed
1926         if ((runState & STOP) == 0) {
1927             for (long r = (seed == 0L) ? 1L : seed;;) { // ensure nonzero
1928                 if (bound == 0 && tryDropSpare(w))
1929                     break;
1930                 // high bits of prev seed for step; current low bits for idx
1931                 int step = (int)(r >>> 48) | 1;
1932                 r ^= r >>> 12; r ^= r << 25; r ^= r >>> 27; // xorshift
1933                 if (scan(w, bound, step, (int)r) < 0 && awaitWork(w) < 0)
1934                     break;
1935             }
1936         }
1937     }
1938 
1939     // Scanning for tasks
1940 
1941     /**
1942      * Repeatedly scans for and tries to steal and execute (via
1943      * workQueue.runTask) a queued task. Each scan traverses queues in
1944      * pseudorandom permutation. Upon finding a non-empty queue, makes
1945      * at most the given bound attempts to re-poll (fewer if
1946      * contended) on the same queue before returning (impossible
1947      * scanState value) 0 to restart scan. Else returns after at least
1948      * 1 and at most 32 full scans.
1949      *
1950      * @param w the worker (via its WorkQueue)
1951      * @param bound repoll bound as bitmask (0 if spare)
1952      * @param step (circular) index increment per iteration (must be odd)
1953      * @param r a random seed for origin index
1954      * @return negative if should await signal
1955      */
1956     private int scan(WorkQueue w, int bound, int step, int r) {
1957         int stat = 0, wl; WorkQueue[] ws;
1958         if ((ws = workQueues) != null && w != null && (wl = ws.length) > 0) {
1959             for (int m = wl - 1,
1960                      origin = m & r, idx = origin,
1961                      npolls = 0,
1962                      ss = w.scanState;;) {         // negative if inactive
1963                 WorkQueue q; ForkJoinTask<?>[] a; int b, al;
1964                 if ((q = ws[idx]) != null && (b = q.base) - q.top < 0 &&
1965                     (a = q.array) != null && (al = a.length) > 0) {
1966                     int index = (al - 1) & b;
1967                     long offset = ((long)index << ASHIFT) + ABASE;
1968                     ForkJoinTask<?> t = (ForkJoinTask<?>)
1969                         U.getObjectVolatile(a, offset);
1970                     if (t == null)
1971                         break;                     // empty or busy
1972                     else if (b++ != q.base)
1973                         break;                     // busy
1974                     else if (ss < 0) {
1975                         tryReactivate(w, ws, r);
1976                         break;                     // retry upon rescan
1977                     }
1978                     else if (!U.compareAndSwapObject(a, offset, t, null))
1979                         break;                     // contended
1980                     else {
1981                         q.base = b;
1982                         w.currentSteal = t;
1983                         if (b != q.top)            // propagate signal
1984                             signalWork();
1985                         w.runTask(t);
1986                         if (++npolls > bound)
1987                             break;
1988                     }
1989                 }
1990                 else if (npolls != 0)              // rescan
1991                     break;
1992                 else if ((idx = (idx + step) & m) == origin) {
1993                     if (ss < 0) {                  // await signal
1994                         stat = ss;
1995                         break;
1996                     }
1997                     else if (r >= 0) {
1998                         inactivate(w, ss);
1999                         break;
2000                     }
2001                     else
2002                         r <<= 1;                   // at most 31 rescans
2003                 }
2004             }
2005         }
2006         return stat;
2007     }
2008 
2009     // Joining tasks
2010 
2011     /**
2012      * Tries to steal and run tasks within the target's computation.
2013      * Uses a variant of the top-level algorithm, restricted to tasks
2014      * with the given task as ancestor: It prefers taking and running
2015      * eligible tasks popped from the worker's own queue (via
2016      * popCC). Otherwise it scans others, randomly moving on
2017      * contention or execution, deciding to give up based on a
2018      * checksum (via return codes from pollAndExecCC). The maxTasks
2019      * argument supports external usages; internal calls use zero,
2020      * allowing unbounded steps (external calls trap non-positive
2021      * values).
2022      *
2023      * @param w caller
2024      * @param maxTasks if non-zero, the maximum number of other tasks to run
2025      * @return task status on exit
2026      */
2027     final int helpComplete(WorkQueue w, CountedCompleter<?> task,
2028                            int maxTasks) {
2029         WorkQueue[] ws; int s = 0, wl;
2030         if ((ws = workQueues) != null && (wl = ws.length) > 1 &&
2031             task != null && w != null) {
2032             for (int m = wl - 1,
2033                      mode = w.config,
2034                      r = ~mode,                  // scanning seed
2035                      origin = r & m, k = origin, // first queue to scan
2036                      step = 3,                   // first scan step
2037                      h = 1,                      // 1:ran, >1:contended, <0:hash
2038                      oldSum = 0, checkSum = 0;;) {
2039                 CountedCompleter<?> p; WorkQueue q; int i;
2040                 if ((s = task.status) < 0)
2041                     break;
2042                 if (h == 1 && (p = w.popCC(task, mode)) != null) {
2043                     p.doExec();                  // run local task
2044                     if (maxTasks != 0 && --maxTasks == 0)
2045                         break;
2046                     origin = k;                  // reset
2047                     oldSum = checkSum = 0;
2048                 }
2049                 else {                           // poll other worker queues
2050                     if ((i = k | 1) < 0 || i > m || (q = ws[i]) == null)
2051                         h = 0;
2052                     else if ((h = q.pollAndExecCC(task)) < 0)
2053                         checkSum += h;
2054                     if (h > 0) {
2055                         if (h == 1 && maxTasks != 0 && --maxTasks == 0)
2056                             break;
2057                         step = (r >>> 16) | 3;
2058                         r ^= r << 13; r ^= r >>> 17; r ^= r << 5; // xorshift
2059                         k = origin = r & m;      // move and restart
2060                         oldSum = checkSum = 0;
2061                     }
2062                     else if ((k = (k + step) & m) == origin) {
2063                         if (oldSum == (oldSum = checkSum))
2064                             break;
2065                         checkSum = 0;
2066                     }
2067                 }
2068             }
2069         }
2070         return s;
2071     }
2072 
2073     /**
2074      * Tries to locate and execute tasks for a stealer of the given
2075      * task, or in turn one of its stealers. Traces currentSteal ->
2076      * currentJoin links looking for a thread working on a descendant
2077      * of the given task and with a non-empty queue to steal back and
2078      * execute tasks from. The first call to this method upon a
2079      * waiting join will often entail scanning/search, (which is OK
2080      * because the joiner has nothing better to do), but this method
2081      * leaves hints in workers to speed up subsequent calls.
2082      *
2083      * @param w caller
2084      * @param task the task to join
2085      */
2086     private void helpStealer(WorkQueue w, ForkJoinTask<?> task) {
2087         if (task != null && w != null) {
2088             ForkJoinTask<?> ps = w.currentSteal;
2089             WorkQueue[] ws; int wl, oldSum = 0;
2090             outer: while (w.tryRemoveAndExec(task) && task.status >= 0 &&
2091                           (ws = workQueues) != null && (wl = ws.length) > 0) {
2092                 ForkJoinTask<?> subtask;
2093                 int m = wl - 1, checkSum = 0;          // for stability check
2094                 WorkQueue j = w, v;                    // v is subtask stealer
2095                 descent: for (subtask = task; subtask.status >= 0; ) {
2096                     for (int h = j.hint | 1, k = 0, i;;) {
2097                         if ((v = ws[i = (h + (k << 1)) & m]) != null) {
2098                             if (v.currentSteal == subtask) {
2099                                 j.hint = i;
2100                                 break;
2101                             }
2102                             checkSum += v.base;
2103                         }
2104                         if (++k > m)                   // can't find stealer
2105                             break outer;
2106                     }
2107 
2108                     for (;;) {                         // help v or descend
2109                         ForkJoinTask<?>[] a; int b, al;
2110                         if (subtask.status < 0)        // too late to help
2111                             break descent;
2112                         checkSum += (b = v.base);
2113                         ForkJoinTask<?> next = v.currentJoin;
2114                         ForkJoinTask<?> t = null;
2115                         if ((a = v.array) != null && (al = a.length) > 0) {
2116                             int index = (al - 1) & b;
2117                             long offset = ((long)index << ASHIFT) + ABASE;
2118                             t = (ForkJoinTask<?>)
2119                                 U.getObjectVolatile(a, offset);
2120                             if (t != null && b++ == v.base) {
2121                                 if (j.currentJoin != subtask ||
2122                                     v.currentSteal != subtask ||
2123                                     subtask.status < 0)
2124                                     break descent;     // stale
2125                                 if (U.compareAndSwapObject(a, offset, t, null)) {
2126                                     v.base = b;
2127                                     w.currentSteal = t;
2128                                     for (int top = w.top;;) {
2129                                         t.doExec();    // help
2130                                         w.currentSteal = ps;
2131                                         if (task.status < 0)
2132                                             break outer;
2133                                         if (w.top == top)
2134                                             break;     // run local tasks
2135                                         if ((t = w.pop()) == null)
2136                                             break descent;
2137                                         w.currentSteal = t;
2138                                     }
2139                                 }
2140                             }
2141                         }
2142                         if (t == null && b == v.base && b - v.top >= 0) {
2143                             if ((subtask = next) == null) {  // try to descend
2144                                 if (next == v.currentJoin &&
2145                                     oldSum == (oldSum = checkSum))
2146                                     break outer;
2147                                 break descent;
2148                             }
2149                             j = v;
2150                             break;
2151                         }
2152                     }
2153                 }
2154             }
2155         }
2156     }
2157 
2158     /**
2159      * Tries to decrement active count (sometimes implicitly) and
2160      * possibly release or create a compensating worker in preparation
2161      * for blocking. Returns false (retryable by caller), on
2162      * contention, detected staleness, instability, or termination.
2163      *
2164      * @param w caller
2165      */
2166     private boolean tryCompensate(WorkQueue w) {
2167         boolean canBlock; int wl;
2168         long c = ctl;
2169         WorkQueue[] ws = workQueues;
2170         int pc = config & SMASK;
2171         int ac = pc + (int)(c >> AC_SHIFT);
2172         int tc = pc + (short)(c >> TC_SHIFT);
2173         if (w == null || w.qlock < 0 || pc == 0 ||  // terminating or disabled
2174             ws == null || (wl = ws.length) <= 0)
2175             canBlock = false;
2176         else {
2177             int m = wl - 1, sp;
2178             boolean busy = true;                    // validate ac
2179             for (int i = 0; i <= m; ++i) {
2180                 int k; WorkQueue v;
2181                 if ((k = (i << 1) | 1) <= m && k >= 0 && (v = ws[k]) != null &&
2182                     v.scanState >= 0 && v.currentSteal == null) {
2183                     busy = false;
2184                     break;
2185                 }
2186             }
2187             if (!busy || ctl != c)
2188                 canBlock = false;                   // unstable or stale
2189             else if ((sp = (int)c) != 0)            // release idle worker
2190                 canBlock = tryRelease(c, ws[m & sp], 0L);
2191             else if (tc >= pc && ac > 1 && w.isEmpty()) {
2192                 long nc = ((AC_MASK & (c - AC_UNIT)) |
2193                            (~AC_MASK & c));         // uncompensated
2194                 canBlock = U.compareAndSwapLong(this, CTL, c, nc);
2195             }
2196             else if (tc >= MAX_CAP ||
2197                      (this == common && tc >= pc + COMMON_MAX_SPARES))
2198                 throw new RejectedExecutionException(
2199                     "Thread limit exceeded replacing blocked worker");
2200             else {                                  // similar to tryAddWorker
2201                 boolean isSpare = (tc >= pc);
2202                 long nc = (AC_MASK & c) | (TC_MASK & (c + TC_UNIT));
2203                 canBlock = (U.compareAndSwapLong(this, CTL, c, nc) &&
2204                             createWorker(isSpare)); // throws on exception
2205             }
2206         }
2207         return canBlock;
2208     }
2209 
2210     /**
2211      * Helps and/or blocks until the given task is done or timeout.
2212      *
2213      * @param w caller
2214      * @param task the task
2215      * @param deadline for timed waits, if nonzero
2216      * @return task status on exit
2217      */
2218     final int awaitJoin(WorkQueue w, ForkJoinTask<?> task, long deadline) {
2219         int s = 0;
2220         if (w != null) {
2221             ForkJoinTask<?> prevJoin = w.currentJoin;
2222             if (task != null && (s = task.status) >= 0) {
2223                 w.currentJoin = task;
2224                 CountedCompleter<?> cc = (task instanceof CountedCompleter) ?
2225                     (CountedCompleter<?>)task : null;
2226                 for (;;) {
2227                     if (cc != null)
2228                         helpComplete(w, cc, 0);
2229                     else
2230                         helpStealer(w, task);
2231                     if ((s = task.status) < 0)
2232                         break;
2233                     long ms, ns;
2234                     if (deadline == 0L)
2235                         ms = 0L;
2236                     else if ((ns = deadline - System.nanoTime()) <= 0L)
2237                         break;
2238                     else if ((ms = TimeUnit.NANOSECONDS.toMillis(ns)) <= 0L)
2239                         ms = 1L;
2240                     if (tryCompensate(w)) {
2241                         task.internalWait(ms);
2242                         U.getAndAddLong(this, CTL, AC_UNIT);
2243                     }
2244                     if ((s = task.status) < 0)
2245                         break;
2246                 }
2247                 w.currentJoin = prevJoin;
2248             }
2249         }
2250         return s;
2251     }
2252 
2253     // Specialized scanning
2254 
2255     /**
2256      * Returns a (probably) non-empty steal queue, if one is found
2257      * during a scan, else null.  This method must be retried by
2258      * caller if, by the time it tries to use the queue, it is empty.
2259      */
2260     private WorkQueue findNonEmptyStealQueue() {
2261         WorkQueue[] ws; int wl;  // one-shot version of scan loop
2262         int r = ThreadLocalRandom.nextSecondarySeed();
2263         if ((ws = workQueues) != null && (wl = ws.length) > 0) {
2264             int m = wl - 1, origin = r & m;
2265             for (int k = origin, oldSum = 0, checkSum = 0;;) {
2266                 WorkQueue q; int b;
2267                 if ((q = ws[k]) != null) {
2268                     if ((b = q.base) - q.top < 0)
2269                         return q;
2270                     checkSum += b;
2271                 }
2272                 if ((k = (k + 1) & m) == origin) {
2273                     if (oldSum == (oldSum = checkSum))
2274                         break;
2275                     checkSum = 0;
2276                 }
2277             }
2278         }
2279         return null;
2280     }
2281 
2282     /**
2283      * Runs tasks until {@code isQuiescent()}. We piggyback on
2284      * active count ctl maintenance, but rather than blocking
2285      * when tasks cannot be found, we rescan until all others cannot
2286      * find tasks either.
2287      */
2288     final void helpQuiescePool(WorkQueue w) {
2289         ForkJoinTask<?> ps = w.currentSteal; // save context
2290         int wc = w.config;
2291         for (boolean active = true;;) {
2292             long c; WorkQueue q; ForkJoinTask<?> t;
2293             if (wc >= 0 && (t = w.pop()) != null) { // run locals if LIFO
2294                 (w.currentSteal = t).doExec();
2295                 w.currentSteal = ps;
2296             }
2297             else if ((q = findNonEmptyStealQueue()) != null) {
2298                 if (!active) {      // re-establish active count
2299                     active = true;
2300                     U.getAndAddLong(this, CTL, AC_UNIT);
2301                 }
2302                 if ((t = q.pollAt(q.base)) != null) {
2303                     (w.currentSteal = t).doExec();
2304                     w.currentSteal = ps;
2305                     if (++w.nsteals < 0)
2306                         w.transferStealCount(this);
2307                 }
2308             }
2309             else if (active) {      // decrement active count without queuing
2310                 long nc = (AC_MASK & ((c = ctl) - AC_UNIT)) | (~AC_MASK & c);
2311                 if (U.compareAndSwapLong(this, CTL, c, nc))
2312                     active = false;
2313             }
2314             else if ((int)((c = ctl) >> AC_SHIFT) + (config & SMASK) <= 0 &&
2315                      U.compareAndSwapLong(this, CTL, c, c + AC_UNIT))
2316                 break;
2317         }
2318     }
2319 
2320     /**
2321      * Gets and removes a local or stolen task for the given worker.
2322      *
2323      * @return a task, if available
2324      */
2325     final ForkJoinTask<?> nextTaskFor(WorkQueue w) {
2326         for (ForkJoinTask<?> t;;) {
2327             WorkQueue q;
2328             if ((t = w.nextLocalTask()) != null)
2329                 return t;
2330             if ((q = findNonEmptyStealQueue()) == null)
2331                 return null;
2332             if ((t = q.pollAt(q.base)) != null)
2333                 return t;
2334         }
2335     }
2336 
2337     /**
2338      * Returns a cheap heuristic guide for task partitioning when
2339      * programmers, frameworks, tools, or languages have little or no
2340      * idea about task granularity.  In essence, by offering this
2341      * method, we ask users only about tradeoffs in overhead vs
2342      * expected throughput and its variance, rather than how finely to
2343      * partition tasks.
2344      *
2345      * In a steady state strict (tree-structured) computation, each
2346      * thread makes available for stealing enough tasks for other
2347      * threads to remain active. Inductively, if all threads play by
2348      * the same rules, each thread should make available only a
2349      * constant number of tasks.
2350      *
2351      * The minimum useful constant is just 1. But using a value of 1
2352      * would require immediate replenishment upon each steal to
2353      * maintain enough tasks, which is infeasible.  Further,
2354      * partitionings/granularities of offered tasks should minimize
2355      * steal rates, which in general means that threads nearer the top
2356      * of computation tree should generate more than those nearer the
2357      * bottom. In perfect steady state, each thread is at
2358      * approximately the same level of computation tree. However,
2359      * producing extra tasks amortizes the uncertainty of progress and
2360      * diffusion assumptions.
2361      *
2362      * So, users will want to use values larger (but not much larger)
2363      * than 1 to both smooth over transient shortages and hedge
2364      * against uneven progress; as traded off against the cost of
2365      * extra task overhead. We leave the user to pick a threshold
2366      * value to compare with the results of this call to guide
2367      * decisions, but recommend values such as 3.
2368      *
2369      * When all threads are active, it is on average OK to estimate
2370      * surplus strictly locally. In steady-state, if one thread is
2371      * maintaining say 2 surplus tasks, then so are others. So we can
2372      * just use estimated queue length.  However, this strategy alone
2373      * leads to serious mis-estimates in some non-steady-state
2374      * conditions (ramp-up, ramp-down, other stalls). We can detect
2375      * many of these by further considering the number of "idle"
2376      * threads, that are known to have zero queued tasks, so
2377      * compensate by a factor of (#idle/#active) threads.
2378      */
2379     static int getSurplusQueuedTaskCount() {
2380         Thread t; ForkJoinWorkerThread wt; ForkJoinPool pool; WorkQueue q;
2381         if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) {
2382             int p = (pool = (wt = (ForkJoinWorkerThread)t).pool).config & SMASK;
2383             int n = (q = wt.workQueue).top - q.base;
2384             int a = (int)(pool.ctl >> AC_SHIFT) + p;
2385             return n - (a > (p >>>= 1) ? 0 :
2386                         a > (p >>>= 1) ? 1 :
2387                         a > (p >>>= 1) ? 2 :
2388                         a > (p >>>= 1) ? 4 :
2389                         8);
2390         }
2391         return 0;
2392     }
2393 
2394     //  Termination
2395 
2396     /**
2397      * Possibly initiates and/or completes termination.
2398      *
2399      * @param now if true, unconditionally terminate, else only
2400      * if no work and no active workers
2401      * @param enable if true, terminate when next possible
2402      * @return -1: terminating/terminated, 0: retry if internal caller, else 1
2403      */
2404     private int tryTerminate(boolean now, boolean enable) {
2405         int rs; // 3 phases: try to set SHUTDOWN, then STOP, then TERMINATED
2406 
2407         while ((rs = runState) >= 0) {
2408             if (!enable || this == common)        // cannot shutdown
2409                 return 1;
2410             else if (rs == 0)
2411                 tryInitialize(false);             // ensure initialized
2412             else
2413                 U.compareAndSwapInt(this, RUNSTATE, rs, rs | SHUTDOWN);
2414         }
2415 
2416         if ((rs & STOP) == 0) {                   // try to initiate termination
2417             if (!now) {                           // check quiescence
2418                 for (long oldSum = 0L;;) {        // repeat until stable
2419                     WorkQueue[] ws; WorkQueue w; int b;
2420                     long checkSum = ctl;
2421                     if ((int)(checkSum >> AC_SHIFT) + (config & SMASK) > 0)
2422                         return 0;                 // still active workers
2423                     if ((ws = workQueues) != null) {
2424                         for (int i = 0; i < ws.length; ++i) {
2425                             if ((w = ws[i]) != null) {
2426                                 checkSum += (b = w.base);
2427                                 if (w.currentSteal != null || b != w.top)
2428                                     return 0;     // retry if internal caller
2429                             }
2430                         }
2431                     }
2432                     if (oldSum == (oldSum = checkSum))
2433                         break;
2434                 }
2435             }
2436             do {} while (!U.compareAndSwapInt(this, RUNSTATE,
2437                                               rs = runState, rs | STOP));
2438         }
2439 
2440         for (long oldSum = 0L;;) {                // repeat until stable
2441             WorkQueue[] ws; WorkQueue w; ForkJoinWorkerThread wt;
2442             long checkSum = ctl;
2443             if ((ws = workQueues) != null) {      // help terminate others
2444                 for (int i = 0; i < ws.length; ++i) {
2445                     if ((w = ws[i]) != null) {
2446                         w.cancelAll();            // clear queues
2447                         checkSum += w.base;
2448                         if (w.qlock >= 0) {
2449                             w.qlock = -1;         // racy set OK
2450                             if ((wt = w.owner) != null) {
2451                                 try {             // unblock join or park
2452                                     wt.interrupt();
2453                                 } catch (Throwable ignore) {
2454                                 }
2455                             }
2456                         }
2457                     }
2458                 }
2459             }
2460             if (oldSum == (oldSum = checkSum))
2461                 break;
2462         }
2463 
2464         if ((short)(ctl >>> TC_SHIFT) + (config & SMASK) <= 0) {
2465             runState = (STARTED | SHUTDOWN | STOP | TERMINATED); // final write
2466             synchronized (this) {
2467                 notifyAll();                      // for awaitTermination
2468             }
2469         }
2470 
2471         return -1;
2472     }
2473 
2474     // External operations
2475 
2476     /**
2477      * Constructs and tries to install a new external queue,
2478      * failing if the workQueues array already has a queue at
2479      * the given index.
2480      *
2481      * @param index the index of the new queue
2482      */
2483     private void tryCreateExternalQueue(int index) {
2484         AuxState aux;
2485         if ((aux = auxState) != null && index >= 0) {
2486             WorkQueue q = new WorkQueue(this, null);
2487             q.config = index;
2488             q.scanState = ~UNSIGNALLED;
2489             q.qlock = 1;                   // lock queue
2490             boolean installed = false;
2491             aux.lock();
2492             try {                          // lock pool to install
2493                 WorkQueue[] ws;
2494                 if ((ws = workQueues) != null && index < ws.length &&
2495                     ws[index] == null) {
2496                     ws[index] = q;         // else throw away
2497                     installed = true;
2498                 }
2499             } finally {
2500                 aux.unlock();
2501             }
2502             if (installed) {
2503                 try {
2504                     q.growArray();
2505                 } finally {
2506                     q.qlock = 0;
2507                 }
2508             }
2509         }
2510     }
2511 
2512     /**
2513      * Adds the given task to a submission queue at submitter's
2514      * current queue. Also performs secondary initialization upon the
2515      * first submission of the first task to the pool, and detects
2516      * first submission by an external thread and creates a new shared
2517      * queue if the one at index if empty or contended.
2518      *
2519      * @param task the task. Caller must ensure non-null.
2520      */
2521     final void externalPush(ForkJoinTask<?> task) {
2522         int r;                            // initialize caller's probe
2523         if ((r = ThreadLocalRandom.getProbe()) == 0) {
2524             ThreadLocalRandom.localInit();
2525             r = ThreadLocalRandom.getProbe();
2526         }
2527         for (;;) {
2528             WorkQueue q; int wl, k, stat;
2529             int rs = runState;
2530             WorkQueue[] ws = workQueues;
2531             if (rs <= 0 || ws == null || (wl = ws.length) <= 0)
2532                 tryInitialize(true);
2533             else if ((q = ws[k = (wl - 1) & r & SQMASK]) == null)
2534                 tryCreateExternalQueue(k);
2535             else if ((stat = q.sharedPush(task)) < 0)
2536                 break;
2537             else if (stat == 0) {
2538                 signalWork();
2539                 break;
2540             }
2541             else                          // move if busy
2542                 r = ThreadLocalRandom.advanceProbe(r);
2543         }
2544     }
2545 
2546     /**
2547      * Pushes a possibly-external submission.
2548      */
2549     private <T> ForkJoinTask<T> externalSubmit(ForkJoinTask<T> task) {
2550         Thread t; ForkJoinWorkerThread w; WorkQueue q;
2551         if (task == null)
2552             throw new NullPointerException();
2553         if (((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) &&
2554             (w = (ForkJoinWorkerThread)t).pool == this &&
2555             (q = w.workQueue) != null)
2556             q.push(task);
2557         else
2558             externalPush(task);
2559         return task;
2560     }
2561 
2562     /**
2563      * Returns common pool queue for an external thread.
2564      */
2565     static WorkQueue commonSubmitterQueue() {
2566         ForkJoinPool p = common;
2567         int r = ThreadLocalRandom.getProbe();
2568         WorkQueue[] ws; int wl;
2569         return (p != null && (ws = p.workQueues) != null &&
2570                 (wl = ws.length) > 0) ?
2571             ws[(wl - 1) & r & SQMASK] : null;
2572     }
2573 
2574     /**
2575      * Performs tryUnpush for an external submitter.
2576      */
2577     final boolean tryExternalUnpush(ForkJoinTask<?> task) {
2578         int r = ThreadLocalRandom.getProbe();
2579         WorkQueue[] ws; WorkQueue w; int wl;
2580         return ((ws = workQueues) != null &&
2581                 (wl = ws.length) > 0 &&
2582                 (w = ws[(wl - 1) & r & SQMASK]) != null &&
2583                 w.trySharedUnpush(task));
2584     }
2585 
2586     /**
2587      * Performs helpComplete for an external submitter.
2588      */
2589     final int externalHelpComplete(CountedCompleter<?> task, int maxTasks) {
2590         WorkQueue[] ws; int wl;
2591         int r = ThreadLocalRandom.getProbe();
2592         return ((ws = workQueues) != null && (wl = ws.length) > 0) ?
2593             helpComplete(ws[(wl - 1) & r & SQMASK], task, maxTasks) : 0;
2594     }
2595 
2596     // Exported methods
2597 
2598     // Constructors
2599 
2600     /**
2601      * Creates a {@code ForkJoinPool} with parallelism equal to {@link
2602      * java.lang.Runtime#availableProcessors}, using the {@linkplain
2603      * #defaultForkJoinWorkerThreadFactory default thread factory},
2604      * no UncaughtExceptionHandler, and non-async LIFO processing mode.
2605      *
2606      * @throws SecurityException if a security manager exists and
2607      *         the caller is not permitted to modify threads
2608      *         because it does not hold {@link
2609      *         java.lang.RuntimePermission}{@code ("modifyThread")}
2610      */
2611     public ForkJoinPool() {
2612         this(Math.min(MAX_CAP, Runtime.getRuntime().availableProcessors()),
2613              defaultForkJoinWorkerThreadFactory, null, false);
2614     }
2615 
2616     /**
2617      * Creates a {@code ForkJoinPool} with the indicated parallelism
2618      * level, the {@linkplain
2619      * #defaultForkJoinWorkerThreadFactory default thread factory},
2620      * no UncaughtExceptionHandler, and non-async LIFO processing mode.
2621      *
2622      * @param parallelism the parallelism level
2623      * @throws IllegalArgumentException if parallelism less than or
2624      *         equal to zero, or greater than implementation limit
2625      * @throws SecurityException if a security manager exists and
2626      *         the caller is not permitted to modify threads
2627      *         because it does not hold {@link
2628      *         java.lang.RuntimePermission}{@code ("modifyThread")}
2629      */
2630     public ForkJoinPool(int parallelism) {
2631         this(parallelism, defaultForkJoinWorkerThreadFactory, null, false);
2632     }
2633 
2634     /**
2635      * Creates a {@code ForkJoinPool} with the given parameters.
2636      *
2637      * @param parallelism the parallelism level. For default value,
2638      * use {@link java.lang.Runtime#availableProcessors}.
2639      * @param factory the factory for creating new threads. For default value,
2640      * use {@link #defaultForkJoinWorkerThreadFactory}.
2641      * @param handler the handler for internal worker threads that
2642      * terminate due to unrecoverable errors encountered while executing
2643      * tasks. For default value, use {@code null}.
2644      * @param asyncMode if true,
2645      * establishes local first-in-first-out scheduling mode for forked
2646      * tasks that are never joined. This mode may be more appropriate
2647      * than default locally stack-based mode in applications in which
2648      * worker threads only process event-style asynchronous tasks.
2649      * For default value, use {@code false}.
2650      * @throws IllegalArgumentException if parallelism less than or
2651      *         equal to zero, or greater than implementation limit
2652      * @throws NullPointerException if the factory is null
2653      * @throws SecurityException if a security manager exists and
2654      *         the caller is not permitted to modify threads
2655      *         because it does not hold {@link
2656      *         java.lang.RuntimePermission}{@code ("modifyThread")}
2657      */
2658     public ForkJoinPool(int parallelism,
2659                         ForkJoinWorkerThreadFactory factory,
2660                         UncaughtExceptionHandler handler,
2661                         boolean asyncMode) {
2662         this(checkParallelism(parallelism),
2663              checkFactory(factory),
2664              handler,
2665              asyncMode ? FIFO_QUEUE : LIFO_QUEUE,
2666              "ForkJoinPool-" + nextPoolId() + "-worker-");
2667         checkPermission();
2668     }
2669 
2670     private static int checkParallelism(int parallelism) {
2671         if (parallelism <= 0 || parallelism > MAX_CAP)
2672             throw new IllegalArgumentException();
2673         return parallelism;
2674     }
2675 
2676     private static ForkJoinWorkerThreadFactory checkFactory
2677         (ForkJoinWorkerThreadFactory factory) {
2678         if (factory == null)
2679             throw new NullPointerException();
2680         return factory;
2681     }
2682 
2683     /**
2684      * Creates a {@code ForkJoinPool} with the given parameters, without
2685      * any security checks or parameter validation.  Invoked directly by
2686      * makeCommonPool.
2687      */
2688     private ForkJoinPool(int parallelism,
2689                          ForkJoinWorkerThreadFactory factory,
2690                          UncaughtExceptionHandler handler,
2691                          int mode,
2692                          String workerNamePrefix) {
2693         this.workerNamePrefix = workerNamePrefix;
2694         this.factory = factory;
2695         this.ueh = handler;
2696         this.config = (parallelism & SMASK) | mode;
2697         long np = (long)(-parallelism); // offset ctl counts
2698         this.ctl = ((np << AC_SHIFT) & AC_MASK) | ((np << TC_SHIFT) & TC_MASK);
2699     }
2700 
2701     /**
2702      * Returns the common pool instance. This pool is statically
2703      * constructed; its run state is unaffected by attempts to {@link
2704      * #shutdown} or {@link #shutdownNow}. However this pool and any
2705      * ongoing processing are automatically terminated upon program
2706      * {@link System#exit}.  Any program that relies on asynchronous
2707      * task processing to complete before program termination should
2708      * invoke {@code commonPool().}{@link #awaitQuiescence awaitQuiescence},
2709      * before exit.
2710      *
2711      * @return the common pool instance
2712      * @since 1.8
2713      */
2714     public static ForkJoinPool commonPool() {
2715         // assert common != null : "static init error";
2716         return common;
2717     }
2718 
2719     // Execution methods
2720 
2721     /**
2722      * Performs the given task, returning its result upon completion.
2723      * If the computation encounters an unchecked Exception or Error,
2724      * it is rethrown as the outcome of this invocation.  Rethrown
2725      * exceptions behave in the same way as regular exceptions, but,
2726      * when possible, contain stack traces (as displayed for example
2727      * using {@code ex.printStackTrace()}) of both the current thread
2728      * as well as the thread actually encountering the exception;
2729      * minimally only the latter.
2730      *
2731      * @param task the task
2732      * @param <T> the type of the task's result
2733      * @return the task's result
2734      * @throws NullPointerException if the task is null
2735      * @throws RejectedExecutionException if the task cannot be
2736      *         scheduled for execution
2737      */
2738     public <T> T invoke(ForkJoinTask<T> task) {
2739         if (task == null)
2740             throw new NullPointerException();
2741         externalSubmit(task);
2742         return task.join();
2743     }
2744 
2745     /**
2746      * Arranges for (asynchronous) execution of the given task.
2747      *
2748      * @param task the task
2749      * @throws NullPointerException if the task is null
2750      * @throws RejectedExecutionException if the task cannot be
2751      *         scheduled for execution
2752      */
2753     public void execute(ForkJoinTask<?> task) {
2754         externalSubmit(task);
2755     }
2756 
2757     // AbstractExecutorService methods
2758 
2759     /**
2760      * @throws NullPointerException if the task is null
2761      * @throws RejectedExecutionException if the task cannot be
2762      *         scheduled for execution
2763      */
2764     public void execute(Runnable task) {
2765         if (task == null)
2766             throw new NullPointerException();
2767         ForkJoinTask<?> job;
2768         if (task instanceof ForkJoinTask<?>) // avoid re-wrap
2769             job = (ForkJoinTask<?>) task;
2770         else
2771             job = new ForkJoinTask.RunnableExecuteAction(task);
2772         externalSubmit(job);
2773     }
2774 
2775     /**
2776      * Submits a ForkJoinTask for execution.
2777      *
2778      * @param task the task to submit
2779      * @param <T> the type of the task's result
2780      * @return the task
2781      * @throws NullPointerException if the task is null
2782      * @throws RejectedExecutionException if the task cannot be
2783      *         scheduled for execution
2784      */
2785     public <T> ForkJoinTask<T> submit(ForkJoinTask<T> task) {
2786         return externalSubmit(task);
2787     }
2788 
2789     /**
2790      * @throws NullPointerException if the task is null
2791      * @throws RejectedExecutionException if the task cannot be
2792      *         scheduled for execution
2793      */
2794     public <T> ForkJoinTask<T> submit(Callable<T> task) {
2795         return externalSubmit(new ForkJoinTask.AdaptedCallable<T>(task));
2796     }
2797 
2798     /**
2799      * @throws NullPointerException if the task is null
2800      * @throws RejectedExecutionException if the task cannot be
2801      *         scheduled for execution
2802      */
2803     public <T> ForkJoinTask<T> submit(Runnable task, T result) {
2804         return externalSubmit(new ForkJoinTask.AdaptedRunnable<T>(task, result));
2805     }
2806 
2807     /**
2808      * @throws NullPointerException if the task is null
2809      * @throws RejectedExecutionException if the task cannot be
2810      *         scheduled for execution
2811      */
2812     public ForkJoinTask<?> submit(Runnable task) {
2813         if (task == null)
2814             throw new NullPointerException();
2815         ForkJoinTask<?> job;
2816         if (task instanceof ForkJoinTask<?>) // avoid re-wrap
2817             job = (ForkJoinTask<?>) task;
2818         else
2819             job = new ForkJoinTask.AdaptedRunnableAction(task);
2820         return externalSubmit(job);
2821     }
2822 
2823     /**
2824      * @throws NullPointerException       {@inheritDoc}
2825      * @throws RejectedExecutionException {@inheritDoc}
2826      */
2827     public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) {
2828         // In previous versions of this class, this method constructed
2829         // a task to run ForkJoinTask.invokeAll, but now external
2830         // invocation of multiple tasks is at least as efficient.
2831         ArrayList<Future<T>> futures = new ArrayList<>(tasks.size());
2832 
2833         try {
2834             for (Callable<T> t : tasks) {
2835                 ForkJoinTask<T> f = new ForkJoinTask.AdaptedCallable<T>(t);
2836                 futures.add(f);
2837                 externalSubmit(f);
2838             }
2839             for (int i = 0, size = futures.size(); i < size; i++)
2840                 ((ForkJoinTask<?>)futures.get(i)).quietlyJoin();
2841             return futures;
2842         } catch (Throwable t) {
2843             for (int i = 0, size = futures.size(); i < size; i++)
2844                 futures.get(i).cancel(false);
2845             throw t;
2846         }
2847     }
2848 
2849     /**
2850      * Returns the factory used for constructing new workers.
2851      *
2852      * @return the factory used for constructing new workers
2853      */
2854     public ForkJoinWorkerThreadFactory getFactory() {
2855         return factory;
2856     }
2857 
2858     /**
2859      * Returns the handler for internal worker threads that terminate
2860      * due to unrecoverable errors encountered while executing tasks.
2861      *
2862      * @return the handler, or {@code null} if none
2863      */
2864     public UncaughtExceptionHandler getUncaughtExceptionHandler() {
2865         return ueh;
2866     }
2867 
2868     /**
2869      * Returns the targeted parallelism level of this pool.
2870      *
2871      * @return the targeted parallelism level of this pool
2872      */
2873     public int getParallelism() {
2874         int par;
2875         return ((par = config & SMASK) > 0) ? par : 1;
2876     }
2877 
2878     /**
2879      * Returns the targeted parallelism level of the common pool.
2880      *
2881      * @return the targeted parallelism level of the common pool
2882      * @since 1.8
2883      */
2884     public static int getCommonPoolParallelism() {
2885         return COMMON_PARALLELISM;
2886     }
2887 
2888     /**
2889      * Returns the number of worker threads that have started but not
2890      * yet terminated.  The result returned by this method may differ
2891      * from {@link #getParallelism} when threads are created to
2892      * maintain parallelism when others are cooperatively blocked.
2893      *
2894      * @return the number of worker threads
2895      */
2896     public int getPoolSize() {
2897         return (config & SMASK) + (short)(ctl >>> TC_SHIFT);
2898     }
2899 
2900     /**
2901      * Returns {@code true} if this pool uses local first-in-first-out
2902      * scheduling mode for forked tasks that are never joined.
2903      *
2904      * @return {@code true} if this pool uses async mode
2905      */
2906     public boolean getAsyncMode() {
2907         return (config & FIFO_QUEUE) != 0;
2908     }
2909 
2910     /**
2911      * Returns an estimate of the number of worker threads that are
2912      * not blocked waiting to join tasks or for other managed
2913      * synchronization. This method may overestimate the
2914      * number of running threads.
2915      *
2916      * @return the number of worker threads
2917      */
2918     public int getRunningThreadCount() {
2919         int rc = 0;
2920         WorkQueue[] ws; WorkQueue w;
2921         if ((ws = workQueues) != null) {
2922             for (int i = 1; i < ws.length; i += 2) {
2923                 if ((w = ws[i]) != null && w.isApparentlyUnblocked())
2924                     ++rc;
2925             }
2926         }
2927         return rc;
2928     }
2929 
2930     /**
2931      * Returns an estimate of the number of threads that are currently
2932      * stealing or executing tasks. This method may overestimate the
2933      * number of active threads.
2934      *
2935      * @return the number of active threads
2936      */
2937     public int getActiveThreadCount() {
2938         int r = (config & SMASK) + (int)(ctl >> AC_SHIFT);
2939         return (r <= 0) ? 0 : r; // suppress momentarily negative values
2940     }
2941 
2942     /**
2943      * Returns {@code true} if all worker threads are currently idle.
2944      * An idle worker is one that cannot obtain a task to execute
2945      * because none are available to steal from other threads, and
2946      * there are no pending submissions to the pool. This method is
2947      * conservative; it might not return {@code true} immediately upon
2948      * idleness of all threads, but will eventually become true if
2949      * threads remain inactive.
2950      *
2951      * @return {@code true} if all threads are currently idle
2952      */
2953     public boolean isQuiescent() {
2954         return (config & SMASK) + (int)(ctl >> AC_SHIFT) <= 0;
2955     }
2956 
2957     /**
2958      * Returns an estimate of the total number of tasks stolen from
2959      * one thread's work queue by another. The reported value
2960      * underestimates the actual total number of steals when the pool
2961      * is not quiescent. This value may be useful for monitoring and
2962      * tuning fork/join programs: in general, steal counts should be
2963      * high enough to keep threads busy, but low enough to avoid
2964      * overhead and contention across threads.
2965      *
2966      * @return the number of steals
2967      */
2968     public long getStealCount() {
2969         AuxState sc = auxState;
2970         long count = (sc == null) ? 0L : sc.stealCount;
2971         WorkQueue[] ws; WorkQueue w;
2972         if ((ws = workQueues) != null) {
2973             for (int i = 1; i < ws.length; i += 2) {
2974                 if ((w = ws[i]) != null)
2975                     count += w.nsteals;
2976             }
2977         }
2978         return count;
2979     }
2980 
2981     /**
2982      * Returns an estimate of the total number of tasks currently held
2983      * in queues by worker threads (but not including tasks submitted
2984      * to the pool that have not begun executing). This value is only
2985      * an approximation, obtained by iterating across all threads in
2986      * the pool. This method may be useful for tuning task
2987      * granularities.
2988      *
2989      * @return the number of queued tasks
2990      */
2991     public long getQueuedTaskCount() {
2992         long count = 0;
2993         WorkQueue[] ws; WorkQueue w;
2994         if ((ws = workQueues) != null) {
2995             for (int i = 1; i < ws.length; i += 2) {
2996                 if ((w = ws[i]) != null)
2997                     count += w.queueSize();
2998             }
2999         }
3000         return count;
3001     }
3002 
3003     /**
3004      * Returns an estimate of the number of tasks submitted to this
3005      * pool that have not yet begun executing.  This method may take
3006      * time proportional to the number of submissions.
3007      *
3008      * @return the number of queued submissions
3009      */
3010     public int getQueuedSubmissionCount() {
3011         int count = 0;
3012         WorkQueue[] ws; WorkQueue w;
3013         if ((ws = workQueues) != null) {
3014             for (int i = 0; i < ws.length; i += 2) {
3015                 if ((w = ws[i]) != null)
3016                     count += w.queueSize();
3017             }
3018         }
3019         return count;
3020     }
3021 
3022     /**
3023      * Returns {@code true} if there are any tasks submitted to this
3024      * pool that have not yet begun executing.
3025      *
3026      * @return {@code true} if there are any queued submissions
3027      */
3028     public boolean hasQueuedSubmissions() {
3029         WorkQueue[] ws; WorkQueue w;
3030         if ((ws = workQueues) != null) {
3031             for (int i = 0; i < ws.length; i += 2) {
3032                 if ((w = ws[i]) != null && !w.isEmpty())
3033                     return true;
3034             }
3035         }
3036         return false;
3037     }
3038 
3039     /**
3040      * Removes and returns the next unexecuted submission if one is
3041      * available.  This method may be useful in extensions to this
3042      * class that re-assign work in systems with multiple pools.
3043      *
3044      * @return the next submission, or {@code null} if none
3045      */
3046     protected ForkJoinTask<?> pollSubmission() {
3047         WorkQueue[] ws; int wl; WorkQueue w; ForkJoinTask<?> t;
3048         int r = ThreadLocalRandom.nextSecondarySeed();
3049         if ((ws = workQueues) != null && (wl = ws.length) > 0) {
3050             for (int m = wl - 1, i = 0; i < wl; ++i) {
3051                 if ((w = ws[(i << 1) & m]) != null && (t = w.poll()) != null)
3052                     return t;
3053             }
3054         }
3055         return null;
3056     }
3057 
3058     /**
3059      * Removes all available unexecuted submitted and forked tasks
3060      * from scheduling queues and adds them to the given collection,
3061      * without altering their execution status. These may include
3062      * artificially generated or wrapped tasks. This method is
3063      * designed to be invoked only when the pool is known to be
3064      * quiescent. Invocations at other times may not remove all
3065      * tasks. A failure encountered while attempting to add elements
3066      * to collection {@code c} may result in elements being in
3067      * neither, either or both collections when the associated
3068      * exception is thrown.  The behavior of this operation is
3069      * undefined if the specified collection is modified while the
3070      * operation is in progress.
3071      *
3072      * @param c the collection to transfer elements into
3073      * @return the number of elements transferred
3074      */
3075     protected int drainTasksTo(Collection<? super ForkJoinTask<?>> c) {
3076         int count = 0;
3077         WorkQueue[] ws; WorkQueue w; ForkJoinTask<?> t;
3078         if ((ws = workQueues) != null) {
3079             for (int i = 0; i < ws.length; ++i) {
3080                 if ((w = ws[i]) != null) {
3081                     while ((t = w.poll()) != null) {
3082                         c.add(t);
3083                         ++count;
3084                     }
3085                 }
3086             }
3087         }
3088         return count;
3089     }
3090 
3091     /**
3092      * Returns a string identifying this pool, as well as its state,
3093      * including indications of run state, parallelism level, and
3094      * worker and task counts.
3095      *
3096      * @return a string identifying this pool, as well as its state
3097      */
3098     public String toString() {
3099         // Use a single pass through workQueues to collect counts
3100         long qt = 0L, qs = 0L; int rc = 0;
3101         AuxState sc = auxState;
3102         long st = (sc == null) ? 0L : sc.stealCount;
3103         long c = ctl;
3104         WorkQueue[] ws; WorkQueue w;
3105         if ((ws = workQueues) != null) {
3106             for (int i = 0; i < ws.length; ++i) {
3107                 if ((w = ws[i]) != null) {
3108                     int size = w.queueSize();
3109                     if ((i & 1) == 0)
3110                         qs += size;
3111                     else {
3112                         qt += size;
3113                         st += w.nsteals;
3114                         if (w.isApparentlyUnblocked())
3115                             ++rc;
3116                     }
3117                 }
3118             }
3119         }
3120         int pc = (config & SMASK);
3121         int tc = pc + (short)(c >>> TC_SHIFT);
3122         int ac = pc + (int)(c >> AC_SHIFT);
3123         if (ac < 0) // ignore transient negative
3124             ac = 0;
3125         int rs = runState;
3126         String level = ((rs & TERMINATED) != 0 ? "Terminated" :
3127                         (rs & STOP)       != 0 ? "Terminating" :
3128                         (rs & SHUTDOWN)   != 0 ? "Shutting down" :
3129                         "Running");
3130         return super.toString() +
3131             "[" + level +
3132             ", parallelism = " + pc +
3133             ", size = " + tc +
3134             ", active = " + ac +
3135             ", running = " + rc +
3136             ", steals = " + st +
3137             ", tasks = " + qt +
3138             ", submissions = " + qs +
3139             "]";
3140     }
3141 
3142     /**
3143      * Possibly initiates an orderly shutdown in which previously
3144      * submitted tasks are executed, but no new tasks will be
3145      * accepted. Invocation has no effect on execution state if this
3146      * is the {@link #commonPool()}, and no additional effect if
3147      * already shut down.  Tasks that are in the process of being
3148      * submitted concurrently during the course of this method may or
3149      * may not be rejected.
3150      *
3151      * @throws SecurityException if a security manager exists and
3152      *         the caller is not permitted to modify threads
3153      *         because it does not hold {@link
3154      *         java.lang.RuntimePermission}{@code ("modifyThread")}
3155      */
3156     public void shutdown() {
3157         checkPermission();
3158         tryTerminate(false, true);
3159     }
3160 
3161     /**
3162      * Possibly attempts to cancel and/or stop all tasks, and reject
3163      * all subsequently submitted tasks.  Invocation has no effect on
3164      * execution state if this is the {@link #commonPool()}, and no
3165      * additional effect if already shut down. Otherwise, tasks that
3166      * are in the process of being submitted or executed concurrently
3167      * during the course of this method may or may not be
3168      * rejected. This method cancels both existing and unexecuted
3169      * tasks, in order to permit termination in the presence of task
3170      * dependencies. So the method always returns an empty list
3171      * (unlike the case for some other Executors).
3172      *
3173      * @return an empty list
3174      * @throws SecurityException if a security manager exists and
3175      *         the caller is not permitted to modify threads
3176      *         because it does not hold {@link
3177      *         java.lang.RuntimePermission}{@code ("modifyThread")}
3178      */
3179     public List<Runnable> shutdownNow() {
3180         checkPermission();
3181         tryTerminate(true, true);
3182         return Collections.emptyList();
3183     }
3184 
3185     /**
3186      * Returns {@code true} if all tasks have completed following shut down.
3187      *
3188      * @return {@code true} if all tasks have completed following shut down
3189      */
3190     public boolean isTerminated() {
3191         return (runState & TERMINATED) != 0;
3192     }
3193 
3194     /**
3195      * Returns {@code true} if the process of termination has
3196      * commenced but not yet completed.  This method may be useful for
3197      * debugging. A return of {@code true} reported a sufficient
3198      * period after shutdown may indicate that submitted tasks have
3199      * ignored or suppressed interruption, or are waiting for I/O,
3200      * causing this executor not to properly terminate. (See the
3201      * advisory notes for class {@link ForkJoinTask} stating that
3202      * tasks should not normally entail blocking operations.  But if
3203      * they do, they must abort them on interrupt.)
3204      *
3205      * @return {@code true} if terminating but not yet terminated
3206      */
3207     public boolean isTerminating() {
3208         int rs = runState;
3209         return (rs & STOP) != 0 && (rs & TERMINATED) == 0;
3210     }
3211 
3212     /**
3213      * Returns {@code true} if this pool has been shut down.
3214      *
3215      * @return {@code true} if this pool has been shut down
3216      */
3217     public boolean isShutdown() {
3218         return (runState & SHUTDOWN) != 0;
3219     }
3220 
3221     /**
3222      * Blocks until all tasks have completed execution after a
3223      * shutdown request, or the timeout occurs, or the current thread
3224      * is interrupted, whichever happens first. Because the {@link
3225      * #commonPool()} never terminates until program shutdown, when
3226      * applied to the common pool, this method is equivalent to {@link
3227      * #awaitQuiescence(long, TimeUnit)} but always returns {@code false}.
3228      *
3229      * @param timeout the maximum time to wait
3230      * @param unit the time unit of the timeout argument
3231      * @return {@code true} if this executor terminated and
3232      *         {@code false} if the timeout elapsed before termination
3233      * @throws InterruptedException if interrupted while waiting
3234      */
3235     public boolean awaitTermination(long timeout, TimeUnit unit)
3236         throws InterruptedException {
3237         if (Thread.interrupted())
3238             throw new InterruptedException();
3239         if (this == common) {
3240             awaitQuiescence(timeout, unit);
3241             return false;
3242         }
3243         long nanos = unit.toNanos(timeout);
3244         if (isTerminated())
3245             return true;
3246         if (nanos <= 0L)
3247             return false;
3248         long deadline = System.nanoTime() + nanos;
3249         synchronized (this) {
3250             for (;;) {
3251                 if (isTerminated())
3252                     return true;
3253                 if (nanos <= 0L)
3254                     return false;
3255                 long millis = TimeUnit.NANOSECONDS.toMillis(nanos);
3256                 wait(millis > 0L ? millis : 1L);
3257                 nanos = deadline - System.nanoTime();
3258             }
3259         }
3260     }
3261 
3262     /**
3263      * If called by a ForkJoinTask operating in this pool, equivalent
3264      * in effect to {@link ForkJoinTask#helpQuiesce}. Otherwise,
3265      * waits and/or attempts to assist performing tasks until this
3266      * pool {@link #isQuiescent} or the indicated timeout elapses.
3267      *
3268      * @param timeout the maximum time to wait
3269      * @param unit the time unit of the timeout argument
3270      * @return {@code true} if quiescent; {@code false} if the
3271      * timeout elapsed.
3272      */
3273     public boolean awaitQuiescence(long timeout, TimeUnit unit) {
3274         long nanos = unit.toNanos(timeout);
3275         ForkJoinWorkerThread wt;
3276         Thread thread = Thread.currentThread();
3277         if ((thread instanceof ForkJoinWorkerThread) &&
3278             (wt = (ForkJoinWorkerThread)thread).pool == this) {
3279             helpQuiescePool(wt.workQueue);
3280             return true;
3281         }
3282         long startTime = System.nanoTime();
3283         WorkQueue[] ws;
3284         int r = 0, wl;
3285         boolean found = true;
3286         while (!isQuiescent() && (ws = workQueues) != null &&
3287                (wl = ws.length) > 0) {
3288             if (!found) {
3289                 if ((System.nanoTime() - startTime) > nanos)
3290                     return false;
3291                 Thread.yield(); // cannot block
3292             }
3293             found = false;
3294             for (int m = wl - 1, j = (m + 1) << 2; j >= 0; --j) {
3295                 ForkJoinTask<?> t; WorkQueue q; int b, k;
3296                 if ((k = r++ & m) <= m && k >= 0 && (q = ws[k]) != null &&
3297                     (b = q.base) - q.top < 0) {
3298                     found = true;
3299                     if ((t = q.pollAt(b)) != null)
3300                         t.doExec();
3301                     break;
3302                 }
3303             }
3304         }
3305         return true;
3306     }
3307 
3308     /**
3309      * Waits and/or attempts to assist performing tasks indefinitely
3310      * until the {@link #commonPool()} {@link #isQuiescent}.
3311      */
3312     static void quiesceCommonPool() {
3313         common.awaitQuiescence(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
3314     }
3315 
3316     /**
3317      * Interface for extending managed parallelism for tasks running
3318      * in {@link ForkJoinPool}s.
3319      *
3320      * <p>A {@code ManagedBlocker} provides two methods.  Method
3321      * {@link #isReleasable} must return {@code true} if blocking is
3322      * not necessary. Method {@link #block} blocks the current thread
3323      * if necessary (perhaps internally invoking {@code isReleasable}
3324      * before actually blocking). These actions are performed by any
3325      * thread invoking {@link ForkJoinPool#managedBlock(ManagedBlocker)}.
3326      * The unusual methods in this API accommodate synchronizers that
3327      * may, but don't usually, block for long periods. Similarly, they
3328      * allow more efficient internal handling of cases in which
3329      * additional workers may be, but usually are not, needed to
3330      * ensure sufficient parallelism.  Toward this end,
3331      * implementations of method {@code isReleasable} must be amenable
3332      * to repeated invocation.
3333      *
3334      * <p>For example, here is a ManagedBlocker based on a
3335      * ReentrantLock:
3336      * <pre> {@code
3337      * class ManagedLocker implements ManagedBlocker {
3338      *   final ReentrantLock lock;
3339      *   boolean hasLock = false;
3340      *   ManagedLocker(ReentrantLock lock) { this.lock = lock; }
3341      *   public boolean block() {
3342      *     if (!hasLock)
3343      *       lock.lock();
3344      *     return true;
3345      *   }
3346      *   public boolean isReleasable() {
3347      *     return hasLock || (hasLock = lock.tryLock());
3348      *   }
3349      * }}</pre>
3350      *
3351      * <p>Here is a class that possibly blocks waiting for an
3352      * item on a given queue:
3353      * <pre> {@code
3354      * class QueueTaker<E> implements ManagedBlocker {
3355      *   final BlockingQueue<E> queue;
3356      *   volatile E item = null;
3357      *   QueueTaker(BlockingQueue<E> q) { this.queue = q; }
3358      *   public boolean block() throws InterruptedException {
3359      *     if (item == null)
3360      *       item = queue.take();
3361      *     return true;
3362      *   }
3363      *   public boolean isReleasable() {
3364      *     return item != null || (item = queue.poll()) != null;
3365      *   }
3366      *   public E getItem() { // call after pool.managedBlock completes
3367      *     return item;
3368      *   }
3369      * }}</pre>
3370      */
3371     public static interface ManagedBlocker {
3372         /**
3373          * Possibly blocks the current thread, for example waiting for
3374          * a lock or condition.
3375          *
3376          * @return {@code true} if no additional blocking is necessary
3377          * (i.e., if isReleasable would return true)
3378          * @throws InterruptedException if interrupted while waiting
3379          * (the method is not required to do so, but is allowed to)
3380          */
3381         boolean block() throws InterruptedException;
3382 
3383         /**
3384          * Returns {@code true} if blocking is unnecessary.
3385          * @return {@code true} if blocking is unnecessary
3386          */
3387         boolean isReleasable();
3388     }
3389 
3390     /**
3391      * Runs the given possibly blocking task.  When {@linkplain
3392      * ForkJoinTask#inForkJoinPool() running in a ForkJoinPool}, this
3393      * method possibly arranges for a spare thread to be activated if
3394      * necessary to ensure sufficient parallelism while the current
3395      * thread is blocked in {@link ManagedBlocker#block blocker.block()}.
3396      *
3397      * <p>This method repeatedly calls {@code blocker.isReleasable()} and
3398      * {@code blocker.block()} until either method returns {@code true}.
3399      * Every call to {@code blocker.block()} is preceded by a call to
3400      * {@code blocker.isReleasable()} that returned {@code false}.
3401      *
3402      * <p>If not running in a ForkJoinPool, this method is
3403      * behaviorally equivalent to
3404      * <pre> {@code
3405      * while (!blocker.isReleasable())
3406      *   if (blocker.block())
3407      *     break;}</pre>
3408      *
3409      * If running in a ForkJoinPool, the pool may first be expanded to
3410      * ensure sufficient parallelism available during the call to
3411      * {@code blocker.block()}.
3412      *
3413      * @param blocker the blocker task
3414      * @throws InterruptedException if {@code blocker.block()} did so
3415      */
3416     public static void managedBlock(ManagedBlocker blocker)
3417         throws InterruptedException {
3418         ForkJoinPool p;
3419         ForkJoinWorkerThread wt;
3420         Thread t = Thread.currentThread();
3421         if ((t instanceof ForkJoinWorkerThread) &&
3422             (p = (wt = (ForkJoinWorkerThread)t).pool) != null) {
3423             WorkQueue w = wt.workQueue;
3424             while (!blocker.isReleasable()) {
3425                 if (p.tryCompensate(w)) {
3426                     try {
3427                         do {} while (!blocker.isReleasable() &&
3428                                      !blocker.block());
3429                     } finally {
3430                         U.getAndAddLong(p, CTL, AC_UNIT);
3431                     }
3432                     break;
3433                 }
3434             }
3435         }
3436         else {
3437             do {} while (!blocker.isReleasable() &&
3438                          !blocker.block());
3439         }
3440     }
3441 
3442     // AbstractExecutorService overrides.  These rely on undocumented
3443     // fact that ForkJoinTask.adapt returns ForkJoinTasks that also
3444     // implement RunnableFuture.
3445 
3446     protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
3447         return new ForkJoinTask.AdaptedRunnable<T>(runnable, value);
3448     }
3449 
3450     protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
3451         return new ForkJoinTask.AdaptedCallable<T>(callable);
3452     }
3453 
3454     // Unsafe mechanics
3455     private static final sun.misc.Unsafe U = sun.misc.Unsafe.getUnsafe();
3456     private static final long CTL;
3457     private static final long RUNSTATE;
3458     private static final int ABASE;
3459     private static final int ASHIFT;
3460 
3461     static {
3462         try {
3463             CTL = U.objectFieldOffset
3464                 (ForkJoinPool.class.getDeclaredField("ctl"));
3465             RUNSTATE = U.objectFieldOffset
3466                 (ForkJoinPool.class.getDeclaredField("runState"));
3467             ABASE = U.arrayBaseOffset(ForkJoinTask[].class);
3468             int scale = U.arrayIndexScale(ForkJoinTask[].class);
3469             if ((scale & (scale - 1)) != 0)
3470                 throw new Error("array index scale not a power of two");
3471             ASHIFT = 31 - Integer.numberOfLeadingZeros(scale);
3472         } catch (ReflectiveOperationException e) {
3473             throw new Error(e);
3474         }
3475 
3476         // Reduce the risk of rare disastrous classloading in first call to
3477         // LockSupport.park: https://bugs.openjdk.java.net/browse/JDK-8074773
3478         Class<?> ensureLoaded = LockSupport.class;
3479 
3480         int commonMaxSpares = DEFAULT_COMMON_MAX_SPARES;
3481         try {
3482             String p = System.getProperty
3483                 ("java.util.concurrent.ForkJoinPool.common.maximumSpares");
3484             if (p != null)
3485                 commonMaxSpares = Integer.parseInt(p);
3486         } catch (Exception ignore) {}
3487         COMMON_MAX_SPARES = commonMaxSpares;
3488 
3489         defaultForkJoinWorkerThreadFactory =
3490             new DefaultForkJoinWorkerThreadFactory();
3491         modifyThreadPermission = new RuntimePermission("modifyThread");
3492 
3493         common = java.security.AccessController.doPrivileged
3494             (new java.security.PrivilegedAction<ForkJoinPool>() {
3495                 public ForkJoinPool run() { return makeCommonPool(); }});
3496 
3497         // report 1 even if threads disabled
3498         COMMON_PARALLELISM = Math.max(common.config & SMASK, 1);
3499     }
3500 
3501     /**
3502      * Creates and returns the common pool, respecting user settings
3503      * specified via system properties.
3504      */
3505     static ForkJoinPool makeCommonPool() {
3506         int parallelism = -1;
3507         ForkJoinWorkerThreadFactory factory = null;
3508         UncaughtExceptionHandler handler = null;
3509         try {  // ignore exceptions in accessing/parsing properties
3510             String pp = System.getProperty
3511                 ("java.util.concurrent.ForkJoinPool.common.parallelism");
3512             String fp = System.getProperty
3513                 ("java.util.concurrent.ForkJoinPool.common.threadFactory");
3514             String hp = System.getProperty
3515                 ("java.util.concurrent.ForkJoinPool.common.exceptionHandler");
3516             if (pp != null)
3517                 parallelism = Integer.parseInt(pp);
3518             if (fp != null)
3519                 factory = ((ForkJoinWorkerThreadFactory)ClassLoader.
3520                            getSystemClassLoader().loadClass(fp).newInstance());
3521             if (hp != null)
3522                 handler = ((UncaughtExceptionHandler)ClassLoader.
3523                            getSystemClassLoader().loadClass(hp).newInstance());
3524         } catch (Exception ignore) {
3525         }
3526         if (factory == null) {
3527             if (System.getSecurityManager() == null)
3528                 factory = defaultForkJoinWorkerThreadFactory;
3529             else // use security-managed default
3530                 factory = new InnocuousForkJoinWorkerThreadFactory();
3531         }
3532         if (parallelism < 0 && // default 1 less than #cores
3533             (parallelism = Runtime.getRuntime().availableProcessors() - 1) <= 0)
3534             parallelism = 1;
3535         if (parallelism > MAX_CAP)
3536             parallelism = MAX_CAP;
3537         return new ForkJoinPool(parallelism, factory, handler, LIFO_QUEUE,
3538                                 "ForkJoinPool.commonPool-worker-");
3539     }
3540 
3541     /**
3542      * Factory for innocuous worker threads.
3543      */
3544     private static final class InnocuousForkJoinWorkerThreadFactory
3545         implements ForkJoinWorkerThreadFactory {
3546 
3547         /**
3548          * An ACC to restrict permissions for the factory itself.
3549          * The constructed workers have no permissions set.
3550          */
3551         private static final AccessControlContext innocuousAcc;
3552         static {
3553             Permissions innocuousPerms = new Permissions();
3554             innocuousPerms.add(modifyThreadPermission);
3555             innocuousPerms.add(new RuntimePermission(
3556                                    "enableContextClassLoaderOverride"));
3557             innocuousPerms.add(new RuntimePermission(
3558                                    "modifyThreadGroup"));
3559             innocuousAcc = new AccessControlContext(new ProtectionDomain[] {
3560                     new ProtectionDomain(null, innocuousPerms)
3561                 });
3562         }
3563 
3564         public final ForkJoinWorkerThread newThread(ForkJoinPool pool) {
3565             return java.security.AccessController.doPrivileged(
3566                 new java.security.PrivilegedAction<ForkJoinWorkerThread>() {
3567                     public ForkJoinWorkerThread run() {
3568                         return new ForkJoinWorkerThread.
3569                             InnocuousForkJoinWorkerThread(pool);
3570                     }}, innocuousAcc);
3571         }
3572     }
3573 
3574 }