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.lang.reflect.Field;
  40 import java.util.ArrayList;
  41 import java.util.Collection;
  42 import java.util.Collections;
  43 import java.util.List;
  44 import java.util.Objects;
  45 import java.util.function.Consumer;
  46 import java.util.function.Predicate;
  47 import java.util.concurrent.CountDownLatch;
  48 import java.util.concurrent.locks.LockSupport;
  49 import jdk.internal.access.JavaLangAccess;
  50 import jdk.internal.access.JavaUtilConcurrentFJPAccess;
  51 import jdk.internal.access.SharedSecrets;
  52 import jdk.internal.misc.Unsafe;
  53 import jdk.internal.vm.SharedThreadContainer;
  54 import static java.util.concurrent.DelayScheduler.ScheduledForkJoinTask;
  55 
  56 /**
  57  * An {@link ExecutorService} for running {@link ForkJoinTask}s.
  58  * A {@code ForkJoinPool} provides the entry point for submissions
  59  * from non-{@code ForkJoinTask} clients, as well as management and
  60  * monitoring operations.
  61  *
  62  * <p>A {@code ForkJoinPool} differs from other kinds of {@link
  63  * ExecutorService} mainly by virtue of employing
  64  * <em>work-stealing</em>: all threads in the pool attempt to find and
  65  * execute tasks submitted to the pool and/or created by other active
  66  * tasks (eventually blocking waiting for work if none exist). This
  67  * enables efficient processing when most tasks spawn other subtasks
  68  * (as do most {@code ForkJoinTask}s), as well as when many small
  69  * tasks are submitted to the pool from external clients.  Especially
  70  * when setting <em>asyncMode</em> to true in constructors, {@code
  71  * ForkJoinPool}s may also be appropriate for use with event-style
  72  * tasks that are never joined. All worker threads are initialized
  73  * with {@link Thread#isDaemon} set {@code true}.
  74  *
  75  * <p>A static {@link #commonPool()} is available and appropriate for
  76  * most applications. The common pool is used by any ForkJoinTask that
  77  * is not explicitly submitted to a specified pool. Using the common
  78  * pool normally reduces resource usage (its threads are slowly
  79  * reclaimed during periods of non-use, and reinstated upon subsequent
  80  * use).
  81  *
  82  * <p>For applications that require separate or custom pools, a {@code
  83  * ForkJoinPool} may be constructed with a given target parallelism
  84  * level; by default, equal to the number of available processors.
  85  * The pool attempts to maintain enough active (or available) threads
  86  * by dynamically adding, suspending, or resuming internal worker
  87  * threads, even if some tasks are stalled waiting to join others.
  88  * However, no such adjustments are guaranteed in the face of blocked
  89  * I/O or other unmanaged synchronization. The nested {@link
  90  * ManagedBlocker} interface enables extension of the kinds of
  91  * synchronization accommodated. The default policies may be
  92  * overridden using a constructor with parameters corresponding to
  93  * those documented in class {@link ThreadPoolExecutor}.
  94  *
  95  * <p>In addition to execution and lifecycle control methods, this
  96  * class provides status check methods (for example
  97  * {@link #getStealCount}) that are intended to aid in developing,
  98  * tuning, and monitoring fork/join applications. Also, method
  99  * {@link #toString} returns indications of pool state in a
 100  * convenient form for informal monitoring.
 101  *
 102  * <p>As is the case with other ExecutorServices, there are three
 103  * main task execution methods summarized in the following table.
 104  * These are designed to be used primarily by clients not already
 105  * engaged in fork/join computations in the current pool.  The main
 106  * forms of these methods accept instances of {@code ForkJoinTask},
 107  * but overloaded forms also allow mixed execution of plain {@code
 108  * Runnable}- or {@code Callable}- based activities as well.  However,
 109  * tasks that are already executing in a pool should normally instead
 110  * use the within-computation forms listed in the table unless using
 111  * async event-style tasks that are not usually joined, in which case
 112  * there is little difference among choice of methods.
 113  *
 114  * <table class="plain">
 115  * <caption>Summary of task execution methods</caption>
 116  *  <tr>
 117  *    <td></td>
 118  *    <th scope="col"> Call from non-fork/join clients</th>
 119  *    <th scope="col"> Call from within fork/join computations</th>
 120  *  </tr>
 121  *  <tr>
 122  *    <th scope="row" style="text-align:left"> Arrange async execution</th>
 123  *    <td> {@link #execute(ForkJoinTask)}</td>
 124  *    <td> {@link ForkJoinTask#fork}</td>
 125  *  </tr>
 126  *  <tr>
 127  *    <th scope="row" style="text-align:left"> Await and obtain result</th>
 128  *    <td> {@link #invoke(ForkJoinTask)}</td>
 129  *    <td> {@link ForkJoinTask#invoke}</td>
 130  *  </tr>
 131  *  <tr>
 132  *    <th scope="row" style="text-align:left"> Arrange exec and obtain Future</th>
 133  *    <td> {@link #submit(ForkJoinTask)}</td>
 134  *    <td> {@link ForkJoinTask#fork} (ForkJoinTasks <em>are</em> Futures)</td>
 135  *  </tr>
 136  * </table>
 137  *
 138  * <p>Additionally, this class supports {@link
 139  * ScheduledExecutorService} methods to delay or periodically execute
 140  * tasks, as well as method {@link #submitWithTimeout} to cancel tasks
 141  * that take too long. The scheduled functions or actions may create
 142  * and invoke other {@linkplain ForkJoinTask ForkJoinTasks}. Delayed
 143  * actions become enabled for execution and behave as ordinary submitted
 144  * tasks when their delays elapse.  Scheduling methods return
 145  * {@linkplain ForkJoinTask ForkJoinTasks} that implement the {@link
 146  * ScheduledFuture} interface. Resource exhaustion encountered after
 147  * initial submission results in task cancellation. When time-based
 148  * methods are used, shutdown policies match the default policies of
 149  * class {@link ScheduledThreadPoolExecutor}: upon {@link #shutdown},
 150  * existing periodic tasks will not re-execute, and the pool
 151  * terminates when quiescent and existing delayed tasks
 152  * complete. Method {@link #cancelDelayedTasksOnShutdown} may be used
 153  * to disable all delayed tasks upon shutdown, and method {@link
 154  * #shutdownNow} may be used to instead unconditionally initiate pool
 155  * termination. Monitoring methods such as {@link #getQueuedTaskCount}
 156  * do not include scheduled tasks that are not yet enabled for execution,
 157  * which are reported separately by method {@link
 158  * #getDelayedTaskCount}.
 159  *
 160  * <p>The parameters used to construct the common pool may be controlled by
 161  * setting the following {@linkplain System#getProperty system properties}:
 162  * <ul>
 163  * <li>{@systemProperty java.util.concurrent.ForkJoinPool.common.parallelism}
 164  * - the parallelism level, a non-negative integer. Usage is discouraged.
 165  *   Use {@link #setParallelism} instead.
 166  * <li>{@systemProperty java.util.concurrent.ForkJoinPool.common.threadFactory}
 167  * - the class name of a {@link ForkJoinWorkerThreadFactory}.
 168  * The {@linkplain ClassLoader#getSystemClassLoader() system class loader}
 169  * is used to load this class.
 170  * <li>{@systemProperty java.util.concurrent.ForkJoinPool.common.exceptionHandler}
 171  * - the class name of a {@link UncaughtExceptionHandler}.
 172  * The {@linkplain ClassLoader#getSystemClassLoader() system class loader}
 173  * is used to load this class.
 174  * <li>{@systemProperty java.util.concurrent.ForkJoinPool.common.maximumSpares}
 175  * - the maximum number of allowed extra threads to maintain target
 176  * parallelism (default 256).
 177  * </ul>
 178  * If no thread factory is supplied via a system property, then the
 179  * common pool uses a factory that uses the system class loader as the
 180  * {@linkplain Thread#getContextClassLoader() thread context class loader}.
 181  *
 182  * Upon any error in establishing these settings, default parameters
 183  * are used. It is possible to disable use of threads by using a
 184  * factory that may return {@code null}, in which case some tasks may
 185  * never execute. While possible, it is strongly discouraged to set
 186  * the parallelism property to zero, which may be internally
 187  * overridden in the presence of intrinsically async tasks.
 188  *
 189  * @implNote This implementation restricts the maximum number of
 190  * running threads to 32767. Attempts to create pools with greater
 191  * than the maximum number result in {@code
 192  * IllegalArgumentException}. Also, this implementation rejects
 193  * submitted tasks (that is, by throwing {@link
 194  * RejectedExecutionException}) only when the pool is shut down or
 195  * internal resources have been exhausted.
 196  *
 197  * @since 1.7
 198  * @author Doug Lea
 199  */
 200 public class ForkJoinPool extends AbstractExecutorService
 201     implements ScheduledExecutorService {
 202 
 203     /*
 204      * Implementation Overview
 205      *
 206      * This class and its nested classes provide the main
 207      * functionality and control for a set of worker threads.  Because
 208      * most internal methods and nested classes are interrelated,
 209      * their main rationale and descriptions are presented here;
 210      * individual methods and nested classes contain only brief
 211      * comments about details. Broadly: submissions from non-FJ
 212      * threads enter into submission queues.  Workers take these tasks
 213      * and typically split them into subtasks that may be stolen by
 214      * other workers. Work-stealing based on randomized scans
 215      * generally leads to better throughput than "work dealing" in
 216      * which producers assign tasks to idle threads, in part because
 217      * threads that have finished other tasks before the signalled
 218      * thread wakes up (which can be a long time) can take the task
 219      * instead.  Preference rules give first priority to processing
 220      * tasks from their own queues (LIFO or FIFO, depending on mode),
 221      * then to randomized FIFO steals of tasks in other queues.
 222      *
 223      * This framework began as vehicle for supporting structured
 224      * parallelism using work-stealing, designed to work best when
 225      * tasks are dag-structured (wrt completion dependencies), nested
 226      * (generated using recursion or completions), of reasonable
 227      * granularity, independent (wrt memory and resources) and where
 228      * callers participate in task execution. These are properties
 229      * that anyone aiming for efficient parallel multicore execution
 230      * should design for.  Over time, the scalability advantages of
 231      * this framework led to extensions to better support more diverse
 232      * usage contexts, amounting to weakenings or violations of each
 233      * of these properties. Accommodating them may compromise
 234      * performance, but mechanics discussed below include tradeoffs
 235      * attempting to arrange that no single performance issue dominates.
 236      *
 237      * Here's a brief history of major revisions, each also with other
 238      * minor features and changes.
 239      *
 240      * 1. Only handle recursively structured computational tasks
 241      * 2. Async (FIFO) mode and striped submission queues
 242      * 3. Completion-based tasks (mainly CountedCompleters)
 243      * 4. CommonPool and parallelStream support
 244      * 5. InterruptibleTasks for externally submitted tasks
 245      * 6. Support ScheduledExecutorService methods
 246      *
 247      * Most changes involve adaptions of base algorithms using
 248      * combinations of static and dynamic bitwise mode settings (both
 249      * here and in ForkJoinTask), and subclassing of ForkJoinTask.
 250      * There are a fair number of odd code constructions and design
 251      * decisions for components that reside at the edge of Java vs JVM
 252      * functionality.
 253      *
 254      * WorkQueues
 255      * ==========
 256      *
 257      * Most operations occur within work-stealing queues (in nested
 258      * class WorkQueue).  These are special forms of Deques that
 259      * support only three of the four possible end-operations -- push,
 260      * pop, and poll (aka steal), under the further constraints that
 261      * push and pop are called only from the owning thread (or, as
 262      * extended here, under a lock), while poll may be called from
 263      * other threads.  (If you are unfamiliar with them, you probably
 264      * want to read Herlihy and Shavit's book "The Art of
 265      * Multiprocessor programming", chapter 16 describing these in
 266      * more detail before proceeding.)  The main work-stealing queue
 267      * design is roughly similar to those in the papers "Dynamic
 268      * Circular Work-Stealing Deque" by Chase and Lev, SPAA 2005
 269      * (http://research.sun.com/scalable/pubs/index.html) and
 270      * "Idempotent work stealing" by Michael, Saraswat, and Vechev,
 271      * PPoPP 2009 (http://portal.acm.org/citation.cfm?id=1504186).
 272      * The main differences ultimately stem from GC requirements that
 273      * we null out taken slots as soon as we can, to maintain as small
 274      * a footprint as possible even in programs generating huge
 275      * numbers of tasks. To accomplish this, we shift the CAS
 276      * arbitrating pop vs poll (steal) from being on the indices
 277      * ("base" and "top") to the slots themselves. These provide the
 278      * primary required memory ordering -- see "Correct and Efficient
 279      * Work-Stealing for Weak Memory Models" by Le, Pop, Cohen, and
 280      * Nardelli, PPoPP 2013
 281      * (http://www.di.ens.fr/~zappa/readings/ppopp13.pdf) for an
 282      * analysis of memory ordering requirements in work-stealing
 283      * algorithms similar to the one used here.  We use per-operation
 284      * ordered writes of various kinds for accesses when required.
 285      *
 286      * We also support a user mode in which local task processing is
 287      * in FIFO, not LIFO order, simply by using a local version of
 288      * poll rather than pop.  This can be useful in message-passing
 289      * frameworks in which tasks are never joined, although with
 290      * increased contention among task producers and consumers. Also,
 291      * the same data structure (and class) is used for "submission
 292      * queues" (described below) holding externally submitted tasks,
 293      * that differ only in that a lock (using field "phase"; see below) is
 294      * required by external callers to push and pop tasks.
 295      *
 296      * Adding tasks then takes the form of a classic array push(task)
 297      * in a circular buffer:
 298      *    q.array[q.top++ % length] = task;
 299      *
 300      * The actual code needs to null-check and size-check the array,
 301      * uses masking, not mod, for indexing a power-of-two-sized array,
 302      * enforces memory ordering, supports resizing, and possibly
 303      * signals waiting workers to start scanning (described below),
 304      * which requires stronger forms of order accesses.
 305      *
 306      * The pop operation (always performed by owner) is of the form:
 307      *   if ((task = getAndSet(q.array, (q.top-1) % length, null)) != null)
 308      *        decrement top and return task;
 309      * If this fails, the queue is empty. This operation is one part
 310      * of the nextLocalTask method, that instead does a local-poll
 311      * in FIFO mode.
 312      *
 313      * The poll operation is, basically:
 314      *   if (CAS nonnull task t = q.array[k = q.base % length] to null)
 315      *       increment base and return task;
 316      *
 317      * However, there are several more cases that must be dealt with.
 318      * Some of them are just due to asynchrony; others reflect
 319      * contention and stealing policies. Stepping through them
 320      * illustrates some of the implementation decisions in this class.
 321      *
 322      *  * Slot k must be read with an acquiring read, which it must
 323      *    anyway to dereference and run the task if the (acquiring)
 324      *    CAS succeeds.
 325      *
 326      *  * q.base may change between reading and using its value to
 327      *    index the slot. To avoid trying to use the wrong t, the
 328      *    index and slot must be reread (not necessarily immediately)
 329      *    until consistent, unless this is a local poll by owner, in
 330      *    which case this form of inconsistency can only appear as t
 331      *    being null, below.
 332      *
 333      *  * Similarly, q.array may change (due to a resize), unless this
 334      *    is a local poll by owner. Otherwise, when t is present, this
 335      *    only needs consideration on CAS failure (since a CAS
 336      *    confirms the non-resized case.)
 337      *
 338      *  * t may appear null because a previous poll operation has not
 339      *    yet incremented q.base, so the read is from an already-taken
 340      *    index. This form of stall reflects the non-lock-freedom of
 341      *    the poll operation. Stalls can be detected by observing that
 342      *    q.base doesn't change on repeated reads of null t and when
 343      *    no other alternatives apply, spin-wait for it to settle.  To
 344      *    reduce producing these kinds of stalls by other stealers, we
 345      *    encourage timely writes to indices using otherwise
 346      *    unnecessarily strong writes.
 347      *
 348      *  * The CAS may fail, in which case we may want to retry unless
 349      *    there is too much contention. One goal is to balance and
 350      *    spread out the many forms of contention that may be
 351      *    encountered across polling and other operations to avoid
 352      *    sustained performance degradations. Across all cases where
 353      *    alternatives exist, a bounded number of CAS misses or stalls
 354      *    are tolerated (for slots, ctl, and elsewhere described
 355      *    below) before taking alternative action. These may move
 356      *    contention or retries elsewhere, which is still preferable
 357      *    to single-point bottlenecks.
 358      *
 359      *  * Even though the check "top == base" is quiescently accurate
 360      *    to determine whether a queue is empty, it is not of much use
 361      *    when deciding whether to try to poll or repoll after a
 362      *    failure.  Both top and base may move independently, and both
 363      *    lag updates to the underlying array. To reduce memory
 364      *    contention, non-owners avoid reading the "top" when
 365      *    possible, by using one-ahead reads to check whether to
 366      *    repoll, relying on the fact that a non-empty queue does not
 367      *    have two null slots in a row, except in cases (resizes and
 368      *    shifts) that can be detected with a secondary recheck that
 369      *    is less likely to conflict with owner writes.
 370      *
 371      * The poll operations in q.poll(), runWorker(), helpJoin(), and
 372      * elsewhere differ with respect to whether other queues are
 373      * available to try, and the presence or nature of screening steps
 374      * when only some kinds of tasks can be taken. When alternatives
 375      * (or failing) is an option, they uniformly give up after
 376      * bounded numbers of stalls and/or CAS failures, which reduces
 377      * contention when too many workers are polling too few tasks.
 378      * Overall, in the aggregate, we ensure probabilistic
 379      * non-blockingness of work-stealing at least until checking
 380      * quiescence (which is intrinsically blocking): If an attempted
 381      * steal fails in these ways, a scanning thief chooses a different
 382      * target to try next. In contexts where alternatives aren't
 383      * available, and when progress conditions can be isolated to
 384      * values of a single variable, simple spinloops (using
 385      * Thread.onSpinWait) are used to reduce memory traffic.
 386      *
 387      * WorkQueues are also used in a similar way for tasks submitted
 388      * to the pool. We cannot mix these tasks in the same queues used
 389      * by workers. Instead, we randomly associate submission queues
 390      * with submitting threads (or carriers when using VirtualThreads)
 391      * using a form of hashing.  The ThreadLocalRandom probe value
 392      * serves as a hash code for choosing existing queues, and may be
 393      * randomly repositioned upon contention with other submitters.
 394      * In essence, submitters act like workers except that they are
 395      * restricted to executing local tasks that they submitted (or
 396      * when known, subtasks thereof).  Insertion of tasks in shared
 397      * mode requires a lock. We use only a simple spinlock (as one
 398      * role of field "phase") because submitters encountering a busy
 399      * queue move to a different position to use or create other
 400      * queues.  They (spin) block when registering new queues, or
 401      * indirectly elsewhere, by revisiting later.
 402      *
 403      * Management
 404      * ==========
 405      *
 406      * The main throughput advantages of work-stealing stem from
 407      * decentralized control -- workers mostly take tasks from
 408      * themselves or each other, at rates that can exceed a billion
 409      * per second.  Most non-atomic control is performed by some form
 410      * of scanning across or within queues.  The pool itself creates,
 411      * activates (enables scanning for and running tasks),
 412      * deactivates, blocks, and terminates threads, all with minimal
 413      * central information.  There are only a few properties that we
 414      * can globally track or maintain, so we pack them into a small
 415      * number of variables, often maintaining atomicity without
 416      * blocking or locking.  Nearly all essentially atomic control
 417      * state is held in a few variables that are by far most often
 418      * read (not written) as status and consistency checks. We pack as
 419      * much information into them as we can.
 420      *
 421      * Field "ctl" contains 64 bits holding information needed to
 422      * atomically decide to add, enqueue (on an event queue), and
 423      * dequeue and release workers.  To enable this packing, we
 424      * restrict maximum parallelism to (1<<15)-1 (which is far in
 425      * excess of normal operating range) to allow ids, counts, and
 426      * their negations (used for thresholding) to fit into 16bit
 427      * subfields.
 428      *
 429      * Field "runState" and per-WorkQueue field "phase" play similar
 430      * roles, as lockable, versioned counters. Field runState also
 431      * includes monotonic event bits:
 432      * * SHUTDOWN: no more external tasks accepted; STOP when quiescent
 433      * * STOP: no more tasks run, and deregister all workers
 434      * * CLEANED: all unexecuted tasks have been cancelled
 435      * * TERMINATED: all workers deregistered and all queues cleaned
 436      * The version tags enable detection of state changes (by
 437      * comparing two reads) modulo bit wraparound. The bit range in
 438      * each case suffices for purposes of determining quiescence,
 439      * termination, avoiding ABA-like errors, and signal control, most
 440      * of which are ultimately based on at most 15bit ranges (due to
 441      * 32767 max total workers). RunState updates do not need to be
 442      * atomic with respect to ctl updates, but because they are not,
 443      * some care is required to avoid stalls. The seqLock properties
 444      * detect changes and conditionally upgrade to coordinate with
 445      * updates. It is typically held for less than a dozen
 446      * instructions unless the queue array is being resized, during
 447      * which contention is rare. To be conservative, lockRunState is
 448      * implemented as a spin/sleep loop. Here and elsewhere spin
 449      * constants are short enough to apply even on systems with few
 450      * available processors.  In addition to checking pool status,
 451      * reads of runState sometimes serve as acquire fences before
 452      * reading other fields.
 453      *
 454      * Field "parallelism" holds the target parallelism (normally
 455      * corresponding to pool size). Users can dynamically reset target
 456      * parallelism, but is only accessed when signalling or awaiting
 457      * work, so only slowly has an effect in creating threads or
 458      * letting them time out and terminate when idle.
 459      *
 460      * Array "queues" holds references to WorkQueues.  It is updated
 461      * (only during worker creation and termination) under the
 462      * runState lock. It is otherwise concurrently readable but reads
 463      * for use in scans (see below) are always prefaced by a volatile
 464      * read of runState (or equivalent constructions), ensuring that
 465      * its state is current at the point it is used (which is all we
 466      * require). To simplify index-based operations, the array size is
 467      * always a power of two, and all readers must tolerate null
 468      * slots.  Worker queues are at odd indices. Worker phase ids
 469      * masked with SMASK match their index. Shared (submission) queues
 470      * are at even indices. Grouping them together in this way aids in
 471      * task scanning: At top-level, both kinds of queues should be
 472      * sampled with approximately the same probability, which is
 473      * simpler if they are all in the same array. But we also need to
 474      * identify what kind they are without looking at them, leading to
 475      * this odd/even scheme. One disadvantage is that there are
 476      * usually many fewer submission queues, so there can be many
 477      * wasted probes (null slots). But this is still cheaper than
 478      * alternatives. Other loops over the queues array vary in origin
 479      * and stride depending on whether they cover only submission
 480      * (even) or worker (odd) queues or both, and whether they require
 481      * randomness (in which case cyclically exhaustive strides may be
 482      * used).
 483      *
 484      * All worker thread creation is on-demand, triggered by task
 485      * submissions, replacement of terminated workers, and/or
 486      * compensation for blocked workers. However, all other support
 487      * code is set up to work with other policies.  To ensure that we
 488      * do not hold on to worker or task references that would prevent
 489      * GC, all accesses to workQueues in waiting, signalling, and
 490      * control methods are via indices into the queues array (which is
 491      * one source of some of the messy code constructions here). In
 492      * essence, the queues array serves as a weak reference
 493      * mechanism. In particular, the stack top subfield of ctl stores
 494      * indices, not references. Operations on queues obtained from
 495      * these indices remain valid (with at most some unnecessary extra
 496      * work) even if an underlying worker failed and was replaced by
 497      * another at the same index. During termination, worker queue
 498      * array updates are disabled.
 499      *
 500      * Queuing Idle Workers. Unlike HPC work-stealing frameworks, we
 501      * cannot let workers spin indefinitely scanning for tasks when
 502      * none can be found immediately, and we cannot start/resume
 503      * workers unless there appear to be tasks available.  On the
 504      * other hand, we must quickly prod them into action when new
 505      * tasks are submitted or generated. These latencies are mainly a
 506      * function of JVM park/unpark (and underlying OS) performance,
 507      * which can be slow and variable (even though usages are
 508      * streamlined as much as possible).  In many usages, ramp-up time
 509      * is the main limiting factor in overall performance, which is
 510      * compounded at program start-up by JIT compilation and
 511      * allocation. On the other hand, throughput degrades when too
 512      * many threads poll for too few tasks. (See below.)
 513      *
 514      * The "ctl" field atomically maintains total and "released"
 515      * worker counts, plus the head of the available worker queue
 516      * (actually stack, represented by the lower 32bit subfield of
 517      * ctl).  Released workers are those known to be scanning for
 518      * and/or running tasks (we cannot accurately determine
 519      * which). Unreleased ("available") workers are recorded in the
 520      * ctl stack. These workers are made eligible for signalling by
 521      * enqueuing in ctl (see method deactivate).  This "queue" is a
 522      * form of Treiber stack. This is ideal for activating threads in
 523      * most-recently used order, and improves performance and
 524      * locality, outweighing the disadvantages of being prone to
 525      * contention and inability to release a worker unless it is
 526      * topmost on stack. The top stack state holds the value of the
 527      * "phase" field of the worker: its index and status, plus a
 528      * version counter that, in addition to the count subfields (also
 529      * serving as version stamps) provide protection against Treiber
 530      * stack ABA effects.
 531      *
 532      * Creating workers. To create a worker, we pre-increment counts
 533      * (serving as a reservation), and attempt to construct a
 534      * ForkJoinWorkerThread via its factory. On starting, the new
 535      * thread first invokes registerWorker, where it is assigned an
 536      * index in the queues array (expanding the array if necessary).
 537      * Upon any exception across these steps, or null return from
 538      * factory, deregisterWorker adjusts counts and records
 539      * accordingly.  If a null return, the pool continues running with
 540      * fewer than the target number workers. If exceptional, the
 541      * exception is propagated, generally to some external caller.
 542      *
 543      * WorkQueue field "phase" encodes the queue array id in lower
 544      * bits, and otherwise acts similarly to the pool runState field:
 545      * The "IDLE" bit is clear while active (either a released worker
 546      * or a locked external queue), with other bits serving as a
 547      * version counter to distinguish changes across multiple reads.
 548      * Note that phase field updates lag queue CAS releases; seeing a
 549      * non-idle phase does not guarantee that the worker is available
 550      * (and so is never checked in this way).
 551      *
 552      * The ctl field also serves as the basis for memory
 553      * synchronization surrounding activation. This uses a more
 554      * efficient version of a Dekker-like rule that task producers and
 555      * consumers sync with each other by both writing/CASing ctl (even
 556      * if to its current value).  However, rather than CASing ctl to
 557      * its current value in the common case where no action is
 558      * required, we reduce write contention by ensuring that
 559      * signalWork invocations are prefaced with a fully fenced memory
 560      * access (which is usually needed anyway).
 561      *
 562      * Signalling. Signals (in signalWork) cause new or reactivated
 563      * workers to scan for tasks.  SignalWork is invoked in two cases:
 564      * (1) When a task is pushed onto an empty queue, and (2) When a
 565      * worker takes a top-level task from a queue that has additional
 566      * tasks. Together, these suffice in O(log(#threads)) steps to
 567      * fully activate with at least enough workers, and ideally no
 568      * more than required.  This ideal is unobtainable: Callers do not
 569      * know whether another worker will finish its current task and
 570      * poll for others without need of a signal (which is otherwise an
 571      * advantage of work-stealing vs other schemes), and also must
 572      * conservatively estimate the triggering conditions of emptiness
 573      * or non-emptiness; all of which usually cause more activations
 574      * than necessary (see below). (Method signalWork is also used as
 575      * failsafe in case of Thread failures in deregisterWorker, to
 576      * activate or create a new worker to replace them).
 577      *
 578      * Top-Level scheduling
 579      * ====================
 580      *
 581      * Scanning. Method runWorker performs top-level scanning for (and
 582      * execution of) tasks by polling a pseudo-random permutation of
 583      * the array (by starting at a given index, and using a constant
 584      * cyclically exhaustive stride.)  It uses the same basic polling
 585      * method as WorkQueue.poll(), but restarts with a different
 586      * permutation on each rescan.  The pseudorandom generator need
 587      * not have high-quality statistical properties in the long
 588      * term. We use Marsaglia XorShifts, seeded with the Weyl sequence
 589      * from ThreadLocalRandom probes, which are cheap and suffice.
 590      *
 591      * Deactivation. When no tasks are found by a worker in runWorker,
 592      * it invokes awaitWork, that first deactivates (to an IDLE
 593      * phase).  Avoiding missed signals during deactivation requires a
 594      * (conservative) rescan, reactivating if there may be tasks to
 595      * poll. Because idle workers are often not yet blocked (parked),
 596      * we use a WorkQueue field to advertise that a waiter actually
 597      * needs unparking upon signal.
 598      *
 599      * When tasks are constructed as (recursive) DAGs, top-level
 600      * scanning is usually infrequent, and doesn't encounter most
 601      * of the following problems addressed by runWorker and awaitWork:
 602      *
 603      * Locality. Polls are organized into "runs", continuing until
 604      * empty or contended, while also minimizing interference by
 605      * postponing bookeeping to ends of runs. This may reduce
 606      * fairness.
 607      *
 608      * Contention. When many workers try to poll few queues, they
 609      * often collide, generating CAS failures and disrupting locality
 610      * of workers already running their tasks. This also leads to
 611      * stalls when tasks cannot be taken because other workers have
 612      * not finished poll operations, which is detected by reading
 613      * ahead in queue arrays. In both cases, workers restart scans in a
 614      * way that approximates randomized backoff.
 615      *
 616      * Oversignalling. When many short top-level tasks are present in
 617      * a small number of queues, the above signalling strategy may
 618      * activate many more workers than needed, worsening locality and
 619      * contention problems, while also generating more global
 620      * contention (field ctl is CASed on every activation and
 621      * deactivation). We filter out (both in runWorker and
 622      * signalWork) attempted signals that are surely not needed
 623      * because the signalled tasks are already taken.
 624      *
 625      * Shutdown and Quiescence
 626      * =======================
 627      *
 628      * Quiescence. Workers scan looking for work, giving up when they
 629      * don't find any, without being sure that none are available.
 630      * However, some required functionality relies on consensus about
 631      * quiescence (also termination, discussed below). The count
 632      * fields in ctl allow accurate discovery of states in which all
 633      * workers are idle.  However, because external (asynchronous)
 634      * submitters are not part of this vote, these mechanisms
 635      * themselves do not guarantee that the pool is in a quiescent
 636      * state with respect to methods isQuiescent, shutdown (which
 637      * begins termination when quiescent), helpQuiesce, and indirectly
 638      * others including tryCompensate. Method quiescent() is used in
 639      * all of these contexts. It provides checks that all workers are
 640      * idle and there are no submissions that they could poll if they
 641      * were not idle, retrying on inconsistent reads of queues and
 642      * using the runState seqLock to retry on queue array updates.
 643      * (It also reports quiescence if the pool is terminating.) A true
 644      * report means only that there was a moment at which quiescence
 645      * held.  False negatives are inevitable (for example when queues
 646      * indices lag updates, as described above), which is accommodated
 647      * when (tentatively) idle by scanning for work etc, and then
 648      * re-invoking. This includes cases in which the final unparked
 649      * thread (in deactivate()) uses quiescent() to check for tasks
 650      * that could have been added during a race window that would not
 651      * be accompanied by a signal, in which case re-activating itself
 652      * (or any other worker) to rescan. Method helpQuiesce acts
 653      * similarly but cannot rely on ctl counts to determine that all
 654      * workers are inactive because the caller and any others
 655      * executing helpQuiesce are not included in counts.
 656      *
 657      * Termination. Termination is initiated by setting STOP in one of
 658      * three ways (via methods tryTerminate and quiescent):
 659      * * A call to shutdownNow, in which case all workers are
 660      *   interrupted, first ensuring that the queues array is stable,
 661      *   to avoid missing any workers.
 662      * * A call to shutdown when quiescent, in which case method
 663      *   releaseWaiters is used to dequeue them, at which point they notice
 664      *   STOP state and return from runWorker to deregister();
 665      * * The pool becomes quiescent() sometime after shutdown has
 666      *   been called, in which case releaseWaiters is also used to
 667      *   propagate as they deregister.
 668      * Upon STOP, each worker, as well as external callers to
 669      * tryTerminate (via close() etc) race to set CLEANED, indicating
 670      * that all tasks have been cancelled. The implementation (method
 671      * cleanQueues) balances cases in which there may be many tasks to
 672      * cancel (benefitting from parallelism) versus contention and
 673      * interference when many threads try to poll remaining queues,
 674      * while also avoiding unnecessary rechecks, by using
 675      * pseudorandom scans and giving up upon interference. This may be
 676      * retried by the same caller only when there are no more
 677      * registered workers, using the same criteria as method
 678      * quiescent.  When CLEANED and all workers have deregistered,
 679      * TERMINATED is set, also signalling any caller of
 680      * awaitTermination or close.  Because shutdownNow-based
 681      * termination relies on interrupts, there is no guarantee that
 682      * workers will stop if their tasks ignore interrupts.  Class
 683      * InterruptibleTask (see below) further arranges runState checks
 684      * before executing task bodies, and ensures interrupts while
 685      * terminating. Even so, there are no guarantees because tasks may
 686      * internally enter unbounded loops.
 687      *
 688      * Trimming workers. To release resources after periods of lack of
 689      * use, a worker starting to wait when the pool is quiescent will
 690      * time out and terminate if the pool has remained quiescent for
 691      * period given by field keepAlive (default 60sec), which applies
 692      * to the first timeout of a quiescent pool. Subsequent cases use
 693      * minimal delays such that, if still quiescent, all will be
 694      * released soon thereafter. This is checked by setting the
 695      * "source" field of signallee to an invalid value, that will
 696      * remain invalid only if it did not process any tasks.
 697      *
 698      * Joining Tasks
 699      * =============
 700      *
 701      * The "Join" part of ForkJoinPools consists of a set of
 702      * mechanisms that sometimes or always (depending on the kind of
 703      * task) avoid context switching or adding worker threads when one
 704      * task would otherwise be blocked waiting for completion of
 705      * another, basically, just by running that task or one of its
 706      * subtasks if not already taken. These mechanics are disabled for
 707      * InterruptibleTasks, that guarantee that callers do not execute
 708      * submitted tasks.
 709      *
 710      * The basic structure of joining is an extended spin/block scheme
 711      * in which workers check for task completions status between
 712      * steps to find other work, until relevant pool state stabilizes
 713      * enough to believe that no such tasks are available, at which
 714      * point blocking. This is usually a good choice of when to block
 715      * that would otherwise be harder to approximate.
 716      *
 717      * These forms of helping may increase stack space usage, but that
 718      * space is bounded in tree/dag structured procedurally parallel
 719      * designs to be no more than that if a task were executed only by
 720      * the joining thread. This is arranged by associated task
 721      * subclasses that also help detect and control the ways in which
 722      * this may occur.
 723      *
 724      * Normally, the first option when joining a task that is not done
 725      * is to try to take it from the local queue and run it. Method
 726      * tryRemoveAndExec tries to do so.  For tasks with any form of
 727      * subtasks that must be completed first, we try to locate these
 728      * subtasks and run them as well. This is easy when local, but
 729      * when stolen, steal-backs are restricted to the same rules as
 730      * stealing (polling), which requires additional bookkeeping and
 731      * scanning. This cost is still very much worthwhile because of
 732      * its impact on task scheduling and resource control.
 733      *
 734      * The two methods for finding and executing subtasks vary in
 735      * details.  The algorithm in helpJoin entails a form of "linear
 736      * helping".  Each worker records (in field "source") the index of
 737      * the internal queue from which it last stole a task. (Note:
 738      * because chains cannot include even-numbered external queues,
 739      * they are ignored, and 0 is an OK default. However, the source
 740      * field is set anyway, or eventually to DROPPED, to ensure
 741      * volatile memory synchronization effects.) The scan in method
 742      * helpJoin uses these markers to try to find a worker to help
 743      * (i.e., steal back a task from and execute it) that could make
 744      * progress toward completion of the actively joined task.  Thus,
 745      * the joiner executes a task that would be on its own local deque
 746      * if the to-be-joined task had not been stolen. This is a
 747      * conservative variant of the approach described in Wagner &
 748      * Calder "Leapfrogging: a portable technique for implementing
 749      * efficient futures" SIGPLAN Notices, 1993
 750      * (http://portal.acm.org/citation.cfm?id=155354). It differs
 751      * mainly in that we only record queues, not full dependency
 752      * links.  This requires a linear scan of the queues to locate
 753      * stealers, but isolates cost to when it is needed, rather than
 754      * adding to per-task overhead.  For CountedCompleters, the
 755      * analogous method helpComplete doesn't need stealer-tracking,
 756      * but requires a similar (but simpler) check of completion
 757      * chains.
 758      *
 759      * In either case, searches can fail to locate stealers when
 760      * stalls delay recording sources or issuing subtasks. We avoid
 761      * some of these cases by using snapshotted values of ctl as a
 762      * check that the numbers of workers are not changing, along with
 763      * rescans to deal with contention and stalls.  But even when
 764      * accurately identified, stealers might not ever produce a task
 765      * that the joiner can in turn help with.
 766      *
 767      * Related method helpAsyncBlocker does not directly rely on
 768      * subtask structure, but instead avoids or postpones blocking of
 769      * tagged tasks (CompletableFuture.AsynchronousCompletionTask) by
 770      * executing other asyncs that can be processed in any order.
 771      * This is currently invoked only in non-join-based blocking
 772      * contexts from classes CompletableFuture and
 773      * SubmissionPublisher, that could be further generalized.
 774      *
 775      * When any of the above fail to avoid blocking, we rely on
 776      * "compensation" -- an indirect form of context switching that
 777      * either activates an existing worker to take the place of the
 778      * blocked one, or expands the number of workers.
 779      *
 780      * Compensation does not by default aim to keep exactly the target
 781      * parallelism number of unblocked threads running at any given
 782      * time. Some previous versions of this class employed immediate
 783      * compensations for any blocked join. However, in practice, the
 784      * vast majority of blockages are transient byproducts of GC and
 785      * other JVM or OS activities that are made worse by replacement
 786      * by causing longer-term oversubscription. These are inevitable
 787      * without (unobtainably) perfect information about whether worker
 788      * creation is actually necessary.  False alarms are common enough
 789      * to negatively impact performance, so compensation is by default
 790      * attempted only when it appears possible that the pool could
 791      * stall due to lack of any unblocked workers.  However, we allow
 792      * users to override defaults using the long form of the
 793      * ForkJoinPool constructor. The compensation mechanism may also
 794      * be bounded.  Bounds for the commonPool better enable JVMs to
 795      * cope with programming errors and abuse before running out of
 796      * resources to do so.
 797      *
 798      * The ManagedBlocker extension API can't use helping so relies
 799      * only on compensation in method awaitBlocker. This API was
 800      * designed to highlight the uncertainty of compensation decisions
 801      * by requiring implementation of method isReleasable to abort
 802      * compensation during attempts to obtain a stable snapshot. But
 803      * users now rely upon the fact that if isReleasable always
 804      * returns false, the API can be used to obtain precautionary
 805      * compensation, which is sometimes the only reasonable option
 806      * when running unknown code in tasks; which is now supported more
 807      * simply (see method beginCompensatedBlock).
 808      *
 809      * Common Pool
 810      * ===========
 811      *
 812      * The static common pool always exists after static
 813      * initialization.  Since it (or any other created pool) need
 814      * never be used, we minimize initial construction overhead and
 815      * footprint to the setup of about a dozen fields, although with
 816      * some System property parsing properties are set. The common pool is
 817      * distinguished by having a null workerNamePrefix (which is an
 818      * odd convention, but avoids the need to decode status in factory
 819      * classes).  It also has PRESET_SIZE config set if parallelism
 820      * was configured by system property.
 821      *
 822      * When external threads use the common pool, they can perform
 823      * subtask processing (see helpComplete and related methods) upon
 824      * joins, unless they are submitted using ExecutorService
 825      * submission methods, which implicitly disallow this.  This
 826      * caller-helps policy makes it sensible to set common pool
 827      * parallelism level to one (or more) less than the total number
 828      * of available cores, or even zero for pure caller-runs. External
 829      * threads waiting for joins first check the common pool for their
 830      * task, which fails quickly if the caller did not fork to common
 831      * pool.
 832      *
 833      * Guarantees for common pool parallelism zero are limited to
 834      * tasks that are joined by their callers in a tree-structured
 835      * fashion or use CountedCompleters (as is true for jdk
 836      * parallelStreams). Support infiltrates several methods,
 837      * including those that retry helping steps until we are sure that
 838      * none apply if there are no workers. To deal with conflicting
 839      * requirements, uses of the commonPool that require async because
 840      * caller-runs need not apply, ensure threads are enabled (by
 841      * setting parallelism) via method asyncCommonPool before
 842      * proceeding. (In principle, overriding zero parallelism needs to
 843      * ensure at least one worker, but due to other backward
 844      * compatibility contraints, ensures two.)
 845      *
 846      * As a more appropriate default in managed environments, unless
 847      * overridden by system properties, we use workers of subclass
 848      * InnocuousForkJoinWorkerThread for the commonPool.  These
 849      * workers do not belong to any user-defined ThreadGroup, and
 850      * clear all ThreadLocals and reset the ContextClassLoader before
 851      * (re)activating to execute top-level tasks.  The associated
 852      * mechanics may be JVM-dependent and must access particular
 853      * Thread class fields to achieve this effect.
 854      *
 855      * InterruptibleTasks
 856      * ====================
 857      *
 858      * Regular ForkJoinTasks manage task cancellation (method cancel)
 859      * independently from the interrupt status of threads running
 860      * tasks.  Interrupts are issued internally only while
 861      * terminating, to wake up workers and cancel queued tasks.  By
 862      * default, interrupts are cleared only when necessary to ensure
 863      * that calls to LockSupport.park do not loop indefinitely (park
 864      * returns immediately if the current thread is interrupted).
 865      *
 866      * To comply with ExecutorService specs, we use subclasses of
 867      * abstract class InterruptibleTask for tasks that require
 868      * stronger interruption and cancellation guarantees.  External
 869      * submitters never run these tasks, even if in the common pool
 870      * (as indicated by ForkJoinTask.noUserHelp status bit).
 871      * InterruptibleTasks include a "runner" field (implemented
 872      * similarly to FutureTask) to support cancel(true).  Upon pool
 873      * shutdown, runners are interrupted so they can cancel. Since
 874      * external joining callers never run these tasks, they must await
 875      * cancellation by others, which can occur along several different
 876      * paths.
 877      *
 878      * Across these APIs, rules for reporting exceptions for tasks
 879      * with results accessed via join() differ from those via get(),
 880      * which differ from those invoked using pool submit methods by
 881      * non-workers (which comply with Future.get() specs). Internal
 882      * usages of ForkJoinTasks ignore interrupt status when executing
 883      * or awaiting completion.  Otherwise, reporting task results or
 884      * exceptions is preferred to throwing InterruptedExceptions,
 885      * which are in turn preferred to timeouts. Similarly, completion
 886      * status is preferred to reporting cancellation.  Cancellation is
 887      * reported as an unchecked exception by join(), and by worker
 888      * calls to get(), but is otherwise wrapped in a (checked)
 889      * ExecutionException.
 890      *
 891      * Worker Threads cannot be VirtualThreads, as enforced by
 892      * requiring ForkJoinWorkerThreads in factories.  There are
 893      * several constructions relying on this.  However as of this
 894      * writing, virtual thread bodies are by default run as some form
 895      * of InterruptibleTask.
 896      *
 897      * DelayScheduler
 898      * ================
 899      *
 900      * This class supports ScheduledExecutorService methods by
 901      * creating and starting a DelayScheduler on first use of these
 902      * methods (via startDelayScheduler). The scheduler operates
 903      * independently in its own thread, relaying tasks to the pool to
 904      * execute when their delays elapse (see method
 905      * executeEnabledScheduledTask).  The only other interactions with
 906      * the delayScheduler are to control shutdown and maintain
 907      * shutdown-related policies in methods quiescent() and
 908      * tryTerminate(). In particular, processing must deal with cases
 909      * in which tasks are submitted before shutdown, but not enabled
 910      * until afterwards, in which case they must bypass some screening
 911      * to be allowed to run. Conversely, the DelayScheduler checks
 912      * runState status and when enabled, completes termination, using
 913      * only methods shutdownStatus and tryStopIfShutdown. All of these
 914      * methods are final and have signatures referencing
 915      * DelaySchedulers, so cannot conflict with those of any existing
 916      * FJP subclasses.
 917      *
 918      * Memory placement
 919      * ================
 920      *
 921      * Performance is very sensitive to placement of instances of
 922      * ForkJoinPool and WorkQueues and their queue arrays, as well as
 923      * the placement of their fields. Caches misses and contention due
 924      * to false-sharing have been observed to slow down some programs
 925      * by more than a factor of four. Effects may vary across initial
 926      * memory configuarations, applications, and different garbage
 927      * collectors and GC settings, so there is no perfect solution.
 928      * Too much isolation may generate more cache misses in common
 929      * cases (because some fields snd slots are usually read at the
 930      * same time). The @Contended annotation provides only rough
 931      * control (for good reason). Similarly for relying on fields
 932      * being placed in size-sorted declaration order.
 933      *
 934      * We isolate the ForkJoinPool.ctl field that otherwise causes the
 935      * most false-sharing misses with respect to other fields. Also,
 936      * ForkJoinPool fields are ordered such that fields less prone to
 937      * contention effects are first, offsetting those that otherwise
 938      * would be, while also reducing total footprint vs using
 939      * multiple @Contended regions, which tends to slow down
 940      * less-contended applications. To help arrange this, some
 941      * non-reference fields are declared as "long" even when ints or
 942      * shorts would suffice.  For class WorkQueue, an
 943      * embedded @Contended isolates the very busy top index, and
 944      * another segregates status and bookkeeping fields written
 945      * (mostly) by owners, that otherwise interfere with reading
 946      * array, top, and base fields. There are other variables commonly
 947      * contributing to false-sharing-related performance issues
 948      * (including fields of class Thread), but we can't do much about
 949      * this except try to minimize access.
 950      *
 951      * Initial sizing and resizing of WorkQueue arrays is an even more
 952      * delicate tradeoff because the best strategy systematically
 953      * varies across garbage collectors. Small arrays are better for
 954      * locality and reduce GC scan time, but large arrays reduce both
 955      * direct false-sharing and indirect cases due to GC bookkeeping
 956      * (cardmarks etc), and reduce the number of resizes, which are
 957      * not especially fast because they require atomic transfers.
 958      * Currently, arrays are initialized to be just large enough to
 959      * avoid resizing in most tree-structured tasks, but grow rapidly
 960      * until large.  (Maintenance note: any changes in fields, queues,
 961      * or their uses, or JVM layout policies, must be accompanied by
 962      * re-evaluation of these placement and sizing decisions.)
 963      *
 964      * Style notes
 965      * ===========
 966      *
 967      * Memory ordering relies mainly on atomic operations (CAS,
 968      * getAndSet, getAndAdd) along with moded accesses. These use
 969      * jdk-internal Unsafe for atomics and special memory modes,
 970      * rather than VarHandles, to avoid initialization dependencies in
 971      * other jdk components that require early parallelism.  This can
 972      * be awkward and ugly, but also reflects the need to control
 973      * outcomes across the unusual cases that arise in very racy code
 974      * with very few invariants. All atomic task slot updates use
 975      * Unsafe operations requiring offset positions, not indices, as
 976      * computed by method slotOffset. All fields are read into locals
 977      * before use, and null-checked if they are references, even if
 978      * they can never be null under current usages. Usually,
 979      * computations (held in local variables) are defined as soon as
 980      * logically enabled, sometimes to convince compilers that they
 981      * may be performed despite memory ordering constraints.  Array
 982      * accesses using masked indices include checks (that are always
 983      * true) that the array length is non-zero to avoid compilers
 984      * inserting more expensive traps.  This is usually done in a
 985      * "C"-like style of listing declarations at the heads of methods
 986      * or blocks, and using inline assignments on first encounter.
 987      * Nearly all explicit checks lead to bypass/return, not exception
 988      * throws, because they may legitimately arise during shutdown. A
 989      * few unusual loop constructions encourage (with varying
 990      * effectiveness) JVMs about where (not) to place safepoints. All
 991      * public methods screen arguments (mainly null checks) before
 992      * creating or executing tasks.
 993      *
 994      * There is a lot of representation-level coupling among classes
 995      * ForkJoinPool, ForkJoinWorkerThread, and ForkJoinTask.  The
 996      * fields of WorkQueue maintain data structures managed by
 997      * ForkJoinPool, so are directly accessed.  There is little point
 998      * trying to reduce this, since any associated future changes in
 999      * representations will need to be accompanied by algorithmic
1000      * changes anyway. Several methods intrinsically sprawl because
1001      * they must accumulate sets of consistent reads of fields held in
1002      * local variables. Some others are artificially broken up to
1003      * reduce producer/consumer imbalances due to dynamic compilation.
1004      * There are also other coding oddities (including several
1005      * unnecessary-looking hoisted null checks) that help some methods
1006      * perform reasonably even when interpreted (not compiled).
1007      *
1008      * The order of declarations in this file is (with a few exceptions):
1009      * (1) Static configuration constants
1010      * (2) Static utility functions
1011      * (3) Nested (static) classes
1012      * (4) Fields, along with constants used when unpacking some of them
1013      * (5) Internal control methods
1014      * (6) Callbacks and other support for ForkJoinTask methods
1015      * (7) Exported methods
1016      * (8) Static block initializing statics in minimally dependent order
1017      *
1018      */
1019 
1020     // static configuration constants
1021 
1022     /**
1023      * Default idle timeout value (in milliseconds) for idle threads
1024      * to park waiting for new work before terminating.
1025      */
1026     static final long DEFAULT_KEEPALIVE = 60_000L;
1027 
1028     /**
1029      * Undershoot tolerance for idle timeouts, also serving as the
1030      * minimum allowed timeout value.
1031      */
1032     static final long TIMEOUT_SLOP = 20L;
1033 
1034     /**
1035      * The default value for common pool maxSpares.  Overridable using
1036      * the "java.util.concurrent.ForkJoinPool.common.maximumSpares"
1037      * system property.  The default value is far in excess of normal
1038      * requirements, but also far short of maximum capacity and typical OS
1039      * thread limits, so allows JVMs to catch misuse/abuse before
1040      * running out of resources needed to do so.
1041      */
1042     static final int DEFAULT_COMMON_MAX_SPARES = 256;
1043 
1044     /**
1045      * Initial capacity of work-stealing queue array.
1046      * Must be a power of two, at least 2. See above.
1047      */
1048     static final int INITIAL_QUEUE_CAPACITY = 1 << 6;
1049 
1050     // conversions among short, int, long
1051     static final int  SMASK           = 0xffff;      // (unsigned) short bits
1052     static final long LMASK           = 0xffffffffL; // lower 32 bits of long
1053     static final long UMASK           = ~LMASK;      // upper 32 bits
1054 
1055     // masks and sentinels for queue indices
1056     static final int MAX_CAP          = 0x7fff;   // max # workers
1057     static final int EXTERNAL_ID_MASK = 0x3ffe;   // max external queue id
1058     static final int INVALID_ID       = 0x4000;   // unused external queue id
1059 
1060     // pool.runState bits
1061     static final long STOP            = 1L <<  0;   // terminating
1062     static final long SHUTDOWN        = 1L <<  1;   // terminate when quiescent
1063     static final long CLEANED         = 1L <<  2;   // stopped and queues cleared
1064     static final long TERMINATED      = 1L <<  3;   // only set if STOP also set
1065     static final long RS_LOCK         = 1L <<  4;   // lowest seqlock bit
1066 
1067     // spin/sleep limits for runState locking and elsewhere
1068     static final int SPIN_WAITS       = 1 <<  7;   // max calls to onSpinWait
1069     static final int MIN_SLEEP        = 1 << 10;   // approx 1 usec as nanos
1070     static final int MAX_SLEEP        = 1 << 20;   // approx 1 sec  as nanos
1071 
1072     // {pool, workQueue} config bits
1073     static final int FIFO             = 1 << 0;   // fifo queue or access mode
1074     static final int CLEAR_TLS        = 1 << 1;   // set for Innocuous workers
1075     static final int PRESET_SIZE      = 1 << 2;   // size was set by property
1076 
1077     // others
1078     static final int DROPPED          = 1 << 16;  // removed from ctl counts
1079     static final int UNCOMPENSATE     = 1 << 16;  // tryCompensate return
1080     static final int IDLE             = 1 << 16;  // phase seqlock/version count
1081     static final int MIN_QUEUES_SIZE  = 1 << 4;   // ensure external slots
1082 
1083     /*
1084      * Bits and masks for ctl and bounds are packed with 4 16 bit subfields:
1085      * RC: Number of released (unqueued) workers
1086      * TC: Number of total workers
1087      * SS: version count and status of top waiting thread
1088      * ID: poolIndex of top of Treiber stack of waiters
1089      *
1090      * When convenient, we can extract the lower 32 stack top bits
1091      * (including version bits) as sp=(int)ctl. When sp is non-zero,
1092      * there are waiting workers.  Count fields may be transiently
1093      * negative during termination because of out-of-order updates.
1094      * To deal with this, we use casts in and out of "short" and/or
1095      * signed shifts to maintain signedness. Because it occupies
1096      * uppermost bits, we can add one release count using getAndAdd of
1097      * RC_UNIT, rather than CAS, when returning from a blocked join.
1098      * Other updates of multiple subfields require CAS.
1099      */
1100 
1101     // Release counts
1102     static final int  RC_SHIFT = 48;
1103     static final long RC_UNIT  = 0x0001L << RC_SHIFT;
1104     static final long RC_MASK  = 0xffffL << RC_SHIFT;
1105     // Total counts
1106     static final int  TC_SHIFT = 32;
1107     static final long TC_UNIT  = 0x0001L << TC_SHIFT;
1108     static final long TC_MASK  = 0xffffL << TC_SHIFT;
1109 
1110     /*
1111      * All atomic operations on task arrays (queues) use Unsafe
1112      * operations that take array offsets versus indices, based on
1113      * array base and shift constants established during static
1114      * initialization.
1115      */
1116     static final long ABASE;
1117     static final int  ASHIFT;
1118 
1119     // Static utilities
1120 
1121     /**
1122      * Returns the array offset corresponding to the given index for
1123      * Unsafe task queue operations
1124      */
1125     static long slotOffset(int index) {
1126         return ((long)index << ASHIFT) + ABASE;
1127     }
1128 
1129     // Nested classes
1130 
1131     /**
1132      * Factory for creating new {@link ForkJoinWorkerThread}s.
1133      * A {@code ForkJoinWorkerThreadFactory} must be defined and used
1134      * for {@code ForkJoinWorkerThread} subclasses that extend base
1135      * functionality or initialize threads with different contexts.
1136      */
1137     public static interface ForkJoinWorkerThreadFactory {
1138         /**
1139          * Returns a new worker thread operating in the given pool.
1140          * Returning null or throwing an exception may result in tasks
1141          * never being executed.  If this method throws an exception,
1142          * it is relayed to the caller of the method (for example
1143          * {@code execute}) causing attempted thread creation. If this
1144          * method returns null or throws an exception, it is not
1145          * retried until the next attempted creation (for example
1146          * another call to {@code execute}).
1147          *
1148          * @param pool the pool this thread works in
1149          * @return the new worker thread, or {@code null} if the request
1150          *         to create a thread is rejected
1151          * @throws NullPointerException if the pool is null
1152          */
1153         public ForkJoinWorkerThread newThread(ForkJoinPool pool);
1154     }
1155 
1156     /**
1157      * Default ForkJoinWorkerThreadFactory implementation; creates a
1158      * new ForkJoinWorkerThread using the system class loader as the
1159      * thread context class loader.
1160      */
1161     static final class DefaultForkJoinWorkerThreadFactory
1162         implements ForkJoinWorkerThreadFactory {
1163         public final ForkJoinWorkerThread newThread(ForkJoinPool pool) {
1164             return ((pool.workerNamePrefix == null) ? // is commonPool
1165                     new ForkJoinWorkerThread.InnocuousForkJoinWorkerThread(pool) :
1166                     new ForkJoinWorkerThread(null, pool, true, false));
1167         }
1168     }
1169 
1170     /**
1171      * Queues supporting work-stealing as well as external task
1172      * submission. See above for descriptions and algorithms.
1173      */
1174     static final class WorkQueue {
1175         // fields declared in order of their likely layout on most VMs
1176         final ForkJoinWorkerThread owner; // null if shared
1177         ForkJoinTask<?>[] array;   // the queued tasks; power of 2 size
1178         int base;                  // index of next slot for poll
1179         final int config;          // mode bits
1180 
1181         @jdk.internal.vm.annotation.Contended("t") // segregate
1182         int top;                   // index of next slot for push
1183 
1184         // fields otherwise causing more unnecessary false-sharing cache misses
1185         @jdk.internal.vm.annotation.Contended("w")
1186         volatile int phase;        // versioned active status
1187         @jdk.internal.vm.annotation.Contended("w")
1188         int stackPred;             // pool stack (ctl) predecessor link
1189         @jdk.internal.vm.annotation.Contended("w")
1190         volatile int parking;      // nonzero if parked in awaitWork
1191         @jdk.internal.vm.annotation.Contended("w")
1192         volatile int source;       // source queue id (or DROPPED)
1193         @jdk.internal.vm.annotation.Contended("w")
1194         int nsteals;               // number of steals from other queues
1195 
1196         // Support for atomic operations
1197         private static final Unsafe U;
1198         private static final long PHASE;
1199         private static final long BASE;
1200         private static final long TOP;
1201         private static final long ARRAY;
1202 
1203         final void updateBase(int v) {
1204             U.putIntVolatile(this, BASE, v);
1205         }
1206         final void updateTop(int v) {
1207             U.putIntOpaque(this, TOP, v);
1208         }
1209         final void updateArray(ForkJoinTask<?>[] a) {
1210             U.getAndSetReference(this, ARRAY, a);
1211         }
1212         final void unlockPhase() {
1213             U.getAndAddInt(this, PHASE, IDLE);
1214         }
1215         final boolean tryLockPhase() {    // seqlock acquire
1216             int p;
1217             return (((p = phase) & IDLE) != 0 &&
1218                     U.compareAndSetInt(this, PHASE, p, p + IDLE));
1219         }
1220 
1221         /**
1222          * Constructor. For internal queues, most fields are initialized
1223          * upon thread start in pool.registerWorker.
1224          */
1225         WorkQueue(ForkJoinWorkerThread owner, int id, int cfg,
1226                   boolean clearThreadLocals) {
1227             this.config = (clearThreadLocals) ? cfg | CLEAR_TLS : cfg;
1228             if ((this.owner = owner) == null) {
1229                 array = new ForkJoinTask<?>[INITIAL_QUEUE_CAPACITY];
1230                 phase = id | IDLE;
1231             }
1232         }
1233 
1234         /**
1235          * Returns an exportable index (used by ForkJoinWorkerThread).
1236          */
1237         final int getPoolIndex() {
1238             return (phase & 0xffff) >>> 1; // ignore odd/even tag bit
1239         }
1240 
1241         /**
1242          * Returns the approximate number of tasks in the queue.
1243          */
1244         final int queueSize() {
1245             int unused = phase;             // for ordering effect
1246             return Math.max(top - base, 0); // ignore transient negative
1247         }
1248 
1249         /**
1250          * Pushes a task. Called only by owner or if already locked
1251          *
1252          * @param task the task; no-op if null
1253          * @param pool the pool to signal if was previously empty, else null
1254          * @param internal if caller owns this queue
1255          * @throws RejectedExecutionException if array could not be resized
1256          */
1257         final void push(ForkJoinTask<?> task, ForkJoinPool pool, boolean internal) {
1258             int s = top, b = base, m, cap, room; ForkJoinTask<?>[] a;
1259             if ((a = array) != null && (cap = a.length) > 0) { // else disabled
1260                 if ((room = (m = cap - 1) - (s - b)) >= 0) {
1261                     top = s + 1;
1262                     long pos = slotOffset(m & s);
1263                     if (!internal)
1264                         U.putReference(a, pos, task);       // inside lock
1265                     else
1266                         U.getAndSetReference(a, pos, task); // fully fenced
1267                     if (room == 0 && (a = growArray(a, cap, s)) != null)
1268                         m = a.length - 1;                   // resize
1269                 }
1270                 if (!internal)
1271                     unlockPhase();
1272                 if (room < 0)
1273                     throw new RejectedExecutionException("Queue capacity exceeded");
1274                 if (pool != null && a != null &&
1275                     U.getReferenceAcquire(a, slotOffset(m & (s - 1))) == null)
1276                     pool.signalWork(a, m & s);   // may have appeared empty
1277             }
1278         }
1279 
1280         /**
1281          * Resizes the queue array unless out of memory.
1282          * @param a old array
1283          * @param cap old array capacity
1284          * @param s current top
1285          * @return new array, or null on failure
1286          */
1287         private ForkJoinTask<?>[] growArray(ForkJoinTask<?>[] a, int cap, int s) {
1288             int newCap = (cap >= 1 << 16) ? cap << 1 : cap << 2;
1289             ForkJoinTask<?>[] newArray = null;
1290             if (a != null && a.length == cap && cap > 0 && newCap > 0) {
1291                 try {
1292                     newArray = new ForkJoinTask<?>[newCap];
1293                 } catch (OutOfMemoryError ex) {
1294                 }
1295                 if (newArray != null) {               // else throw on next push
1296                     int mask = cap - 1, newMask = newCap - 1;
1297                     for (int k = s, j = cap; j > 0; --j, --k) {
1298                         ForkJoinTask<?> u;            // poll old, push to new
1299                         if ((u = (ForkJoinTask<?>)U.getAndSetReference(
1300                                  a, slotOffset(k & mask), null)) == null)
1301                             break;                    // lost to pollers
1302                         newArray[k & newMask] = u;
1303                     }
1304                     updateArray(newArray);           // fully fenced
1305                 }
1306             }
1307             return newArray;
1308         }
1309 
1310         /**
1311          * Takes next task, if one exists, in lifo order.
1312          */
1313         private ForkJoinTask<?> localPop() {
1314             ForkJoinTask<?> t = null;
1315             int s = top - 1, cap; long k; ForkJoinTask<?>[] a;
1316             if ((a = array) != null && (cap = a.length) > 0 &&
1317                 U.getReference(a, k = slotOffset((cap - 1) & s)) != null &&
1318                 (t = (ForkJoinTask<?>)U.getAndSetReference(a, k, null)) != null)
1319                 updateTop(s);
1320             return t;
1321         }
1322 
1323         /**
1324          * Takes next task, if one exists, in fifo order.
1325          */
1326         private ForkJoinTask<?> localPoll() {
1327             ForkJoinTask<?> t = null;
1328             int p = top, cap; ForkJoinTask<?>[] a;
1329             if ((a = array) != null && (cap = a.length) > 0) {
1330                 for (int b = base; p - b > 0; ) {
1331                     int nb = b + 1;
1332                     long k = slotOffset((cap - 1) & b);
1333                     if (U.getReference(a, k) == null) {
1334                         if (nb == p)
1335                             break;          // else base is lagging
1336                         while (b == (b = U.getIntAcquire(this, BASE)))
1337                             Thread.onSpinWait(); // spin to reduce memory traffic
1338                     }
1339                     else if ((t = (ForkJoinTask<?>)
1340                               U.getAndSetReference(a, k, null)) != null) {
1341                         updateBase(nb);
1342                         break;
1343                     }
1344                     else
1345                         b = base;
1346                 }
1347             }
1348             return t;
1349         }
1350 
1351         /**
1352          * Takes next task, if one exists, using configured mode.
1353          */
1354         final ForkJoinTask<?> nextLocalTask() {
1355             return (config & FIFO) == 0 ? localPop() : localPoll();
1356         }
1357 
1358         /**
1359          * Pops the given task only if it is at the current top.
1360          * @param task the task. Caller must ensure non-null.
1361          * @param internal if caller owns this queue
1362          */
1363         final boolean tryUnpush(ForkJoinTask<?> task, boolean internal) {
1364             boolean taken = false;
1365             ForkJoinTask<?>[] a = array;
1366             int p = top, s = p - 1, cap; long k;
1367             if (a != null && (cap = a.length) > 0 &&
1368                 U.getReference(a, k = slotOffset((cap - 1) & s)) == task &&
1369                 (internal || tryLockPhase())) {
1370                 if (top == p && U.compareAndSetReference(a, k, task, null)) {
1371                     taken = true;
1372                     updateTop(s);
1373                 }
1374                 if (!internal)
1375                     unlockPhase();
1376             }
1377             return taken;
1378         }
1379 
1380         /**
1381          * Returns next task, if one exists, in order specified by mode.
1382          */
1383         final ForkJoinTask<?> peek() {
1384             ForkJoinTask<?>[] a = array;
1385             int b = base, cfg = config, p = top, cap;
1386             if (p != b && a != null && (cap = a.length) > 0) {
1387                 if ((cfg & FIFO) == 0)
1388                     return a[(cap - 1) & (p - 1)];
1389                 else { // skip over in-progress removals
1390                     ForkJoinTask<?> t;
1391                     for ( ; p - b > 0; ++b) {
1392                         if ((t = a[(cap - 1) & b]) != null)
1393                             return t;
1394                     }
1395                 }
1396             }
1397             return null;
1398         }
1399 
1400         /**
1401          * Polls for a task. Used only by non-owners.
1402          */
1403         final ForkJoinTask<?> poll() {
1404             for (int pb = -1, b; ; pb = b) {       // track progress
1405                 ForkJoinTask<?> t; int cap, nb; long k; ForkJoinTask<?>[] a;
1406                 if ((a = array) == null || (cap = a.length) <= 0)
1407                     break;
1408                 t = (ForkJoinTask<?>)U.getReferenceAcquire(
1409                     a, k = slotOffset((cap - 1) & (b = base)));
1410                 Object u = U.getReference(         // next slot
1411                     a, slotOffset((cap - 1) & (nb = b + 1)));
1412                 if (base != b)                     // inconsistent
1413                     ;
1414                 else if (t == null) {
1415                     if (u == null && top - b <= 0)
1416                         break;                     // empty
1417                     if (pb == b)
1418                         Thread.onSpinWait();       // stalled
1419                 }
1420                 else if (U.compareAndSetReference(a, k, t, null)) {
1421                     updateBase(nb);
1422                     return t;
1423                 }
1424             }
1425             return null;
1426         }
1427 
1428         // specialized execution methods
1429 
1430         /*
1431          * Two version (lifo and fifo) of top-level execution, split
1432          * across modes to better isolate task dispatch and local
1433          * processing from top-level scheduling.
1434          */
1435         final void topLevelExecLifo(ForkJoinTask<?> task) {
1436             while (task != null) {
1437                 task.doExec();
1438                 task = localPop();
1439             }
1440         }
1441 
1442         final void topLevelExecFifo(ForkJoinTask<?> task) {
1443             while (task != null) {
1444                 task.doExec();
1445                 task = localPoll();
1446             }
1447         }
1448 
1449         /**
1450          * Deep form of tryUnpush: Traverses from top and removes and
1451          * runs task if present.
1452          */
1453         final void tryRemoveAndExec(ForkJoinTask<?> task, boolean internal) {
1454             ForkJoinTask<?>[] a = array;
1455             int b = base, p = top, s = p - 1, d = p - b, cap;
1456             if (a != null && (cap = a.length) > 0) {
1457                 for (int m = cap - 1, i = s; d > 0; --i, --d) {
1458                     long k; boolean taken;
1459                     ForkJoinTask<?> t = (ForkJoinTask<?>)U.getReference(
1460                         a, k = slotOffset(i & m));
1461                     if (t == null)
1462                         break;
1463                     if (t == task) {
1464                         if (!internal && !tryLockPhase())
1465                             break;                  // fail if locked
1466                         if (taken =
1467                             (top == p &&
1468                              U.compareAndSetReference(a, k, task, null))) {
1469                             if (i == s)             // act as pop
1470                                 updateTop(s);
1471                             else if (i == base)     // act as poll
1472                                 updateBase(i + 1);
1473                             else {                  // swap with top
1474                                 U.putReferenceVolatile(
1475                                     a, k, (ForkJoinTask<?>)
1476                                     U.getAndSetReference(
1477                                         a, slotOffset(s & m), null));
1478                                 updateTop(s);
1479                             }
1480                         }
1481                         if (!internal)
1482                             unlockPhase();
1483                         if (taken)
1484                             task.doExec();
1485                         break;
1486                     }
1487                 }
1488             }
1489         }
1490 
1491         /**
1492          * Tries to pop and run tasks within the target's computation
1493          * until done, not found, or limit exceeded.
1494          *
1495          * @param task root of computation
1496          * @param limit max runs, or zero for no limit
1497          * @return task status if known to be done
1498          */
1499         final int helpComplete(ForkJoinTask<?> task, boolean internal, int limit) {
1500             int status = 0;
1501             if (task != null) {
1502                 outer: for (;;) {
1503                     ForkJoinTask<?>[] a; boolean taken; Object o;
1504                     int stat, p, s, cap;
1505                     if ((stat = task.status) < 0) {
1506                         status = stat;
1507                         break;
1508                     }
1509                     if ((a = array) == null || (cap = a.length) <= 0)
1510                         break;
1511                     long k = slotOffset((cap - 1) & (s = (p = top) - 1));
1512                     if (!((o = U.getReference(a, k)) instanceof CountedCompleter))
1513                         break;
1514                     CountedCompleter<?> t = (CountedCompleter<?>)o, f = t;
1515                     for (int steps = cap;;) {       // bound path
1516                         if (f == task)
1517                             break;
1518                         if ((f = f.completer) == null || --steps == 0)
1519                             break outer;
1520                     }
1521                     if (!internal && !tryLockPhase())
1522                         break;
1523                     if (taken =
1524                         (top == p &&
1525                          U.compareAndSetReference(a, k, t, null)))
1526                         updateTop(s);
1527                     if (!internal)
1528                         unlockPhase();
1529                     if (!taken)
1530                         break;
1531                     t.doExec();
1532                     if (limit != 0 && --limit == 0)
1533                         break;
1534                 }
1535             }
1536             return status;
1537         }
1538 
1539         /**
1540          * Tries to poll and run AsynchronousCompletionTasks until
1541          * none found or blocker is released
1542          *
1543          * @param blocker the blocker
1544          */
1545         final void helpAsyncBlocker(ManagedBlocker blocker) {
1546             for (;;) {
1547                 ForkJoinTask<?> t; ForkJoinTask<?>[] a; int b, cap; long k;
1548                 if ((a = array) == null || (cap = a.length) <= 0)
1549                     break;
1550                 t = (ForkJoinTask<?>)U.getReferenceAcquire(
1551                     a, k = slotOffset((cap - 1) & (b = base)));
1552                 if (t == null) {
1553                     if (top - b <= 0)
1554                         break;
1555                 }
1556                 else if (!(t instanceof CompletableFuture
1557                            .AsynchronousCompletionTask))
1558                     break;
1559                 if (blocker != null && blocker.isReleasable())
1560                     break;
1561                 if (base == b && t != null &&
1562                     U.compareAndSetReference(a, k, t, null)) {
1563                     updateBase(b + 1);
1564                     t.doExec();
1565                 }
1566             }
1567         }
1568 
1569         // misc
1570 
1571         /**
1572          * Cancels all local tasks. Called only by owner.
1573          */
1574         final void cancelTasks() {
1575             for (ForkJoinTask<?> t; (t = localPop()) != null; ) {
1576                 try {
1577                     t.cancel(false);
1578                 } catch (Throwable ignore) {
1579                 }
1580             }
1581         }
1582 
1583         /**
1584          * Returns true if internal and not known to be blocked.
1585          */
1586         final boolean isApparentlyUnblocked() {
1587             Thread wt; Thread.State s;
1588             return ((wt = owner) != null && (phase & IDLE) != 0 &&
1589                     (s = wt.getState()) != Thread.State.BLOCKED &&
1590                     s != Thread.State.WAITING &&
1591                     s != Thread.State.TIMED_WAITING);
1592         }
1593 
1594         static {
1595             U = Unsafe.getUnsafe();
1596             Class<WorkQueue> klass = WorkQueue.class;
1597             PHASE = U.objectFieldOffset(klass, "phase");
1598             BASE = U.objectFieldOffset(klass, "base");
1599             TOP = U.objectFieldOffset(klass, "top");
1600             ARRAY = U.objectFieldOffset(klass, "array");
1601         }
1602     }
1603 
1604     // static fields (initialized in static initializer below)
1605 
1606     /**
1607      * Creates a new ForkJoinWorkerThread. This factory is used unless
1608      * overridden in ForkJoinPool constructors.
1609      */
1610     public static final ForkJoinWorkerThreadFactory
1611         defaultForkJoinWorkerThreadFactory;
1612 
1613     /**
1614      * Common (static) pool. Non-null for public use unless a static
1615      * construction exception, but internal usages null-check on use
1616      * to paranoically avoid potential initialization circularities
1617      * as well as to simplify generated code.
1618      */
1619     static final ForkJoinPool common;
1620 
1621     /**
1622      * Sequence number for creating worker names
1623      */
1624     private static volatile int poolIds;
1625 
1626     /**
1627      * For VirtualThread intrinsics
1628      */
1629     private static final JavaLangAccess JLA;
1630 
1631     // fields declared in order of their likely layout on most VMs
1632     volatile CountDownLatch termination; // lazily constructed
1633     final Predicate<? super ForkJoinPool> saturate;
1634     final ForkJoinWorkerThreadFactory factory;
1635     final UncaughtExceptionHandler ueh;  // per-worker UEH
1636     final SharedThreadContainer container;
1637     final String workerNamePrefix;       // null for common pool
1638     final String poolName;
1639     volatile DelayScheduler delayScheduler;  // lazily constructed
1640     WorkQueue[] queues;                  // main registry
1641     volatile long runState;              // versioned, lockable
1642     final long keepAlive;                // milliseconds before dropping if idle
1643     final long config;                   // static configuration bits
1644     volatile long stealCount;            // collects worker nsteals
1645     volatile long threadIds;             // for worker thread names
1646 
1647     @jdk.internal.vm.annotation.Contended("fjpctl") // segregate
1648     volatile long ctl;                   // main pool control
1649     @jdk.internal.vm.annotation.Contended("fjpctl") // colocate
1650     int parallelism;                     // target number of workers
1651 
1652     // Support for atomic operations
1653     private static final Unsafe U;
1654     private static final long CTL;
1655     private static final long RUNSTATE;
1656     private static final long PARALLELISM;
1657     private static final long THREADIDS;
1658     private static final long TERMINATION;
1659     private static final Object POOLIDS_BASE;
1660     private static final long POOLIDS;
1661 
1662     private boolean compareAndSetCtl(long c, long v) {
1663         return U.compareAndSetLong(this, CTL, c, v);
1664     }
1665     private long compareAndExchangeCtl(long c, long v) {
1666         return U.compareAndExchangeLong(this, CTL, c, v);
1667     }
1668     private long getAndAddCtl(long v) {
1669         return U.getAndAddLong(this, CTL, v);
1670     }
1671     private long incrementThreadIds() {
1672         return U.getAndAddLong(this, THREADIDS, 1L);
1673     }
1674     private static int getAndAddPoolIds(int x) {
1675         return U.getAndAddInt(POOLIDS_BASE, POOLIDS, x);
1676     }
1677     private int getAndSetParallelism(int v) {
1678         return U.getAndSetInt(this, PARALLELISM, v);
1679     }
1680     private int getParallelismOpaque() {
1681         return U.getIntOpaque(this, PARALLELISM);
1682     }
1683     private CountDownLatch cmpExTerminationSignal(CountDownLatch x) {
1684         return (CountDownLatch)
1685             U.compareAndExchangeReference(this, TERMINATION, null, x);
1686     }
1687 
1688     // runState operations
1689 
1690     private long getAndBitwiseOrRunState(long v) { // for status bits
1691         return U.getAndBitwiseOrLong(this, RUNSTATE, v);
1692     }
1693     private boolean casRunState(long c, long v) {
1694         return U.compareAndSetLong(this, RUNSTATE, c, v);
1695     }
1696     private void unlockRunState() {              // increment lock bit
1697         U.getAndAddLong(this, RUNSTATE, RS_LOCK);
1698     }
1699     private long lockRunState() {                // lock and return current state
1700         long s, u;                               // locked when RS_LOCK set
1701         if (((s = runState) & RS_LOCK) == 0L && casRunState(s, u = s + RS_LOCK))
1702             return u;
1703         else
1704             return spinLockRunState();
1705     }
1706     private long spinLockRunState() {            // spin/sleep
1707         for (int waits = 0;;) {
1708             long s, u;
1709             if (((s = runState) & RS_LOCK) == 0L) {
1710                 if (casRunState(s, u = s + RS_LOCK))
1711                     return u;
1712                 waits = 0;
1713             } else if (waits < SPIN_WAITS) {
1714                 ++waits;
1715                 Thread.onSpinWait();
1716             } else {
1717                 if (waits < MIN_SLEEP)
1718                     waits = MIN_SLEEP;
1719                 LockSupport.parkNanos(this, (long)waits);
1720                 if (waits < MAX_SLEEP)
1721                     waits <<= 1;
1722             }
1723         }
1724     }
1725 
1726     static boolean poolIsStopping(ForkJoinPool p) { // Used by ForkJoinTask
1727         return p != null && (p.runState & STOP) != 0L;
1728     }
1729 
1730     // Creating, registering, and deregistering workers
1731 
1732     /**
1733      * Tries to construct and start one worker. Assumes that total
1734      * count has already been incremented as a reservation.  Invokes
1735      * deregisterWorker on any failure.
1736      *
1737      * @return true if successful
1738      */
1739     private boolean createWorker() {
1740         ForkJoinWorkerThreadFactory fac = factory;
1741         SharedThreadContainer ctr = container;
1742         Throwable ex = null;
1743         ForkJoinWorkerThread wt = null;
1744         try {
1745             if ((runState & STOP) == 0L &&  // avoid construction if terminating
1746                 fac != null && (wt = fac.newThread(this)) != null) {
1747                 if (ctr != null)
1748                     ctr.start(wt);
1749                 else
1750                     wt.start();
1751                 return true;
1752             }
1753         } catch (Throwable rex) {
1754             ex = rex;
1755         }
1756         deregisterWorker(wt, ex);
1757         return false;
1758     }
1759 
1760     /**
1761      * Provides a name for ForkJoinWorkerThread constructor.
1762      */
1763     final String nextWorkerThreadName() {
1764         String prefix = workerNamePrefix;
1765         long tid = incrementThreadIds() + 1L;
1766         if (prefix == null) // commonPool has no prefix
1767             prefix = "ForkJoinPool.commonPool-worker-";
1768         return prefix.concat(Long.toString(tid));
1769     }
1770 
1771     /**
1772      * Finishes initializing and records internal queue.
1773      *
1774      * @param w caller's WorkQueue
1775      */
1776     final void registerWorker(WorkQueue w) {
1777         if (w != null) {
1778             w.array = new ForkJoinTask<?>[INITIAL_QUEUE_CAPACITY];
1779             ThreadLocalRandom.localInit();
1780             int seed = w.stackPred = ThreadLocalRandom.getProbe();
1781             int phaseSeq = seed & ~((IDLE << 1) - 1); // initial phase tag
1782             int id = ((seed << 1) | 1) & SMASK; // base of linear-probe-like scan
1783             long stop = lockRunState() & STOP;
1784             try {
1785                 WorkQueue[] qs; int n;
1786                 if (stop == 0L && (qs = queues) != null && (n = qs.length) > 0) {
1787                     for (int k = n, m = n - 1;  ; id += 2) {
1788                         if (qs[id &= m] == null)
1789                             break;
1790                         if ((k -= 2) <= 0) {
1791                             id |= n;
1792                             break;
1793                         }
1794                     }
1795                     w.phase = id | phaseSeq;    // now publishable
1796                     if (id < n)
1797                         qs[id] = w;
1798                     else {                      // expand
1799                         int an = n << 1, am = an - 1;
1800                         WorkQueue[] as = new WorkQueue[an];
1801                         as[id & am] = w;
1802                         for (int j = 1; j < n; j += 2)
1803                             as[j] = qs[j];
1804                         for (int j = 0; j < n; j += 2) {
1805                             WorkQueue q;        // shared queues may move
1806                             if ((q = qs[j]) != null)
1807                                 as[q.phase & EXTERNAL_ID_MASK & am] = q;
1808                         }
1809                         U.storeFence();         // fill before publish
1810                         queues = as;
1811                     }
1812                 }
1813             } finally {
1814                 unlockRunState();
1815             }
1816         }
1817     }
1818 
1819     /**
1820      * Final callback from terminating worker, as well as upon failure
1821      * to construct or start a worker.  Removes record of worker from
1822      * array, and adjusts counts. If pool is shutting down, tries to
1823      * complete termination.
1824      *
1825      * @param wt the worker thread, or null if construction failed
1826      * @param ex the exception causing failure, or null if none
1827      */
1828     final void deregisterWorker(ForkJoinWorkerThread wt, Throwable ex) {
1829         WorkQueue w = null;                // null if not created
1830         int phase = 0;                     // 0 if not registered
1831         if (wt != null && (w = wt.workQueue) != null &&
1832             (phase = w.phase) != 0 && (phase & IDLE) != 0)
1833             releaseWaiters();              // ensure released
1834         if (w == null || w.source != DROPPED) {
1835             long c = ctl;                  // decrement counts
1836             do {} while (c != (c = compareAndExchangeCtl(
1837                                    c, ((RC_MASK & (c - RC_UNIT)) |
1838                                        (TC_MASK & (c - TC_UNIT)) |
1839                                        (LMASK & c)))));
1840         }
1841         if (phase != 0 && w != null) {     // remove index unless terminating
1842             long ns = w.nsteals & 0xffffffffL;
1843             if ((runState & STOP) == 0L) {
1844                 WorkQueue[] qs; int n, i;
1845                 if ((lockRunState() & STOP) == 0L &&
1846                     (qs = queues) != null && (n = qs.length) > 0 &&
1847                     qs[i = phase & SMASK & (n - 1)] == w) {
1848                     qs[i] = null;
1849                     stealCount += ns;      // accumulate steals
1850                 }
1851                 unlockRunState();
1852             }
1853         }
1854         if ((tryTerminate(false, false) & STOP) == 0L &&
1855             phase != 0 && w != null && w.source != DROPPED) {
1856             w.cancelTasks();               // clean queue
1857             signalWork(null, 0);           // possibly replace
1858         }
1859         if (ex != null)
1860             ForkJoinTask.rethrow(ex);
1861     }
1862 
1863     /**
1864      * Releases an idle worker, or creates one if not enough exist,
1865      * giving up if array a is nonnull and task at a[k] already taken.
1866      */
1867     final void signalWork(ForkJoinTask<?>[] a, int k) {
1868         int pc = parallelism;
1869         for (long c = ctl;;) {
1870             WorkQueue[] qs = queues;
1871             long ac = (c + RC_UNIT) & RC_MASK, nc;
1872             int sp = (int)c, i = sp & SMASK;
1873             if ((short)(c >>> RC_SHIFT) >= pc)
1874                 break;
1875             if (qs == null)
1876                 break;
1877             if (qs.length <= i)
1878                 break;
1879             WorkQueue w = qs[i], v = null;
1880             if (sp == 0) {
1881                 if ((short)(c >>> TC_SHIFT) >= pc)
1882                     break;
1883                 nc = ((c + TC_UNIT) & TC_MASK) | ac;
1884             }
1885             else if ((v = w) == null)
1886                 break;
1887             else
1888                 nc = (v.stackPred & LMASK) | (c & TC_MASK) | ac;
1889             if (a != null && k < a.length && k >= 0 && a[k] == null)
1890                 break;
1891             if (c == (c = ctl) && c == (c = compareAndExchangeCtl(c, nc))) {
1892                 if (v == null)
1893                     createWorker();
1894                 else {
1895                     v.phase = sp;
1896                     if (v.parking != 0)
1897                         U.unpark(v.owner);
1898                 }
1899                 break;
1900             }
1901         }
1902     }
1903 
1904     /**
1905      * Releases all waiting workers. Called only during shutdown.
1906      */
1907     private void releaseWaiters() {
1908         for (long c = ctl;;) {
1909             WorkQueue[] qs; WorkQueue v; int sp, i;
1910             if ((sp = (int)c) == 0 || (qs = queues) == null ||
1911                 qs.length <= (i = sp & SMASK) || (v = qs[i]) == null)
1912                 break;
1913             if (c == (c = compareAndExchangeCtl(
1914                           c, ((UMASK & (c + RC_UNIT)) | (c & TC_MASK) |
1915                               (v.stackPred & LMASK))))) {
1916                 v.phase = sp;
1917                 if (v.parking != 0)
1918                     U.unpark(v.owner);
1919             }
1920         }
1921     }
1922 
1923     /**
1924      * Internal version of isQuiescent and related functionality.
1925      * @return positive if stopping, nonnegative if terminating or all
1926      * workers are inactive and submission queues are empty and
1927      * unlocked; if so, setting STOP if shutdown is enabled
1928      */
1929     private int quiescent() {
1930         for (;;) {
1931             long phaseSum = 0L;
1932             boolean swept = false;
1933             for (long e, prevRunState = 0L; ; prevRunState = e) {
1934                 DelayScheduler ds;
1935                 long c = ctl;
1936                 if (((e = runState) & STOP) != 0L)
1937                     return 1;                             // terminating
1938                 else if ((c & RC_MASK) > 0L)
1939                     return -1;                            // at least one active
1940                 else if (!swept || e != prevRunState || (e & RS_LOCK) != 0) {
1941                     long sum = c;
1942                     WorkQueue[] qs = queues;
1943                     int n = (qs == null) ? 0 : qs.length;
1944                     for (int i = 0; i < n; ++i) {         // scan queues
1945                         WorkQueue q;
1946                         if ((q = qs[i]) != null) {
1947                             int p = q.phase, s = q.top, b = q.base;
1948                             sum += (p & 0xffffffffL) | ((long)b << 32);
1949                             if ((p & IDLE) == 0 || s - b > 0)
1950                                 return -1;
1951                         }
1952                     }
1953                     swept = (phaseSum == (phaseSum = sum));
1954                 }
1955                 else if ((e & SHUTDOWN) == 0)
1956                     return 0;
1957                 else if ((ds = delayScheduler) != null && !ds.canShutDown())
1958                     return 0;
1959                 else if (compareAndSetCtl(c, c) && casRunState(e, e | STOP))
1960                     return 1;                             // enable termination
1961                 else
1962                     break;                                // restart
1963             }
1964         }
1965     }
1966 
1967     /**
1968      * Top-level runloop for workers, called by ForkJoinWorkerThread.run.
1969      * See above for explanation.
1970      *
1971      * @param w caller's WorkQueue (may be null on failed initialization)
1972      */
1973     final void runWorker(WorkQueue w) {
1974         if (w != null) {
1975             int r = w.stackPred;                          // seed from registerWorker
1976             int fifo = (int)config & FIFO;
1977             int nsteals = 0;                              // shadow w.nsteals
1978             boolean rescan = true;
1979             WorkQueue[] qs; int n;
1980             while ((rescan || deactivate(w) == 0) && (runState & STOP) == 0L &&
1981                    (qs = queues) != null && (n = qs.length) > 0) {
1982                 rescan = false;
1983                 int i = r, step = (r >>> 16) | 1;
1984                 r ^= r << 13; r ^= r >>> 17; r ^= r << 5; // xorshift
1985                 scan: for (int j = n << 1; j != 0; --j, i += step) { // 2 sweeps
1986                     WorkQueue q; int qid;
1987                     if ((q = qs[qid = i & (n - 1)]) != null) {
1988                         for (;;) {                        // poll queue q
1989                             ForkJoinTask<?>[] a; int cap, b, m, nb, nk;
1990                             if ((a = q.array) == null || (cap = a.length) <= 0)
1991                                 break;
1992                             long bp = slotOffset((m = cap - 1) & (b = q.base));
1993                             long np = slotOffset(nk = m & (nb = b + 1));
1994                             ForkJoinTask<?> t = (ForkJoinTask<?>)
1995                                 U.getReferenceAcquire(a, bp);
1996                             if (q.array != a || q.base != b ||
1997                                 U.getReference(a, bp) != t)
1998                                 continue;                 // inconsistent
1999                             if (t == null) {
2000                                 if (rescan) {             // end of run
2001                                     w.nsteals = nsteals;
2002                                     break scan;
2003                                 }
2004                                 if (U.getReference(a, np) != null) {
2005                                     rescan = true;        // stalled; reorder scan
2006                                     break scan;
2007                                 }
2008                                 break;                    // probably empty
2009                             }
2010                             if (U.compareAndSetReference(a, bp, t, null)) {
2011                                 q.base = nb;
2012                                 Object nt = U.getReferenceAcquire(a, np);
2013                                 if (!rescan) {            // begin run
2014                                     rescan = true;
2015                                     w.source = qid;
2016                                 }
2017                                 ++nsteals;
2018                                 if (nt != null &&         // confirm a[nk]
2019                                     U.getReference(a, np) == nt)
2020                                     signalWork(a, nk);    // propagate
2021                                 if (fifo != 0)            // run t & its subtasks
2022                                     w.topLevelExecFifo(t);
2023                                 else
2024                                     w.topLevelExecLifo(t);
2025                             }
2026                         }
2027                     }
2028                 }
2029             }
2030         }
2031     }
2032 
2033     /**
2034      * Deactivates and awaits signal or termination.
2035      *
2036      * @param w the work queue
2037      * @return zero if now active
2038      */
2039     private int deactivate(WorkQueue w) {
2040         int idle = 1;
2041         if (w != null) {                        // always true; hoist checks
2042             int p = w.phase, idlePhase = p | IDLE, activePhase = p + (IDLE << 1);
2043             long pc = ctl, qc = (activePhase & LMASK) | ((pc - RC_UNIT) & UMASK);
2044             w.stackPred = (int)pc;              // set ctl stack link
2045             w.phase = idlePhase;
2046             if (!compareAndSetCtl(pc, qc)) {    // try to enqueue
2047                 w.phase = p;                    // back out on contention
2048                 idle = 0;
2049             }
2050             WorkQueue[] qs; int n; long e;
2051             if (idle != 0 && ((e = runState) & STOP) == 0 && // quiescence checks
2052                 ((e & SHUTDOWN) == 0L || (qc & RC_MASK) > 0L || quiescent() <= 0) &&
2053                 (qs = queues) != null && (n = qs.length) > 1) {
2054                 long psp = pc & LMASK;          // ctl predecessor prefix
2055                 for (int i = 1; i < n; ++i) {   // scan; stagger origins
2056                     WorkQueue q; long c;        // missed signal check
2057                     if ((q = qs[(activePhase + i) & (n - 1)]) != null &&
2058                         q.top - q.base > 0) {
2059                         if ((idle = w.phase - activePhase) != 0 &&
2060                             (int)(c = ctl) == activePhase &&
2061                             compareAndSetCtl(c, psp | ((c + RC_UNIT) & UMASK))) {
2062                             w.phase = activePhase;
2063                             idle = 0;           // reactivated
2064                         }                       // else ineligible or lost race
2065                         break;
2066                     }
2067                 }
2068                 if (idle != 0 && (idle = w.phase - activePhase) != 0)
2069                     idle = awaitWork(w, activePhase, n);
2070             }
2071         }
2072         return idle;
2073     }
2074 
2075     /**
2076      * Awaits signal or termination.
2077      *
2078      * @param w the work queue
2079      * @param activePhase w's next active phase
2080      * @param qsize current size of queues array
2081      * @return zero if now active
2082      */
2083     private int awaitWork(WorkQueue w, int activePhase, int qsize) {
2084         int idle = 1;
2085         if ((runState & STOP) == 0L && w != null) {
2086             int cfg = w.config;
2087             long waitTime = (w.source == INVALID_ID) ? 0L : keepAlive;
2088             long deadline = waitTime + System.currentTimeMillis();
2089             int spins = (qsize << 1) | (qsize - 1); // approx traversal cost
2090             if ((cfg & CLEAR_TLS) != 0 &&     // instanceof check always true
2091                 Thread.currentThread() instanceof ForkJoinWorkerThread f)
2092                 f.resetThreadLocals();        // clear while accessing thread state
2093             LockSupport.setCurrentBlocker(this);
2094             for (;;) {
2095                 Thread.interrupted();         // clear status
2096                 int s = spins;
2097                 while ((idle = w.phase - activePhase) != 0 && --s != 0)
2098                     Thread.onSpinWait();      // spin before/between parks
2099                 if (idle == 0)
2100                     break;
2101                 if ((runState & STOP) != 0L)
2102                     break;
2103                 boolean trimmable = false;    // use timed wait if trimmable
2104                 long d = 0L, c;
2105                 if (((c = ctl) & RC_MASK) == 0L && (int)c == activePhase) {
2106                     if (deadline - System.currentTimeMillis() <= TIMEOUT_SLOP) {
2107                         if (tryTrim(w, c, activePhase))
2108                             break;
2109                         continue;             // lost race to trim
2110                     }
2111                     d = deadline;
2112                     trimmable = true;
2113                 }
2114                 w.parking = 1;                // enable unpark and recheck
2115                 if ((idle = w.phase - activePhase) != 0)
2116                     U.park(trimmable, d);
2117                 w.parking = 0;                // close unpark window
2118                 if (idle == 0 || (idle = w.phase - activePhase) == 0)
2119                     break;
2120             }
2121             LockSupport.setCurrentBlocker(null);
2122         }
2123         return idle;
2124     }
2125 
2126     /**
2127      * Tries to remove and deregister worker after timeout, and release
2128      * another to do the same unless new tasks are found.
2129      */
2130     private boolean tryTrim(WorkQueue w, long c, int activePhase) {
2131         if (w != null) {
2132             int vp, i; WorkQueue[] vs; WorkQueue v;
2133             long nc = ((w.stackPred & LMASK) |
2134                        ((RC_MASK & c) | (TC_MASK & (c - TC_UNIT))));
2135             if (compareAndSetCtl(c, nc)) {
2136                 w.source = DROPPED;
2137                 w.phase = activePhase;
2138                 if ((vp = (int)nc) != 0 && (vs = queues) != null &&
2139                     vs.length > (i = vp & SMASK) && (v = vs[i]) != null &&
2140                     compareAndSetCtl(           // try to wake up next waiter
2141                         nc, ((v.stackPred & LMASK) |
2142                              ((UMASK & (nc + RC_UNIT)) | (nc & TC_MASK))))) {
2143                     v.source = INVALID_ID;      // enable cascaded timeouts
2144                     v.phase = vp;
2145                     U.unpark(v.owner);
2146                 }
2147                 return true;
2148             }
2149         }
2150         return false;
2151     }
2152 
2153     /**
2154      * Scans for and returns a polled task, if available.  Used only
2155      * for untracked polls. Begins scan at a random index to avoid
2156      * systematic unfairness.
2157      *
2158      * @param submissionsOnly if true, only scan submission queues
2159      */
2160     private ForkJoinTask<?> pollScan(boolean submissionsOnly) {
2161         if ((runState & STOP) == 0L) {
2162             WorkQueue[] qs; int n; WorkQueue q; ForkJoinTask<?> t;
2163             int r = ThreadLocalRandom.nextSecondarySeed();
2164             if (submissionsOnly)                 // even indices only
2165                 r &= ~1;
2166             int step = (submissionsOnly) ? 2 : 1;
2167             if ((qs = queues) != null && (n = qs.length) > 0) {
2168                 for (int i = n; i > 0; i -= step, r += step) {
2169                     if ((q = qs[r & (n - 1)]) != null &&
2170                         (t = q.poll()) != null)
2171                         return t;
2172                 }
2173             }
2174         }
2175         return null;
2176     }
2177 
2178     /**
2179      * Tries to decrement counts (sometimes implicitly) and possibly
2180      * arrange for a compensating worker in preparation for
2181      * blocking. May fail due to interference, in which case -1 is
2182      * returned so caller may retry. A zero return value indicates
2183      * that the caller doesn't need to re-adjust counts when later
2184      * unblocked.
2185      *
2186      * @param c incoming ctl value
2187      * @return UNCOMPENSATE: block then adjust, 0: block, -1 : retry
2188      */
2189     private int tryCompensate(long c) {
2190         Predicate<? super ForkJoinPool> sat;
2191         long b = config;
2192         int pc        = parallelism,                    // unpack fields
2193             minActive = (short)(b >>> RC_SHIFT),
2194             maxTotal  = (short)(b >>> TC_SHIFT) + pc,
2195             active    = (short)(c >>> RC_SHIFT),
2196             total     = (short)(c >>> TC_SHIFT),
2197             sp        = (int)c,
2198             stat      = -1;                             // default retry return
2199         if (sp != 0 && active <= pc) {                  // activate idle worker
2200             WorkQueue[] qs; WorkQueue v; int i;
2201             if ((qs = queues) != null && qs.length > (i = sp & SMASK) &&
2202                 (v = qs[i]) != null &&
2203                 compareAndSetCtl(c, (c & UMASK) | (v.stackPred & LMASK))) {
2204                 v.phase = sp;
2205                 if (v.parking != 0)
2206                     U.unpark(v.owner);
2207                 stat = UNCOMPENSATE;
2208             }
2209         }
2210         else if (active > minActive && total >= pc) {   // reduce active workers
2211             if (compareAndSetCtl(c, ((c - RC_UNIT) & RC_MASK) | (c & ~RC_MASK)))
2212                 stat = UNCOMPENSATE;
2213         }
2214         else if (total < maxTotal && total < MAX_CAP) { // try to expand pool
2215             long nc = ((c + TC_UNIT) & TC_MASK) | (c & ~TC_MASK);
2216             if ((runState & STOP) != 0L)                // terminating
2217                 stat = 0;
2218             else if (compareAndSetCtl(c, nc))
2219                 stat = createWorker() ? UNCOMPENSATE : 0;
2220         }
2221         else if (!compareAndSetCtl(c, c))               // validate
2222             ;
2223         else if ((sat = saturate) != null && sat.test(this))
2224             stat = 0;
2225         else
2226             throw new RejectedExecutionException(
2227                 "Thread limit exceeded replacing blocked worker");
2228         return stat;
2229     }
2230 
2231     /**
2232      * Readjusts RC count; called from ForkJoinTask after blocking.
2233      */
2234     final void uncompensate() {
2235         getAndAddCtl(RC_UNIT);
2236     }
2237 
2238     /**
2239      * Helps if possible until the given task is done.  Processes
2240      * compatible local tasks and scans other queues for task produced
2241      * by w's stealers; returning compensated blocking sentinel if
2242      * none are found.
2243      *
2244      * @param task the task
2245      * @param w caller's WorkQueue
2246      * @param internal true if w is owned by a ForkJoinWorkerThread
2247      * @return task status on exit, or UNCOMPENSATE for compensated blocking
2248      */
2249     final int helpJoin(ForkJoinTask<?> task, WorkQueue w, boolean internal) {
2250         if (w != null)
2251             w.tryRemoveAndExec(task, internal);
2252         int s = 0;
2253         if (task != null && (s = task.status) >= 0 && internal && w != null) {
2254             int wid = w.phase & SMASK, r = wid + 2, wsrc = w.source;
2255             long sctl = 0L;                             // track stability
2256             outer: for (boolean rescan = true;;) {
2257                 if ((s = task.status) < 0)
2258                     break;
2259                 if (!rescan) {
2260                     if ((runState & STOP) != 0L)
2261                         break;
2262                     if (sctl == (sctl = ctl) && (s = tryCompensate(sctl)) >= 0)
2263                         break;
2264                 }
2265                 rescan = false;
2266                 WorkQueue[] qs = queues;
2267                 int n = (qs == null) ? 0 : qs.length;
2268                 scan: for (int l = n >>> 1; l > 0; --l, r += 2) {
2269                     int j; WorkQueue q;
2270                     if ((q = qs[j = r & SMASK & (n - 1)]) != null) {
2271                         for (;;) {
2272                             ForkJoinTask<?> t; ForkJoinTask<?>[] a;
2273                             boolean eligible = false;
2274                             int sq = q.source, b, cap; long k;
2275                             if ((a = q.array) == null || (cap = a.length) <= 0)
2276                                 break;
2277                             t = (ForkJoinTask<?>)U.getReferenceAcquire(
2278                                 a, k = slotOffset((cap - 1) & (b = q.base)));
2279                             if (t == task)
2280                                 eligible = true;
2281                             else if (t != null) {       // check steal chain
2282                                 for (int v = sq, d = cap;;) {
2283                                     WorkQueue p;
2284                                     if (v == wid) {
2285                                         eligible = true;
2286                                         break;
2287                                     }
2288                                     if ((v & 1) == 0 || // external or none
2289                                         --d < 0 ||      // bound depth
2290                                         (p = qs[v & (n - 1)]) == null)
2291                                         break;
2292                                     v = p.source;
2293                                 }
2294                             }
2295                             if ((s = task.status) < 0)
2296                                 break outer;            // validate
2297                             if (q.source == sq && q.base == b &&
2298                                 U.getReference(a, k) == t) {
2299                                 if (!eligible) {        // revisit if nonempty
2300                                     if (!rescan && t == null && q.top - b > 0)
2301                                         rescan = true;
2302                                     break;
2303                                 }
2304                                 if (U.compareAndSetReference(a, k, t, null)) {
2305                                     q.base = b + 1;
2306                                     w.source = j;    // volatile write
2307                                     t.doExec();
2308                                     w.source = wsrc;
2309                                     rescan = true;   // restart at index r
2310                                     break scan;
2311                                 }
2312                             }
2313                         }
2314                     }
2315                 }
2316             }
2317         }
2318         return s;
2319     }
2320 
2321     /**
2322      * Version of helpJoin for CountedCompleters.
2323      *
2324      * @param task root of computation (only called when a CountedCompleter)
2325      * @param w caller's WorkQueue
2326      * @param internal true if w is owned by a ForkJoinWorkerThread
2327      * @return task status on exit, or UNCOMPENSATE for compensated blocking
2328      */
2329     final int helpComplete(ForkJoinTask<?> task, WorkQueue w, boolean internal) {
2330         int s = 0;
2331         if (task != null && (s = task.status) >= 0 && w != null) {
2332             int r = w.phase + 1;                          // for indexing
2333             long sctl = 0L;                               // track stability
2334             outer: for (boolean rescan = true, locals = true;;) {
2335                 if (locals && (s = w.helpComplete(task, internal, 0)) < 0)
2336                     break;
2337                 if ((s = task.status) < 0)
2338                     break;
2339                 if (!rescan) {
2340                     if ((runState & STOP) != 0L)
2341                         break;
2342                     if (sctl == (sctl = ctl) &&
2343                         (!internal || (s = tryCompensate(sctl)) >= 0))
2344                         break;
2345                 }
2346                 rescan = locals = false;
2347                 WorkQueue[] qs = queues;
2348                 int n = (qs == null) ? 0 : qs.length;
2349                 scan: for (int l = n; l > 0; --l, ++r) {
2350                     int j; WorkQueue q;
2351                     if ((q = qs[j = r & SMASK & (n - 1)]) != null) {
2352                         for (;;) {
2353                             ForkJoinTask<?> t; ForkJoinTask<?>[] a;
2354                             int b, cap, nb; long k;
2355                             boolean eligible = false;
2356                             if ((a = q.array) == null || (cap = a.length) <= 0)
2357                                 break;
2358                             t = (ForkJoinTask<?>)U.getReferenceAcquire(
2359                                 a, k = slotOffset((cap - 1) & (b = q.base)));
2360                             if (t instanceof CountedCompleter) {
2361                                 CountedCompleter<?> f = (CountedCompleter<?>)t;
2362                                 for (int steps = cap; steps > 0; --steps) {
2363                                     if (f == task) {
2364                                         eligible = true;
2365                                         break;
2366                                     }
2367                                     if ((f = f.completer) == null)
2368                                         break;
2369                                 }
2370                             }
2371                             if ((s = task.status) < 0)    // validate
2372                                 break outer;
2373                             if (q.base == b) {
2374                                 if (eligible) {
2375                                     if (U.compareAndSetReference(
2376                                             a, k, t, null)) {
2377                                         q.updateBase(b + 1);
2378                                         t.doExec();
2379                                         locals = rescan = true;
2380                                         break scan;
2381                                     }
2382                                 }
2383                                 else if (U.getReference(a, k) == t) {
2384                                     if (!rescan && t == null && q.top - b > 0)
2385                                         rescan = true;    // revisit
2386                                     break;
2387                                 }
2388                             }
2389                         }
2390                     }
2391                 }
2392             }
2393         }
2394         return s;
2395      }
2396 
2397     /**
2398      * Runs tasks until all workers are inactive and no tasks are
2399      * found. Rather than blocking when tasks cannot be found, rescans
2400      * until all others cannot find tasks either.
2401      *
2402      * @param nanos max wait time (Long.MAX_VALUE if effectively untimed)
2403      * @param interruptible true if return on interrupt
2404      * @return positive if quiescent, negative if interrupted, else 0
2405      */
2406     private int helpQuiesce(WorkQueue w, long nanos, boolean interruptible) {
2407         int phase; // w.phase inactive bit set when temporarily quiescent
2408         if (w == null || ((phase = w.phase) & IDLE) != 0)
2409             return 0;
2410         int wsrc = w.source;
2411         long startTime = System.nanoTime();
2412         long maxSleep = Math.min(nanos >>> 8, MAX_SLEEP); // approx 1% nanos
2413         long prevSum = 0L;
2414         int activePhase = phase, inactivePhase = phase + IDLE;
2415         int r = phase + 1, waits = 0, returnStatus = 1;
2416         boolean locals = true;
2417         for (long e = runState;;) {
2418             if ((e & STOP) != 0L)
2419                 break;                      // terminating
2420             if (interruptible && Thread.interrupted()) {
2421                 returnStatus = -1;
2422                 break;
2423             }
2424             if (locals) {                   // run local tasks before (re)polling
2425                 locals = false;
2426                 for (ForkJoinTask<?> u; (u = w.nextLocalTask()) != null;)
2427                     u.doExec();
2428             }
2429             WorkQueue[] qs = queues;
2430             int n = (qs == null) ? 0 : qs.length;
2431             long phaseSum = 0L;
2432             boolean rescan = false, busy = false;
2433             scan: for (int l = n; l > 0; --l, ++r) {
2434                 int j; WorkQueue q;
2435                 if ((q = qs[j = r & SMASK & (n - 1)]) != null && q != w) {
2436                     for (;;) {
2437                         ForkJoinTask<?> t; ForkJoinTask<?>[] a;
2438                         int b, cap; long k;
2439                         if ((a = q.array) == null || (cap = a.length) <= 0)
2440                             break;
2441                         t = (ForkJoinTask<?>)U.getReferenceAcquire(
2442                             a, k = slotOffset((cap - 1) & (b = q.base)));
2443                         if (t != null && phase == inactivePhase) // reactivate
2444                             w.phase = phase = activePhase;
2445                         if (q.base == b && U.getReference(a, k) == t) {
2446                             int nb = b + 1;
2447                             if (t == null) {
2448                                 if (!rescan) {
2449                                     int qp = q.phase, mq = qp & (IDLE | 1);
2450                                     phaseSum += qp;
2451                                     if (mq == 0 || q.top - b > 0)
2452                                         rescan = true;
2453                                     else if (mq == 1)
2454                                         busy = true;
2455                                 }
2456                                 break;
2457                             }
2458                             if (U.compareAndSetReference(a, k, t, null)) {
2459                                 q.base = nb;
2460                                 w.source = j; // volatile write
2461                                 t.doExec();
2462                                 w.source = wsrc;
2463                                 rescan = locals = true;
2464                                 break scan;
2465                             }
2466                         }
2467                     }
2468                 }
2469             }
2470             if (e != (e = runState) || prevSum != (prevSum = phaseSum) ||
2471                 rescan || (e & RS_LOCK) != 0L)
2472                 ;                   // inconsistent
2473             else if (!busy)
2474                 break;
2475             else if (phase == activePhase) {
2476                 waits = 0;          // recheck, then sleep
2477                 w.phase = phase = inactivePhase;
2478             }
2479             else if (System.nanoTime() - startTime > nanos) {
2480                 returnStatus = 0;   // timed out
2481                 break;
2482             }
2483             else if (waits == 0)   // same as spinLockRunState except
2484                 waits = MIN_SLEEP; //   with rescan instead of onSpinWait
2485             else {
2486                 LockSupport.parkNanos(this, (long)waits);
2487                 if (waits < maxSleep)
2488                     waits <<= 1;
2489             }
2490         }
2491         w.phase = activePhase;
2492         return returnStatus;
2493     }
2494 
2495     /**
2496      * Helps quiesce from external caller until done, interrupted, or timeout
2497      *
2498      * @param nanos max wait time (Long.MAX_VALUE if effectively untimed)
2499      * @param interruptible true if return on interrupt
2500      * @return positive if quiescent, negative if interrupted, else 0
2501      */
2502     private int externalHelpQuiesce(long nanos, boolean interruptible) {
2503         if (quiescent() < 0) {
2504             long startTime = System.nanoTime();
2505             long maxSleep = Math.min(nanos >>> 8, MAX_SLEEP);
2506             for (int waits = 0;;) {
2507                 ForkJoinTask<?> t;
2508                 if (interruptible && Thread.interrupted())
2509                     return -1;
2510                 else if ((t = pollScan(false)) != null) {
2511                     waits = 0;
2512                     t.doExec();
2513                 }
2514                 else if (quiescent() >= 0)
2515                     break;
2516                 else if (System.nanoTime() - startTime > nanos)
2517                     return 0;
2518                 else if (waits == 0)
2519                     waits = MIN_SLEEP;
2520                 else {
2521                     LockSupport.parkNanos(this, (long)waits);
2522                     if (waits < maxSleep)
2523                         waits <<= 1;
2524                 }
2525             }
2526         }
2527         return 1;
2528     }
2529 
2530     /**
2531      * Helps quiesce from either internal or external caller
2532      *
2533      * @param pool the pool to use, or null if any
2534      * @param nanos max wait time (Long.MAX_VALUE if effectively untimed)
2535      * @param interruptible true if return on interrupt
2536      * @return positive if quiescent, negative if interrupted, else 0
2537      */
2538     static final int helpQuiescePool(ForkJoinPool pool, long nanos,
2539                                      boolean interruptible) {
2540         Thread t; ForkJoinPool p; ForkJoinWorkerThread wt;
2541         if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread &&
2542             (p = (wt = (ForkJoinWorkerThread)t).pool) != null &&
2543             (p == pool || pool == null))
2544             return p.helpQuiesce(wt.workQueue, nanos, interruptible);
2545         else if ((p = pool) != null || (p = common) != null)
2546             return p.externalHelpQuiesce(nanos, interruptible);
2547         else
2548             return 0;
2549     }
2550 
2551     /**
2552      * Gets and removes a local or stolen task for the given worker.
2553      *
2554      * @return a task, if available
2555      */
2556     final ForkJoinTask<?> nextTaskFor(WorkQueue w) {
2557         ForkJoinTask<?> t;
2558         if (w == null || (t = w.nextLocalTask()) == null)
2559             t = pollScan(false);
2560         return t;
2561     }
2562 
2563     // External operations
2564 
2565     /**
2566      * Finds and locks a WorkQueue for an external submitter, or
2567      * throws RejectedExecutionException if shutdown
2568      * @param rejectOnShutdown true if RejectedExecutionException
2569      *        should be thrown when shutdown
2570      */
2571     final WorkQueue externalSubmissionQueue(boolean rejectOnShutdown) {
2572         int r;
2573         if ((r = ThreadLocalRandom.getProbe()) == 0) {
2574             ThreadLocalRandom.localInit();   // initialize caller's probe
2575             r = ThreadLocalRandom.getProbe();
2576         }
2577         for (;;) {
2578             WorkQueue q; WorkQueue[] qs; int n, id, i;
2579             if ((qs = queues) == null || (n = qs.length) <= 0)
2580                 break;
2581             if ((q = qs[i = (id = r & EXTERNAL_ID_MASK) & (n - 1)]) == null) {
2582                 WorkQueue newq = new WorkQueue(null, id, 0, false);
2583                 lockRunState();
2584                 if (qs[i] == null && queues == qs)
2585                     q = qs[i] = newq;         // else lost race to install
2586                 unlockRunState();
2587             }
2588             if (q != null && q.tryLockPhase()) {
2589                 if (rejectOnShutdown && (runState & SHUTDOWN) != 0L) {
2590                     q.unlockPhase();          // check while q lock held
2591                     break;
2592                 }
2593                 return q;
2594             }
2595             r = ThreadLocalRandom.advanceProbe(r); // move
2596         }
2597         throw new RejectedExecutionException();
2598     }
2599 
2600     private <T> ForkJoinTask<T> poolSubmit(boolean signalIfEmpty, ForkJoinTask<T> task) {
2601         Thread t; ForkJoinWorkerThread wt; WorkQueue q; boolean internal;
2602         if (((t = JLA.currentCarrierThread()) instanceof ForkJoinWorkerThread) &&
2603             (wt = (ForkJoinWorkerThread)t).pool == this) {
2604             internal = true;
2605             q = wt.workQueue;
2606         }
2607         else {                     // find and lock queue
2608             internal = false;
2609             q = externalSubmissionQueue(true);
2610         }
2611         q.push(task, signalIfEmpty ? this : null, internal);
2612         return task;
2613     }
2614 
2615     /**
2616      * Returns queue for an external thread, if one exists that has
2617      * possibly ever submitted to the given pool (nonzero probe), or
2618      * null if none.
2619      */
2620     static WorkQueue externalQueue(ForkJoinPool p) {
2621         WorkQueue[] qs; int n;
2622         int r = ThreadLocalRandom.getProbe();
2623         return (p != null && (qs = p.queues) != null &&
2624                 (n = qs.length) > 0 && r != 0) ?
2625             qs[r & EXTERNAL_ID_MASK & (n - 1)] : null;
2626     }
2627 
2628     /**
2629      * Returns external queue for common pool.
2630      */
2631     static WorkQueue commonQueue() {
2632         return externalQueue(common);
2633     }
2634 
2635     /**
2636      * If the given executor is a ForkJoinPool, poll and execute
2637      * AsynchronousCompletionTasks from worker's queue until none are
2638      * available or blocker is released.
2639      */
2640     static void helpAsyncBlocker(Executor e, ManagedBlocker blocker) {
2641         WorkQueue w = null; Thread t; ForkJoinWorkerThread wt;
2642         if (((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) &&
2643             (wt = (ForkJoinWorkerThread)t).pool == e)
2644             w = wt.workQueue;
2645         else if (e instanceof ForkJoinPool)
2646             w = externalQueue((ForkJoinPool)e);
2647         if (w != null)
2648             w.helpAsyncBlocker(blocker);
2649     }
2650 
2651     /**
2652      * Returns a cheap heuristic guide for task partitioning when
2653      * programmers, frameworks, tools, or languages have little or no
2654      * idea about task granularity.  In essence, by offering this
2655      * method, we ask users only about tradeoffs in overhead vs
2656      * expected throughput and its variance, rather than how finely to
2657      * partition tasks.
2658      *
2659      * In a steady state strict (tree-structured) computation, each
2660      * thread makes available for stealing enough tasks for other
2661      * threads to remain active. Inductively, if all threads play by
2662      * the same rules, each thread should make available only a
2663      * constant number of tasks.
2664      *
2665      * The minimum useful constant is just 1. But using a value of 1
2666      * would require immediate replenishment upon each steal to
2667      * maintain enough tasks, which is infeasible.  Further,
2668      * partitionings/granularities of offered tasks should minimize
2669      * steal rates, which in general means that threads nearer the top
2670      * of computation tree should generate more than those nearer the
2671      * bottom. In perfect steady state, each thread is at
2672      * approximately the same level of computation tree. However,
2673      * producing extra tasks amortizes the uncertainty of progress and
2674      * diffusion assumptions.
2675      *
2676      * So, users will want to use values larger (but not much larger)
2677      * than 1 to both smooth over transient shortages and hedge
2678      * against uneven progress; as traded off against the cost of
2679      * extra task overhead. We leave the user to pick a threshold
2680      * value to compare with the results of this call to guide
2681      * decisions, but recommend values such as 3.
2682      *
2683      * When all threads are active, it is on average OK to estimate
2684      * surplus strictly locally. In steady-state, if one thread is
2685      * maintaining say 2 surplus tasks, then so are others. So we can
2686      * just use estimated queue length.  However, this strategy alone
2687      * leads to serious mis-estimates in some non-steady-state
2688      * conditions (ramp-up, ramp-down, other stalls). We can detect
2689      * many of these by further considering the number of "idle"
2690      * threads, that are known to have zero queued tasks, so
2691      * compensate by a factor of (#idle/#active) threads.
2692      */
2693     static int getSurplusQueuedTaskCount() {
2694         Thread t; ForkJoinWorkerThread wt; ForkJoinPool pool; WorkQueue q;
2695         if (((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) &&
2696             (pool = (wt = (ForkJoinWorkerThread)t).pool) != null &&
2697             (q = wt.workQueue) != null) {
2698             int n = q.top - q.base;
2699             int p = pool.parallelism;
2700             int a = (short)(pool.ctl >>> RC_SHIFT);
2701             return n - (a > (p >>>= 1) ? 0 :
2702                         a > (p >>>= 1) ? 1 :
2703                         a > (p >>>= 1) ? 2 :
2704                         a > (p >>>= 1) ? 4 :
2705                         8);
2706         }
2707         return 0;
2708     }
2709 
2710     // Termination
2711 
2712     /**
2713      * Possibly initiates and/or completes pool termination.
2714      *
2715      * @param now if true, unconditionally terminate, else only
2716      * if no work and no active workers
2717      * @param enable if true, terminate when next possible
2718      * @return runState on exit
2719      */
2720     private long tryTerminate(boolean now, boolean enable) {
2721         long e, isShutdown, ps;
2722         if (((e = runState) & TERMINATED) != 0L)
2723             now = false;
2724         else if ((e & STOP) != 0L)
2725             now = true;
2726         else if (now) {
2727             if (((ps = getAndBitwiseOrRunState(SHUTDOWN|STOP) & STOP)) == 0L) {
2728                 if ((ps & RS_LOCK) != 0L) {
2729                     spinLockRunState(); // ensure queues array stable after stop
2730                     unlockRunState();
2731                 }
2732                 interruptAll();
2733             }
2734         }
2735         else if ((isShutdown = (e & SHUTDOWN)) != 0L || enable) {
2736             long quiet; DelayScheduler ds;
2737             if (isShutdown == 0L)
2738                 getAndBitwiseOrRunState(SHUTDOWN);
2739             if ((quiet = quiescent()) > 0)
2740                 now = true;
2741             else if (quiet == 0 && (ds = delayScheduler) != null)
2742                 ds.signal();
2743         }
2744 
2745         if (now) {
2746             DelayScheduler ds;
2747             releaseWaiters();
2748             if ((ds = delayScheduler) != null)
2749                 ds.signal();
2750             for (;;) {
2751                 if (((e = runState) & CLEANED) == 0L) {
2752                     boolean clean = cleanQueues();
2753                     if (((e = runState) & CLEANED) == 0L && clean)
2754                         e = getAndBitwiseOrRunState(CLEANED) | CLEANED;
2755                 }
2756                 if ((e & TERMINATED) != 0L)
2757                     break;
2758                 if (ctl != 0L) // else loop if didn't finish cleaning
2759                     break;
2760                 if ((ds = delayScheduler) != null && ds.signal() >= 0)
2761                     break;
2762                 if ((e & CLEANED) != 0L) {
2763                     e |= TERMINATED;
2764                     if ((getAndBitwiseOrRunState(TERMINATED) & TERMINATED) == 0L) {
2765                         CountDownLatch done; SharedThreadContainer ctr;
2766                         if ((done = termination) != null)
2767                             done.countDown();
2768                         if ((ctr = container) != null)
2769                             ctr.close();
2770                     }
2771                     break;
2772                 }
2773             }
2774         }
2775         return e;
2776     }
2777 
2778     /**
2779      * Scans queues in a psuedorandom order based on thread id,
2780      * cancelling tasks until empty, or returning early upon
2781      * interference or still-active external queues, in which case
2782      * other calls will finish cancellation.
2783      *
2784      * @return true if all queues empty
2785      */
2786     private boolean cleanQueues() {
2787         int r = (int)Thread.currentThread().threadId();
2788         r ^= r << 13; r ^= r >>> 17; r ^= r << 5; // xorshift
2789         int step = (r >>> 16) | 1;                // randomize traversals
2790         WorkQueue[] qs = queues;
2791         int n = (qs == null) ? 0 : qs.length;
2792         for (int l = n; l > 0; --l, r += step) {
2793             WorkQueue q; ForkJoinTask<?>[] a; int cap;
2794             if ((q = qs[r & (n - 1)]) != null &&
2795                 (a = q.array) != null && (cap = a.length) > 0) {
2796                 for (;;) {
2797                     ForkJoinTask<?> t; int b; long k;
2798                     t = (ForkJoinTask<?>)U.getReferenceAcquire(
2799                         a, k = slotOffset((cap - 1) & (b = q.base)));
2800                     if (q.base == b && t != null &&
2801                         U.compareAndSetReference(a, k, t, null)) {
2802                         q.updateBase(b + 1);
2803                         try {
2804                             t.cancel(false);
2805                         } catch (Throwable ignore) {
2806                         }
2807                     }
2808                     else if ((q.phase & (IDLE|1)) == 0 || // externally locked
2809                              q.top - q.base > 0)
2810                         return false;             // incomplete
2811                     else
2812                         break;
2813                 }
2814             }
2815         }
2816         return true;
2817     }
2818 
2819     /**
2820      * Interrupts all workers
2821      */
2822     private void interruptAll() {
2823         Thread current = Thread.currentThread();
2824         WorkQueue[] qs = queues;
2825         int n = (qs == null) ? 0 : qs.length;
2826         for (int i = 1; i < n; i += 2) {
2827             WorkQueue q; Thread o;
2828             if ((q = qs[i]) != null && (o = q.owner) != null && o != current) {
2829                 try {
2830                     o.interrupt();
2831                 } catch (Throwable ignore) {
2832                 }
2833             }
2834         }
2835     }
2836 
2837     /**
2838      * Returns termination signal, constructing if necessary
2839      */
2840     private CountDownLatch terminationSignal() {
2841         CountDownLatch signal, s, u;
2842         if ((signal = termination) == null)
2843             signal = ((u = cmpExTerminationSignal(
2844                            s = new CountDownLatch(1))) == null) ? s : u;
2845         return signal;
2846     }
2847 
2848     // Exported methods
2849 
2850     // Constructors
2851 
2852     /**
2853      * Creates a {@code ForkJoinPool} with parallelism equal to {@link
2854      * java.lang.Runtime#availableProcessors}, using defaults for all
2855      * other parameters (see {@link #ForkJoinPool(int,
2856      * ForkJoinWorkerThreadFactory, UncaughtExceptionHandler, boolean,
2857      * int, int, int, Predicate, long, TimeUnit)}).
2858      */
2859     public ForkJoinPool() {
2860         this(Math.min(MAX_CAP, Runtime.getRuntime().availableProcessors()),
2861              defaultForkJoinWorkerThreadFactory, null, false,
2862              0, MAX_CAP, 1, null, DEFAULT_KEEPALIVE, TimeUnit.MILLISECONDS);
2863     }
2864 
2865     /**
2866      * Creates a {@code ForkJoinPool} with the indicated parallelism
2867      * level, using defaults for all other parameters (see {@link
2868      * #ForkJoinPool(int, ForkJoinWorkerThreadFactory,
2869      * UncaughtExceptionHandler, boolean, int, int, int, Predicate,
2870      * long, TimeUnit)}).
2871      *
2872      * @param parallelism the parallelism level
2873      * @throws IllegalArgumentException if parallelism less than or
2874      *         equal to zero, or greater than implementation limit
2875      */
2876     public ForkJoinPool(int parallelism) {
2877         this(parallelism, defaultForkJoinWorkerThreadFactory, null, false,
2878              0, MAX_CAP, 1, null, DEFAULT_KEEPALIVE, TimeUnit.MILLISECONDS);
2879     }
2880 
2881     /**
2882      * Creates a {@code ForkJoinPool} with the given parameters (using
2883      * defaults for others -- see {@link #ForkJoinPool(int,
2884      * ForkJoinWorkerThreadFactory, UncaughtExceptionHandler, boolean,
2885      * int, int, int, Predicate, long, TimeUnit)}).
2886      *
2887      * @param parallelism the parallelism level. For default value,
2888      * use {@link java.lang.Runtime#availableProcessors}.
2889      * @param factory the factory for creating new threads. For default value,
2890      * use {@link #defaultForkJoinWorkerThreadFactory}.
2891      * @param handler the handler for internal worker threads that
2892      * terminate due to unrecoverable errors encountered while executing
2893      * tasks. For default value, use {@code null}.
2894      * @param asyncMode if true,
2895      * establishes local first-in-first-out scheduling mode for forked
2896      * tasks that are never joined. This mode may be more appropriate
2897      * than default locally stack-based mode in applications in which
2898      * worker threads only process event-style asynchronous tasks.
2899      * For default value, use {@code false}.
2900      * @throws IllegalArgumentException if parallelism less than or
2901      *         equal to zero, or greater than implementation limit
2902      * @throws NullPointerException if the factory is null
2903      */
2904     public ForkJoinPool(int parallelism,
2905                         ForkJoinWorkerThreadFactory factory,
2906                         UncaughtExceptionHandler handler,
2907                         boolean asyncMode) {
2908         this(parallelism, factory, handler, asyncMode,
2909              0, MAX_CAP, 1, null, DEFAULT_KEEPALIVE, TimeUnit.MILLISECONDS);
2910     }
2911 
2912     /**
2913      * Creates a {@code ForkJoinPool} with the given parameters.
2914      *
2915      * @param parallelism the parallelism level. For default value,
2916      * use {@link java.lang.Runtime#availableProcessors}.
2917      *
2918      * @param factory the factory for creating new threads. For
2919      * default value, use {@link #defaultForkJoinWorkerThreadFactory}.
2920      *
2921      * @param handler the handler for internal worker threads that
2922      * terminate due to unrecoverable errors encountered while
2923      * executing tasks. For default value, use {@code null}.
2924      *
2925      * @param asyncMode if true, establishes local first-in-first-out
2926      * scheduling mode for forked tasks that are never joined. This
2927      * mode may be more appropriate than default locally stack-based
2928      * mode in applications in which worker threads only process
2929      * event-style asynchronous tasks.  For default value, use {@code
2930      * false}.
2931      *
2932      * @param corePoolSize ignored: used in previous releases of this
2933      * class but no longer applicable. Using {@code 0} maintains
2934      * compatibility across releases.
2935      *
2936      * @param maximumPoolSize the maximum number of threads allowed.
2937      * When the maximum is reached, attempts to replace blocked
2938      * threads fail.  (However, because creation and termination of
2939      * different threads may overlap, and may be managed by the given
2940      * thread factory, this value may be transiently exceeded.)  To
2941      * arrange the same value as is used by default for the common
2942      * pool, use {@code 256} plus the {@code parallelism} level. (By
2943      * default, the common pool allows a maximum of 256 spare
2944      * threads.)  Using a value (for example {@code
2945      * Integer.MAX_VALUE}) larger than the implementation's total
2946      * thread limit has the same effect as using this limit (which is
2947      * the default).
2948      *
2949      * @param minimumRunnable the minimum allowed number of core
2950      * threads not blocked by a join or {@link ManagedBlocker}.  To
2951      * ensure progress, when too few unblocked threads exist and
2952      * unexecuted tasks may exist, new threads are constructed, up to
2953      * the given maximumPoolSize.  For the default value, use {@code
2954      * 1}, that ensures liveness.  A larger value might improve
2955      * throughput in the presence of blocked activities, but might
2956      * not, due to increased overhead.  A value of zero may be
2957      * acceptable when submitted tasks cannot have dependencies
2958      * requiring additional threads.
2959      *
2960      * @param saturate if non-null, a predicate invoked upon attempts
2961      * to create more than the maximum total allowed threads.  By
2962      * default, when a thread is about to block on a join or {@link
2963      * ManagedBlocker}, but cannot be replaced because the
2964      * maximumPoolSize would be exceeded, a {@link
2965      * RejectedExecutionException} is thrown.  But if this predicate
2966      * returns {@code true}, then no exception is thrown, so the pool
2967      * continues to operate with fewer than the target number of
2968      * runnable threads, which might not ensure progress.
2969      *
2970      * @param keepAliveTime the elapsed time since last use before
2971      * a thread is terminated (and then later replaced if needed).
2972      * For the default value, use {@code 60, TimeUnit.SECONDS}.
2973      *
2974      * @param unit the time unit for the {@code keepAliveTime} argument
2975      *
2976      * @throws IllegalArgumentException if parallelism is less than or
2977      *         equal to zero, or is greater than implementation limit,
2978      *         or if maximumPoolSize is less than parallelism,
2979      *         of if the keepAliveTime is less than or equal to zero.
2980      * @throws NullPointerException if the factory is null
2981      * @since 9
2982      */
2983     public ForkJoinPool(int parallelism,
2984                         ForkJoinWorkerThreadFactory factory,
2985                         UncaughtExceptionHandler handler,
2986                         boolean asyncMode,
2987                         int corePoolSize,
2988                         int maximumPoolSize,
2989                         int minimumRunnable,
2990                         Predicate<? super ForkJoinPool> saturate,
2991                         long keepAliveTime,
2992                         TimeUnit unit) {
2993         int p = parallelism;
2994         if (p <= 0 || p > MAX_CAP || p > maximumPoolSize || keepAliveTime <= 0L)
2995             throw new IllegalArgumentException();
2996         if (factory == null || unit == null)
2997             throw new NullPointerException();
2998         int size = Math.max(MIN_QUEUES_SIZE,
2999                             1 << (33 - Integer.numberOfLeadingZeros(p - 1)));
3000         this.parallelism = p;
3001         this.factory = factory;
3002         this.ueh = handler;
3003         this.saturate = saturate;
3004         this.keepAlive = Math.max(unit.toMillis(keepAliveTime), TIMEOUT_SLOP);
3005         int maxSpares = Math.clamp(maximumPoolSize - p, 0, MAX_CAP);
3006         int minAvail = Math.clamp(minimumRunnable, 0, MAX_CAP);
3007         this.config = (((asyncMode ? FIFO : 0) & LMASK) |
3008                        (((long)maxSpares) << TC_SHIFT) |
3009                        (((long)minAvail)  << RC_SHIFT));
3010         this.queues = new WorkQueue[size];
3011         String pid = Integer.toString(getAndAddPoolIds(1) + 1);
3012         String name = "ForkJoinPool-" + pid;
3013         this.poolName = name;
3014         this.workerNamePrefix = name + "-worker-";
3015         this.container = SharedThreadContainer.create(name);
3016     }
3017 
3018     /**
3019      * Constructor for common pool using parameters possibly
3020      * overridden by system properties
3021      */
3022     private ForkJoinPool(byte forCommonPoolOnly) {
3023         String name = "ForkJoinPool.commonPool";
3024         ForkJoinWorkerThreadFactory fac = defaultForkJoinWorkerThreadFactory;
3025         UncaughtExceptionHandler handler = null;
3026         int maxSpares = DEFAULT_COMMON_MAX_SPARES;
3027         int pc = 0, preset = 0; // nonzero if size set as property
3028         try {  // ignore exceptions in accessing/parsing properties
3029             String pp = System.getProperty
3030                 ("java.util.concurrent.ForkJoinPool.common.parallelism");
3031             if (pp != null) {
3032                 pc = Math.max(0, Integer.parseInt(pp));
3033                 preset = PRESET_SIZE;
3034             }
3035             String ms = System.getProperty
3036                 ("java.util.concurrent.ForkJoinPool.common.maximumSpares");
3037             if (ms != null)
3038                 maxSpares = Math.clamp(Integer.parseInt(ms), 0, MAX_CAP);
3039             String sf = System.getProperty
3040                 ("java.util.concurrent.ForkJoinPool.common.threadFactory");
3041             String sh = System.getProperty
3042                 ("java.util.concurrent.ForkJoinPool.common.exceptionHandler");
3043             if (sf != null || sh != null) {
3044                 ClassLoader ldr = ClassLoader.getSystemClassLoader();
3045                 if (sf != null)
3046                     fac = (ForkJoinWorkerThreadFactory)
3047                         ldr.loadClass(sf).getConstructor().newInstance();
3048                 if (sh != null)
3049                     handler = (UncaughtExceptionHandler)
3050                         ldr.loadClass(sh).getConstructor().newInstance();
3051             }
3052         } catch (Exception ignore) {
3053         }
3054         if (preset == 0)
3055             pc = Math.max(1, Runtime.getRuntime().availableProcessors() - 1);
3056         int p = Math.min(pc, MAX_CAP);
3057         int size = Math.max(MIN_QUEUES_SIZE,
3058                             (p == 0) ? 1 :
3059                             1 << (33 - Integer.numberOfLeadingZeros(p-1)));
3060         this.parallelism = p;
3061         this.config = ((preset & LMASK) | (((long)maxSpares) << TC_SHIFT) |
3062                        (1L << RC_SHIFT));
3063         this.factory = fac;
3064         this.ueh = handler;
3065         this.keepAlive = DEFAULT_KEEPALIVE;
3066         this.saturate = null;
3067         this.workerNamePrefix = null;
3068         this.poolName = name;
3069         this.queues = new WorkQueue[size];
3070         this.container = SharedThreadContainer.create(name);
3071     }
3072 
3073     /**
3074      * Returns the common pool instance. This pool is statically
3075      * constructed; its run state is unaffected by attempts to {@link
3076      * #shutdown} or {@link #shutdownNow}. However this pool and any
3077      * ongoing processing are automatically terminated upon program
3078      * {@link System#exit}.  Any program that relies on asynchronous
3079      * task processing to complete before program termination should
3080      * invoke {@code commonPool().}{@link #awaitQuiescence awaitQuiescence},
3081      * before exit.
3082      *
3083      * @return the common pool instance
3084      * @since 1.8
3085      */
3086     public static ForkJoinPool commonPool() {
3087         // assert common != null : "static init error";
3088         return common;
3089     }
3090 
3091     /**
3092      * Package-private access to commonPool overriding zero parallelism
3093      */
3094     static ForkJoinPool asyncCommonPool() {
3095         ForkJoinPool cp; int p;
3096         if ((p = (cp = common).parallelism) == 0)
3097             U.compareAndSetInt(cp, PARALLELISM, 0, 2);
3098         return cp;
3099     }
3100 
3101     // Execution methods
3102 
3103     /**
3104      * Performs the given task, returning its result upon completion.
3105      * If the computation encounters an unchecked Exception or Error,
3106      * it is rethrown as the outcome of this invocation.  Rethrown
3107      * exceptions behave in the same way as regular exceptions, but,
3108      * when possible, contain stack traces (as displayed for example
3109      * using {@code ex.printStackTrace()}) of both the current thread
3110      * as well as the thread actually encountering the exception;
3111      * minimally only the latter.
3112      *
3113      * @param task the task
3114      * @param <T> the type of the task's result
3115      * @return the task's result
3116      * @throws NullPointerException if the task is null
3117      * @throws RejectedExecutionException if the task cannot be
3118      *         scheduled for execution
3119      */
3120     public <T> T invoke(ForkJoinTask<T> task) {
3121         poolSubmit(true, Objects.requireNonNull(task));
3122         try {
3123             return task.join();
3124         } catch (RuntimeException | Error unchecked) {
3125             throw unchecked;
3126         } catch (Exception checked) {
3127             throw new RuntimeException(checked);
3128         }
3129     }
3130 
3131     /**
3132      * Arranges for (asynchronous) execution of the given task.
3133      *
3134      * @param task the task
3135      * @throws NullPointerException if the task is null
3136      * @throws RejectedExecutionException if the task cannot be
3137      *         scheduled for execution
3138      */
3139     public void execute(ForkJoinTask<?> task) {
3140         poolSubmit(true,  Objects.requireNonNull(task));
3141     }
3142 
3143     // AbstractExecutorService methods
3144 
3145     /**
3146      * @throws NullPointerException if the task is null
3147      * @throws RejectedExecutionException if the task cannot be
3148      *         scheduled for execution
3149      */
3150     @Override
3151     @SuppressWarnings("unchecked")
3152     public void execute(Runnable task) {
3153         poolSubmit(true, (Objects.requireNonNull(task) instanceof ForkJoinTask<?>)
3154                    ? (ForkJoinTask<Void>) task // avoid re-wrap
3155                    : new ForkJoinTask.RunnableExecuteAction(task));
3156     }
3157 
3158     /**
3159      * Submits a ForkJoinTask for execution.
3160      *
3161      * @implSpec
3162      * This method is equivalent to {@link #externalSubmit(ForkJoinTask)}
3163      * when called from a thread that is not in this pool.
3164      *
3165      * @param task the task to submit
3166      * @param <T> the type of the task's result
3167      * @return the task
3168      * @throws NullPointerException if the task is null
3169      * @throws RejectedExecutionException if the task cannot be
3170      *         scheduled for execution
3171      */
3172     public <T> ForkJoinTask<T> submit(ForkJoinTask<T> task) {
3173         return poolSubmit(true,  Objects.requireNonNull(task));
3174     }
3175 
3176     /**
3177      * @throws NullPointerException if the task is null
3178      * @throws RejectedExecutionException if the task cannot be
3179      *         scheduled for execution
3180      */
3181     @Override
3182     public <T> ForkJoinTask<T> submit(Callable<T> task) {
3183         Objects.requireNonNull(task);
3184         return poolSubmit(
3185             true,
3186             (Thread.currentThread() instanceof ForkJoinWorkerThread) ?
3187             new ForkJoinTask.AdaptedCallable<T>(task) :
3188             new ForkJoinTask.AdaptedInterruptibleCallable<T>(task));
3189     }
3190 
3191     /**
3192      * @throws NullPointerException if the task is null
3193      * @throws RejectedExecutionException if the task cannot be
3194      *         scheduled for execution
3195      */
3196     @Override
3197     public <T> ForkJoinTask<T> submit(Runnable task, T result) {
3198         Objects.requireNonNull(task);
3199         return poolSubmit(
3200             true,
3201             (Thread.currentThread() instanceof ForkJoinWorkerThread) ?
3202             new ForkJoinTask.AdaptedRunnable<T>(task, result) :
3203             new ForkJoinTask.AdaptedInterruptibleRunnable<T>(task, result));
3204     }
3205 
3206     /**
3207      * @throws NullPointerException if the task is null
3208      * @throws RejectedExecutionException if the task cannot be
3209      *         scheduled for execution
3210      */
3211     @Override
3212     @SuppressWarnings("unchecked")
3213     public ForkJoinTask<?> submit(Runnable task) {
3214         Objects.requireNonNull(task);
3215         return poolSubmit(
3216             true,
3217             (task instanceof ForkJoinTask<?>) ?
3218             (ForkJoinTask<Void>) task : // avoid re-wrap
3219             ((Thread.currentThread() instanceof ForkJoinWorkerThread) ?
3220              new ForkJoinTask.AdaptedRunnable<Void>(task, null) :
3221              new ForkJoinTask.AdaptedInterruptibleRunnable<Void>(task, null)));
3222     }
3223 
3224     /**
3225      * Submits the given task as if submitted from a non-{@code ForkJoinTask}
3226      * client. The task is added to a scheduling queue for submissions to the
3227      * pool even when called from a thread in the pool.
3228      *
3229      * @implSpec
3230      * This method is equivalent to {@link #submit(ForkJoinTask)} when called
3231      * from a thread that is not in this pool.
3232      *
3233      * @return the task
3234      * @param task the task to submit
3235      * @param <T> the type of the task's result
3236      * @throws NullPointerException if the task is null
3237      * @throws RejectedExecutionException if the task cannot be
3238      *         scheduled for execution
3239      * @since 20
3240      */
3241     public <T> ForkJoinTask<T> externalSubmit(ForkJoinTask<T> task) {
3242         Objects.requireNonNull(task);
3243         externalSubmissionQueue(true).push(task, this, false);
3244         return task;
3245     }
3246 
3247     /**
3248      * Submits the given task without guaranteeing that it will
3249      * eventually execute in the absence of available active threads.
3250      * In some contexts, this method may reduce contention and
3251      * overhead by relying on context-specific knowledge that existing
3252      * threads (possibly including the calling thread if operating in
3253      * this pool) will eventually be available to execute the task.
3254      *
3255      * @param task the task
3256      * @param <T> the type of the task's result
3257      * @return the task
3258      * @throws NullPointerException if the task is null
3259      * @throws RejectedExecutionException if the task cannot be
3260      *         scheduled for execution
3261      * @since 19
3262      */
3263     public <T> ForkJoinTask<T> lazySubmit(ForkJoinTask<T> task) {
3264         return poolSubmit(false,  Objects.requireNonNull(task));
3265     }
3266 
3267     /**
3268      * Changes the target parallelism of this pool, controlling the
3269      * future creation, use, and termination of worker threads.
3270      * Applications include contexts in which the number of available
3271      * processors changes over time.
3272      *
3273      * @implNote This implementation restricts the maximum number of
3274      * running threads to 32767
3275      *
3276      * @param size the target parallelism level
3277      * @return the previous parallelism level.
3278      * @throws IllegalArgumentException if size is less than 1 or
3279      *         greater than the maximum supported by this pool.
3280      * @throws UnsupportedOperationException this is the{@link
3281      *         #commonPool()} and parallelism level was set by System
3282      *         property {@systemProperty
3283      *         java.util.concurrent.ForkJoinPool.common.parallelism}.
3284      * @since 19
3285      */
3286     public int setParallelism(int size) {
3287         if (size < 1 || size > MAX_CAP)
3288             throw new IllegalArgumentException();
3289         if ((config & PRESET_SIZE) != 0)
3290             throw new UnsupportedOperationException("Cannot override System property");
3291         return getAndSetParallelism(size);
3292     }
3293 
3294     /**
3295      * Uninterrupible version of {@code invokeAll}. Executes the given
3296      * tasks, returning a list of Futures holding their status and
3297      * results when all complete, ignoring interrupts.  {@link
3298      * Future#isDone} is {@code true} for each element of the returned
3299      * list.  Note that a <em>completed</em> task could have
3300      * terminated either normally or by throwing an exception.  The
3301      * results of this method are undefined if the given collection is
3302      * modified while this operation is in progress.
3303      *
3304      * @apiNote This method supports usages that previously relied on an
3305      * incompatible override of
3306      * {@link ExecutorService#invokeAll(java.util.Collection)}.
3307      *
3308      * @param tasks the collection of tasks
3309      * @param <T> the type of the values returned from the tasks
3310      * @return a list of Futures representing the tasks, in the same
3311      *         sequential order as produced by the iterator for the
3312      *         given task list, each of which has completed
3313      * @throws NullPointerException if tasks or any of its elements are {@code null}
3314      * @throws RejectedExecutionException if any task cannot be
3315      *         scheduled for execution
3316      * @since 22
3317      */
3318     public <T> List<Future<T>> invokeAllUninterruptibly(Collection<? extends Callable<T>> tasks) {
3319         ArrayList<Future<T>> futures = new ArrayList<>(tasks.size());
3320         try {
3321             for (Callable<T> t : tasks) {
3322                 ForkJoinTask<T> f = ForkJoinTask.adapt(t);
3323                 futures.add(f);
3324                 poolSubmit(true, f);
3325             }
3326             for (int i = futures.size() - 1; i >= 0; --i)
3327                 ((ForkJoinTask<?>)futures.get(i)).quietlyJoin();
3328             return futures;
3329         } catch (Throwable t) {
3330             for (Future<T> e : futures)
3331                 e.cancel(true);
3332             throw t;
3333         }
3334     }
3335 
3336     /**
3337      * Common support for timed and untimed invokeAll
3338      */
3339     private  <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks,
3340                                            long deadline)
3341         throws InterruptedException {
3342         ArrayList<Future<T>> futures = new ArrayList<>(tasks.size());
3343         try {
3344             for (Callable<T> t : tasks) {
3345                 ForkJoinTask<T> f = ForkJoinTask.adaptInterruptible(t);
3346                 futures.add(f);
3347                 poolSubmit(true, f);
3348             }
3349             for (int i = futures.size() - 1; i >= 0; --i)
3350                 ((ForkJoinTask<?>)futures.get(i))
3351                     .quietlyJoinPoolInvokeAllTask(deadline);
3352             return futures;
3353         } catch (Throwable t) {
3354             for (Future<T> e : futures)
3355                 e.cancel(true);
3356             throw t;
3357         }
3358     }
3359 
3360     @Override
3361     public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
3362         throws InterruptedException {
3363         return invokeAll(tasks, 0L);
3364     }
3365     // for jdk version < 22, replace with
3366     // /**
3367     //  * @throws NullPointerException       {@inheritDoc}
3368     //  * @throws RejectedExecutionException {@inheritDoc}
3369     //  */
3370     // @Override
3371     // public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) {
3372     //     return invokeAllUninterruptibly(tasks);
3373     // }
3374 
3375     @Override
3376     public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks,
3377                                          long timeout, TimeUnit unit)
3378         throws InterruptedException {
3379         return invokeAll(tasks, (System.nanoTime() + unit.toNanos(timeout)) | 1L);
3380     }
3381 
3382     @Override
3383     public <T> T invokeAny(Collection<? extends Callable<T>> tasks)
3384         throws InterruptedException, ExecutionException {
3385         try {
3386             return new ForkJoinTask.InvokeAnyRoot<T>()
3387                 .invokeAny(tasks, this, false, 0L);
3388         } catch (TimeoutException cannotHappen) {
3389             assert false;
3390             return null;
3391         }
3392     }
3393 
3394     @Override
3395     public <T> T invokeAny(Collection<? extends Callable<T>> tasks,
3396                            long timeout, TimeUnit unit)
3397         throws InterruptedException, ExecutionException, TimeoutException {
3398         return new ForkJoinTask.InvokeAnyRoot<T>()
3399             .invokeAny(tasks, this, true, unit.toNanos(timeout));
3400     }
3401 
3402     // Support for delayed tasks
3403 
3404     /**
3405      * Returns STOP and SHUTDOWN status (zero if neither), masking or
3406      * truncating out other bits.
3407      */
3408     final int shutdownStatus(DelayScheduler ds) {
3409         return (int)(runState & (SHUTDOWN | STOP));
3410     }
3411 
3412     /**
3413      * Tries to stop and possibly terminate if already enabled, return success.
3414      */
3415     final boolean tryStopIfShutdown(DelayScheduler ds) {
3416         return (tryTerminate(false, false) & STOP) != 0L;
3417     }
3418 
3419     /**
3420      *  Creates and starts DelayScheduler
3421      */
3422     private DelayScheduler startDelayScheduler() {
3423         DelayScheduler ds;
3424         if ((ds = delayScheduler) == null) {
3425             boolean start = false;
3426             String name = poolName + "-delayScheduler";
3427             if (workerNamePrefix == null)
3428                 asyncCommonPool();  // override common parallelism zero
3429             long isShutdown = lockRunState() & SHUTDOWN;
3430             try {
3431                 if (isShutdown == 0L && (ds = delayScheduler) == null) {
3432                     ds = delayScheduler = new DelayScheduler(this, name);
3433                     start = true;
3434                 }
3435             } finally {
3436                 unlockRunState();
3437             }
3438             if (start) { // start outside of lock
3439                 SharedThreadContainer ctr;
3440                 try {
3441                     if ((ctr = container) != null)
3442                         ctr.start(ds);
3443                     else
3444                         ds.start();
3445                 } catch (RuntimeException | Error ex) { // back out
3446                     lockRunState();
3447                     ds = delayScheduler = null;
3448                     unlockRunState();
3449                     tryTerminate(false, false);
3450                     if (ex instanceof Error)
3451                         throw ex;
3452                 }
3453             }
3454         }
3455         return ds;
3456     }
3457 
3458     /**
3459      * Arranges execution of a ScheduledForkJoinTask whose delay has
3460      * elapsed
3461      */
3462     final void executeEnabledScheduledTask(ScheduledForkJoinTask<?> task) {
3463         externalSubmissionQueue(false).push(task, this, false);
3464     }
3465 
3466     /**
3467      * Arranges delayed execution of a ScheduledForkJoinTask via the
3468      * DelayScheduler, creating and starting it if necessary.
3469      * @return the task
3470      */
3471     final <T> ScheduledForkJoinTask<T> scheduleDelayedTask(ScheduledForkJoinTask<T> task) {
3472         DelayScheduler ds;
3473         if (((ds = delayScheduler) == null &&
3474              (ds = startDelayScheduler()) == null) ||
3475             (runState & SHUTDOWN) != 0L)
3476             throw new RejectedExecutionException();
3477         ds.pend(task);
3478         return task;
3479     }
3480 
3481     /**
3482      * Submits a one-shot task that becomes enabled for execution after the given
3483      * delay.  At that point it will execute unless explicitly
3484      * cancelled, or fail to execute (eventually reporting
3485      * cancellation) when encountering resource exhaustion, or the
3486      * pool is {@link #shutdownNow}, or is {@link #shutdown} when
3487      * otherwise quiescent and {@link #cancelDelayedTasksOnShutdown}
3488      * is in effect.
3489      *
3490      * @param command the task to execute
3491      * @param delay the time from now to delay execution
3492      * @param unit the time unit of the delay parameter
3493      * @return a ForkJoinTask implementing the ScheduledFuture
3494      *         interface, whose {@code get()} method will return
3495      *         {@code null} upon normal completion.
3496      * @throws RejectedExecutionException if the pool is shutdown or
3497      *         submission encounters resource exhaustion.
3498      * @throws NullPointerException if command or unit is null
3499      * @since 25
3500      */
3501     public ScheduledFuture<?> schedule(Runnable command,
3502                                        long delay, TimeUnit unit) {
3503         return scheduleDelayedTask(
3504             new ScheduledForkJoinTask<Void>(
3505                 unit.toNanos(delay), 0L, false, // implicit null check of unit
3506                 Objects.requireNonNull(command), null, this));
3507     }
3508 
3509     /**
3510      * Submits a value-returning one-shot task that becomes enabled for execution
3511      * after the given delay. At that point it will execute unless
3512      * explicitly cancelled, or fail to execute (eventually reporting
3513      * cancellation) when encountering resource exhaustion, or the
3514      * pool is {@link #shutdownNow}, or is {@link #shutdown} when
3515      * otherwise quiescent and {@link #cancelDelayedTasksOnShutdown}
3516      * is in effect.
3517      *
3518      * @param callable the function to execute
3519      * @param delay the time from now to delay execution
3520      * @param unit the time unit of the delay parameter
3521      * @param <V> the type of the callable's result
3522      * @return a ForkJoinTask implementing the ScheduledFuture
3523      *         interface, whose {@code get()} method will return the
3524      *         value from the callable upon normal completion.
3525      * @throws RejectedExecutionException if the pool is shutdown or
3526      *         submission encounters resource exhaustion.
3527      * @throws NullPointerException if command or unit is null
3528      * @since 25
3529      */
3530     public <V> ScheduledFuture<V> schedule(Callable<V> callable,
3531                                            long delay, TimeUnit unit) {
3532         return scheduleDelayedTask(
3533             new ScheduledForkJoinTask<V>(
3534                 unit.toNanos(delay), 0L, false, null,  // implicit null check of unit
3535                 Objects.requireNonNull(callable), this));
3536     }
3537 
3538     /**
3539      * Submits a periodic action that becomes enabled for execution first after the
3540      * given initial delay, and subsequently with the given period;
3541      * that is, executions will commence after
3542      * {@code initialDelay}, then {@code initialDelay + period}, then
3543      * {@code initialDelay + 2 * period}, and so on.
3544      *
3545      * <p>The sequence of task executions continues indefinitely until
3546      * one of the following exceptional completions occur:
3547      * <ul>
3548      * <li>The task is {@linkplain Future#cancel explicitly cancelled}
3549      * <li>Method {@link #shutdownNow} is called
3550      * <li>Method {@link #shutdown} is called and the pool is
3551      * otherwise quiescent, in which case existing executions continue
3552      * but subsequent executions do not.
3553      * <li>An execution or the task encounters resource exhaustion.
3554      * <li>An execution of the task throws an exception.  In this case
3555      * calling {@link Future#get() get} on the returned future will throw
3556      * {@link ExecutionException}, holding the exception as its cause.
3557      * </ul>
3558      * Subsequent executions are suppressed.  Subsequent calls to
3559      * {@link Future#isDone isDone()} on the returned future will
3560      * return {@code true}.
3561      *
3562      * <p>If any execution of this task takes longer than its period, then
3563      * subsequent executions may start late, but will not concurrently
3564      * execute.
3565      * @param command the task to execute
3566      * @param initialDelay the time to delay first execution
3567      * @param period the period between successive executions
3568      * @param unit the time unit of the initialDelay and period parameters
3569      * @return a ForkJoinTask implementing the ScheduledFuture
3570      *         interface.  The future's {@link Future#get() get()}
3571      *         method will never return normally, and will throw an
3572      *         exception upon task cancellation or abnormal
3573      *         termination of a task execution.
3574      * @throws RejectedExecutionException if the pool is shutdown or
3575      *         submission encounters resource exhaustion.
3576      * @throws NullPointerException if command or unit is null
3577      * @throws IllegalArgumentException if period less than or equal to zero
3578      * @since 25
3579      */
3580     public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,
3581                                                   long initialDelay,
3582                                                   long period, TimeUnit unit) {
3583         if (period <= 0L)
3584             throw new IllegalArgumentException();
3585         return scheduleDelayedTask(
3586             new ScheduledForkJoinTask<Void>(
3587                 unit.toNanos(initialDelay),  // implicit null check of unit
3588                 unit.toNanos(period), false,
3589                 Objects.requireNonNull(command), null, this));
3590     }
3591 
3592     /**
3593      * Submits a periodic action that becomes enabled for execution first after the
3594      * given initial delay, and subsequently with the given delay
3595      * between the termination of one execution and the commencement of
3596      * the next.
3597      * <p>The sequence of task executions continues indefinitely until
3598      * one of the following exceptional completions occur:
3599      * <ul>
3600      * <li>The task is {@linkplain Future#cancel explicitly cancelled}
3601      * <li>Method {@link #shutdownNow} is called
3602      * <li>Method {@link #shutdown} is called and the pool is
3603      * otherwise quiescent, in which case existing executions continue
3604      * but subsequent executions do not.
3605      * <li>An execution or the task encounters resource exhaustion.
3606      * <li>An execution of the task throws an exception.  In this case
3607      * calling {@link Future#get() get} on the returned future will throw
3608      * {@link ExecutionException}, holding the exception as its cause.
3609      * </ul>
3610      * Subsequent executions are suppressed.  Subsequent calls to
3611      * {@link Future#isDone isDone()} on the returned future will
3612      * return {@code true}.
3613      * @param command the task to execute
3614      * @param initialDelay the time to delay first execution
3615      * @param delay the delay between the termination of one
3616      * execution and the commencement of the next
3617      * @param unit the time unit of the initialDelay and delay parameters
3618      * @return a ForkJoinTask implementing the ScheduledFuture
3619      *         interface.  The future's {@link Future#get() get()}
3620      *         method will never return normally, and will throw an
3621      *         exception upon task cancellation or abnormal
3622      *         termination of a task execution.
3623      * @throws RejectedExecutionException if the pool is shutdown or
3624      *         submission encounters resource exhaustion.
3625      * @throws NullPointerException if command or unit is null
3626      * @throws IllegalArgumentException if delay less than or equal to zero
3627      * @since 25
3628      */
3629     public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,
3630                                                      long initialDelay,
3631                                                      long delay, TimeUnit unit) {
3632         if (delay <= 0L)
3633             throw new IllegalArgumentException();
3634         return scheduleDelayedTask(
3635             new ScheduledForkJoinTask<Void>(
3636                 unit.toNanos(initialDelay),  // implicit null check of unit
3637                 -unit.toNanos(delay), false, // negative for fixed delay
3638                 Objects.requireNonNull(command), null, this));
3639     }
3640 
3641     /**
3642      * Body of a task performed on timeout of another task
3643      */
3644     static final class TimeoutAction<V> implements Runnable {
3645         // set after construction, nulled after use
3646         ForkJoinTask.CallableWithTimeout<V> task;
3647         Consumer<? super ForkJoinTask<V>> action;
3648         TimeoutAction(Consumer<? super ForkJoinTask<V>> action) {
3649             this.action = action;
3650         }
3651         public void run() {
3652             ForkJoinTask.CallableWithTimeout<V> t = task;
3653             Consumer<? super ForkJoinTask<V>> a = action;
3654             task = null;
3655             action = null;
3656             if (t != null && t.status >= 0) {
3657                 if (a == null)
3658                     t.cancel(true);
3659                 else {
3660                     a.accept(t);
3661                     t.interruptIfRunning(true);
3662                 }
3663             }
3664         }
3665     }
3666 
3667     /**
3668      * Submits a task executing the given function, cancelling the
3669      * task or performing a given timeoutAction if not completed
3670      * within the given timeout period. If the optional {@code
3671      * timeoutAction} is null, the task is cancelled (via {@code
3672      * cancel(true)}.  Otherwise, the action is applied and the task
3673      * may be interrupted if running. Actions may include {@link
3674      * ForkJoinTask#complete} to set a replacement value or {@link
3675      * ForkJoinTask#completeExceptionally} to throw an appropriate
3676      * exception. Note that these can succeed only if the task has
3677      * not already completed when the timeoutAction executes.
3678      *
3679      * @param callable the function to execute
3680      * @param <V> the type of the callable's result
3681      * @param timeout the time to wait before cancelling if not completed
3682      * @param timeoutAction if nonnull, an action to perform on
3683      *        timeout, otherwise the default action is to cancel using
3684      *        {@code cancel(true)}.
3685      * @param unit the time unit of the timeout parameter
3686      * @return a Future that can be used to extract result or cancel
3687      * @throws RejectedExecutionException if the task cannot be
3688      *         scheduled for execution
3689      * @throws NullPointerException if callable or unit is null
3690      * @since 25
3691      */
3692     public <V> ForkJoinTask<V> submitWithTimeout(Callable<V> callable,
3693                                                  long timeout, TimeUnit unit,
3694                                                  Consumer<? super ForkJoinTask<V>> timeoutAction) {
3695         ForkJoinTask.CallableWithTimeout<V> task; TimeoutAction<V> onTimeout;
3696         Objects.requireNonNull(callable);
3697         ScheduledForkJoinTask<Void> timeoutTask =
3698             new ScheduledForkJoinTask<Void>(
3699                 unit.toNanos(timeout), 0L, true,
3700                 onTimeout = new TimeoutAction<V>(timeoutAction), null, this);
3701         onTimeout.task = task =
3702             new ForkJoinTask.CallableWithTimeout<V>(callable, timeoutTask);
3703         scheduleDelayedTask(timeoutTask);
3704         return poolSubmit(true, task);
3705     }
3706 
3707     /**
3708      * Arranges that scheduled tasks that are not executing and have
3709      * not already been enabled for execution will not be executed and
3710      * will be cancelled upon {@link #shutdown} (unless this pool is
3711      * the {@link #commonPool()} which never shuts down). This method
3712      * may be invoked either before {@link #shutdown} to take effect
3713      * upon the next call, or afterwards to cancel such tasks, which
3714      * may then allow termination. Note that subsequent executions of
3715      * periodic tasks are always disabled upon shutdown, so this
3716      * method applies meaningfully only to non-periodic tasks.
3717      * @since 25
3718      */
3719     public void cancelDelayedTasksOnShutdown() {
3720         DelayScheduler ds;
3721         if ((ds = delayScheduler) != null ||
3722             (ds = startDelayScheduler()) != null)
3723             ds.cancelDelayedTasksOnShutdown();
3724     }
3725 
3726     /**
3727      * Returns the factory used for constructing new workers.
3728      *
3729      * @return the factory used for constructing new workers
3730      */
3731     public ForkJoinWorkerThreadFactory getFactory() {
3732         return factory;
3733     }
3734 
3735     /**
3736      * Returns the handler for internal worker threads that terminate
3737      * due to unrecoverable errors encountered while executing tasks.
3738      *
3739      * @return the handler, or {@code null} if none
3740      */
3741     public UncaughtExceptionHandler getUncaughtExceptionHandler() {
3742         return ueh;
3743     }
3744 
3745     /**
3746      * Returns the targeted parallelism level of this pool.
3747      *
3748      * @return the targeted parallelism level of this pool
3749      */
3750     public int getParallelism() {
3751         return Math.max(getParallelismOpaque(), 1);
3752     }
3753 
3754     /**
3755      * Returns the targeted parallelism level of the common pool.
3756      *
3757      * @return the targeted parallelism level of the common pool
3758      * @since 1.8
3759      */
3760     public static int getCommonPoolParallelism() {
3761         return common.getParallelism();
3762     }
3763 
3764     /**
3765      * Returns the number of worker threads that have started but not
3766      * yet terminated.  The result returned by this method may differ
3767      * from {@link #getParallelism} when threads are created to
3768      * maintain parallelism when others are cooperatively blocked.
3769      *
3770      * @return the number of worker threads
3771      */
3772     public int getPoolSize() {
3773         return (short)(ctl >>> TC_SHIFT);
3774     }
3775 
3776     /**
3777      * Returns {@code true} if this pool uses local first-in-first-out
3778      * scheduling mode for forked tasks that are never joined.
3779      *
3780      * @return {@code true} if this pool uses async mode
3781      */
3782     public boolean getAsyncMode() {
3783         return (config & FIFO) != 0;
3784     }
3785 
3786     /**
3787      * Returns an estimate of the number of worker threads that are
3788      * not blocked waiting to join tasks or for other managed
3789      * synchronization. This method may overestimate the
3790      * number of running threads.
3791      *
3792      * @return the number of worker threads
3793      */
3794     public int getRunningThreadCount() {
3795         WorkQueue[] qs; WorkQueue q;
3796         int rc = 0;
3797         if ((runState & TERMINATED) == 0L && (qs = queues) != null) {
3798             for (int i = 1; i < qs.length; i += 2) {
3799                 if ((q = qs[i]) != null && q.isApparentlyUnblocked())
3800                     ++rc;
3801             }
3802         }
3803         return rc;
3804     }
3805 
3806     /**
3807      * Returns an estimate of the number of threads that are currently
3808      * stealing or executing tasks. This method may overestimate the
3809      * number of active threads.
3810      *
3811      * @return the number of active threads
3812      */
3813     public int getActiveThreadCount() {
3814         return Math.max((short)(ctl >>> RC_SHIFT), 0);
3815     }
3816 
3817     /**
3818      * Returns {@code true} if all worker threads are currently idle.
3819      * An idle worker is one that cannot obtain a task to execute
3820      * because none are available to steal from other threads, and
3821      * there are no pending submissions to the pool. This method is
3822      * conservative; it might not return {@code true} immediately upon
3823      * idleness of all threads, but will eventually become true if
3824      * threads remain inactive.
3825      *
3826      * @return {@code true} if all threads are currently idle
3827      */
3828     public boolean isQuiescent() {
3829         return quiescent() >= 0;
3830     }
3831 
3832     /**
3833      * Returns an estimate of the total number of completed tasks that
3834      * were executed by a thread other than their submitter. The
3835      * reported value underestimates the actual total number of steals
3836      * when the pool is not quiescent. This value may be useful for
3837      * monitoring and tuning fork/join programs: in general, steal
3838      * counts should be high enough to keep threads busy, but low
3839      * enough to avoid overhead and contention across threads.
3840      *
3841      * @return the number of steals
3842      */
3843     public long getStealCount() {
3844         long count = stealCount;
3845         WorkQueue[] qs; WorkQueue q;
3846         if ((qs = queues) != null) {
3847             for (int i = 1; i < qs.length; i += 2) {
3848                 if ((q = qs[i]) != null)
3849                      count += (long)q.nsteals & 0xffffffffL;
3850             }
3851         }
3852         return count;
3853     }
3854 
3855     /**
3856      * Returns an estimate of the total number of tasks currently held
3857      * in queues by worker threads (but not including tasks submitted
3858      * to the pool that have not begun executing). This value is only
3859      * an approximation, obtained by iterating across all threads in
3860      * the pool. This method may be useful for tuning task
3861      * granularities.The returned count does not include scheduled
3862      * tasks that are not yet ready to execute, which are reported
3863      * separately by method {@link getDelayedTaskCount}.
3864      *
3865      * @return the number of queued tasks
3866      * @see ForkJoinWorkerThread#getQueuedTaskCount()
3867      */
3868     public long getQueuedTaskCount() {
3869         WorkQueue[] qs; WorkQueue q;
3870         long count = 0;
3871         if ((runState & TERMINATED) == 0L && (qs = queues) != null) {
3872             for (int i = 1; i < qs.length; i += 2) {
3873                 if ((q = qs[i]) != null)
3874                     count += q.queueSize();
3875             }
3876         }
3877         return count;
3878     }
3879 
3880     /**
3881      * Returns an estimate of the number of tasks submitted to this
3882      * pool that have not yet begun executing.  This method may take
3883      * time proportional to the number of submissions.
3884      *
3885      * @return the number of queued submissions
3886      */
3887     public int getQueuedSubmissionCount() {
3888         WorkQueue[] qs; WorkQueue q;
3889         int count = 0;
3890         if ((runState & TERMINATED) == 0L && (qs = queues) != null) {
3891             for (int i = 0; i < qs.length; i += 2) {
3892                 if ((q = qs[i]) != null)
3893                     count += q.queueSize();
3894             }
3895         }
3896         return count;
3897     }
3898 
3899     /**
3900      * Returns an estimate of the number of delayed (including
3901      * periodic) tasks scheduled in this pool that are not yet ready
3902      * to submit for execution. The returned value is inaccurate while
3903      * delayed tasks are being processed.
3904      *
3905      * @return an estimate of the number of delayed tasks
3906      * @since 25
3907      */
3908     public long getDelayedTaskCount() {
3909         DelayScheduler ds;
3910         return ((ds = delayScheduler) == null ? 0 : ds.lastStableSize());
3911     }
3912 
3913     /**
3914      * Returns {@code true} if there are any tasks submitted to this
3915      * pool that have not yet begun executing.
3916      *
3917      * @return {@code true} if there are any queued submissions
3918      */
3919     public boolean hasQueuedSubmissions() {
3920         WorkQueue[] qs; WorkQueue q;
3921         if ((runState & STOP) == 0L && (qs = queues) != null) {
3922             for (int i = 0; i < qs.length; i += 2) {
3923                 if ((q = qs[i]) != null && q.queueSize() > 0)
3924                     return true;
3925             }
3926         }
3927         return false;
3928     }
3929 
3930     /**
3931      * Removes and returns the next unexecuted submission if one is
3932      * available.  This method may be useful in extensions to this
3933      * class that re-assign work in systems with multiple pools.
3934      *
3935      * @return the next submission, or {@code null} if none
3936      */
3937     protected ForkJoinTask<?> pollSubmission() {
3938         return pollScan(true);
3939     }
3940 
3941     /**
3942      * Removes all available unexecuted submitted and forked tasks
3943      * from scheduling queues and adds them to the given collection,
3944      * without altering their execution status. These may include
3945      * artificially generated or wrapped tasks. This method is
3946      * designed to be invoked only when the pool is known to be
3947      * quiescent. Invocations at other times may not remove all
3948      * tasks. A failure encountered while attempting to add elements
3949      * to collection {@code c} may result in elements being in
3950      * neither, either or both collections when the associated
3951      * exception is thrown.  The behavior of this operation is
3952      * undefined if the specified collection is modified while the
3953      * operation is in progress.
3954      *
3955      * @param c the collection to transfer elements into
3956      * @return the number of elements transferred
3957      */
3958     protected int drainTasksTo(Collection<? super ForkJoinTask<?>> c) {
3959         int count = 0;
3960         for (ForkJoinTask<?> t; (t = pollScan(false)) != null; ) {
3961             c.add(t);
3962             ++count;
3963         }
3964         return count;
3965     }
3966 
3967     /**
3968      * Returns a string identifying this pool, as well as its state,
3969      * including indications of run state, parallelism level, and
3970      * worker and task counts.
3971      *
3972      * @return a string identifying this pool, as well as its state
3973      */
3974     public String toString() {
3975         // Use a single pass through queues to collect counts
3976         DelayScheduler ds;
3977         long e = runState;
3978         long st = stealCount;
3979         long qt = 0L, ss = 0L; int rc = 0;
3980         WorkQueue[] qs; WorkQueue q;
3981         if ((qs = queues) != null) {
3982             for (int i = 0; i < qs.length; ++i) {
3983                 if ((q = qs[i]) != null) {
3984                     int size = q.queueSize();
3985                     if ((i & 1) == 0)
3986                         ss += size;
3987                     else {
3988                         qt += size;
3989                         st += (long)q.nsteals & 0xffffffffL;
3990                         if (q.isApparentlyUnblocked())
3991                             ++rc;
3992                     }
3993                 }
3994             }
3995         }
3996         String delayed = ((ds = delayScheduler) == null ? "" :
3997                           ", delayed = " + ds.lastStableSize());
3998         int pc = parallelism;
3999         long c = ctl;
4000         int tc = (short)(c >>> TC_SHIFT);
4001         int ac = (short)(c >>> RC_SHIFT);
4002         if (ac < 0) // ignore transient negative
4003             ac = 0;
4004         String level = ((e & TERMINATED) != 0L ? "Terminated" :
4005                         (e & STOP)       != 0L ? "Terminating" :
4006                         (e & SHUTDOWN)   != 0L ? "Shutting down" :
4007                         "Running");
4008         return super.toString() +
4009             "[" + level +
4010             ", parallelism = " + pc +
4011             ", size = " + tc +
4012             ", active = " + ac +
4013             ", running = " + rc +
4014             ", steals = " + st +
4015             ", tasks = " + qt +
4016             ", submissions = " + ss +
4017             delayed +
4018             "]";
4019     }
4020 
4021     /**
4022      * Possibly initiates an orderly shutdown in which previously
4023      * submitted tasks are executed, but no new tasks will be
4024      * accepted. Invocation has no effect on execution state if this
4025      * is the {@link #commonPool()}, and no additional effect if
4026      * already shut down.  Tasks that are in the process of being
4027      * submitted concurrently during the course of this method may or
4028      * may not be rejected.
4029      */
4030     public void shutdown() {
4031         if (workerNamePrefix != null) // not common pool
4032             tryTerminate(false, true);
4033     }
4034 
4035     /**
4036      * Possibly attempts to cancel and/or stop all tasks, and reject
4037      * all subsequently submitted tasks.  Invocation has no effect on
4038      * execution state if this is the {@link #commonPool()}, and no
4039      * additional effect if already shut down. Otherwise, tasks that
4040      * are in the process of being submitted or executed concurrently
4041      * during the course of this method may or may not be
4042      * rejected. This method cancels both existing and unexecuted
4043      * tasks, in order to permit termination in the presence of task
4044      * dependencies. So the method always returns an empty list
4045      * (unlike the case for some other Executors).
4046      *
4047      * @return an empty list
4048      */
4049     public List<Runnable> shutdownNow() {
4050         if (workerNamePrefix != null) // not common pool
4051             tryTerminate(true, true);
4052         return Collections.emptyList();
4053     }
4054 
4055     /**
4056      * Returns {@code true} if all tasks have completed following shut down.
4057      *
4058      * @return {@code true} if all tasks have completed following shut down
4059      */
4060     public boolean isTerminated() {
4061         return (tryTerminate(false, false) & TERMINATED) != 0;
4062     }
4063 
4064     /**
4065      * Returns {@code true} if the process of termination has
4066      * commenced but not yet completed.  This method may be useful for
4067      * debugging. A return of {@code true} reported a sufficient
4068      * period after shutdown may indicate that submitted tasks have
4069      * ignored or suppressed interruption, or are waiting for I/O,
4070      * causing this executor not to properly terminate. (See the
4071      * advisory notes for class {@link ForkJoinTask} stating that
4072      * tasks should not normally entail blocking operations.  But if
4073      * they do, they must abort them on interrupt.)
4074      *
4075      * @return {@code true} if terminating but not yet terminated
4076      */
4077     public boolean isTerminating() {
4078         return (tryTerminate(false, false) & (STOP | TERMINATED)) == STOP;
4079     }
4080 
4081     /**
4082      * Returns {@code true} if this pool has been shut down.
4083      *
4084      * @return {@code true} if this pool has been shut down
4085      */
4086     public boolean isShutdown() {
4087         return (runState & SHUTDOWN) != 0L;
4088     }
4089 
4090     /**
4091      * Blocks until all tasks have completed execution after a
4092      * shutdown request, or the timeout occurs, or the current thread
4093      * is interrupted, whichever happens first. Because the {@link
4094      * #commonPool()} never terminates until program shutdown, when
4095      * applied to the common pool, this method is equivalent to {@link
4096      * #awaitQuiescence(long, TimeUnit)} but always returns {@code false}.
4097      *
4098      * @param timeout the maximum time to wait
4099      * @param unit the time unit of the timeout argument
4100      * @return {@code true} if this executor terminated and
4101      *         {@code false} if the timeout elapsed before termination
4102      * @throws InterruptedException if interrupted while waiting
4103      */
4104     public boolean awaitTermination(long timeout, TimeUnit unit)
4105         throws InterruptedException {
4106         long nanos = unit.toNanos(timeout);
4107         CountDownLatch done;
4108         if (workerNamePrefix == null) {    // is common pool
4109             if (helpQuiescePool(this, nanos, true) < 0)
4110                 throw new InterruptedException();
4111             return false;
4112         }
4113         else if ((tryTerminate(false, false) & TERMINATED) != 0 ||
4114                  (done = terminationSignal()) == null ||
4115                  (runState & TERMINATED) != 0L)
4116             return true;
4117         else
4118             return done.await(nanos, TimeUnit.NANOSECONDS);
4119     }
4120 
4121     /**
4122      * If called by a ForkJoinTask operating in this pool, equivalent
4123      * in effect to {@link ForkJoinTask#helpQuiesce}. Otherwise,
4124      * waits and/or attempts to assist performing tasks until this
4125      * pool {@link #isQuiescent} or the indicated timeout elapses.
4126      *
4127      * @param timeout the maximum time to wait
4128      * @param unit the time unit of the timeout argument
4129      * @return {@code true} if quiescent; {@code false} if the
4130      * timeout elapsed.
4131      */
4132     public boolean awaitQuiescence(long timeout, TimeUnit unit) {
4133         return (helpQuiescePool(this, unit.toNanos(timeout), false) > 0);
4134     }
4135 
4136     /**
4137      * Unless this is the {@link #commonPool()}, initiates an orderly
4138      * shutdown in which previously submitted tasks are executed, but
4139      * no new tasks will be accepted, and waits until all tasks have
4140      * completed execution and the executor has terminated.
4141      *
4142      * <p> If already terminated, or this is the {@link
4143      * #commonPool()}, this method has no effect on execution, and
4144      * does not wait. Otherwise, if interrupted while waiting, this
4145      * method stops all executing tasks as if by invoking {@link
4146      * #shutdownNow()}. It then continues to wait until all actively
4147      * executing tasks have completed. Tasks that were awaiting
4148      * execution are not executed. The interrupt status will be
4149      * re-asserted before this method returns.
4150      *
4151      * @since 19
4152      */
4153     @Override
4154     public void close() {
4155         if (workerNamePrefix != null) {
4156             CountDownLatch done = null;
4157             boolean interrupted = false;
4158             while ((tryTerminate(interrupted, true) & TERMINATED) == 0) {
4159                 if (done == null)
4160                     done = terminationSignal();
4161                 else {
4162                     try {
4163                         done.await();
4164                         break;
4165                     } catch (InterruptedException ex) {
4166                         interrupted = true;
4167                     }
4168                 }
4169             }
4170             if (interrupted)
4171                 Thread.currentThread().interrupt();
4172         }
4173     }
4174 
4175     /**
4176      * Interface for extending managed parallelism for tasks running
4177      * in {@link ForkJoinPool}s.
4178      *
4179      * <p>A {@code ManagedBlocker} provides two methods.  Method
4180      * {@link #isReleasable} must return {@code true} if blocking is
4181      * not necessary. Method {@link #block} blocks the current thread
4182      * if necessary (perhaps internally invoking {@code isReleasable}
4183      * before actually blocking). These actions are performed by any
4184      * thread invoking {@link
4185      * ForkJoinPool#managedBlock(ManagedBlocker)}.  The unusual
4186      * methods in this API accommodate synchronizers that may, but
4187      * don't usually, block for long periods. Similarly, they allow
4188      * more efficient internal handling of cases in which additional
4189      * workers may be, but usually are not, needed to ensure
4190      * sufficient parallelism.  Toward this end, implementations of
4191      * method {@code isReleasable} must be amenable to repeated
4192      * invocation. Neither method is invoked after a prior invocation
4193      * of {@code isReleasable} or {@code block} returns {@code true}.
4194      *
4195      * <p>For example, here is a ManagedBlocker based on a
4196      * ReentrantLock:
4197      * <pre> {@code
4198      * class ManagedLocker implements ManagedBlocker {
4199      *   final ReentrantLock lock;
4200      *   boolean hasLock = false;
4201      *   ManagedLocker(ReentrantLock lock) { this.lock = lock; }
4202      *   public boolean block() {
4203      *     if (!hasLock)
4204      *       lock.lock();
4205      *     return true;
4206      *   }
4207      *   public boolean isReleasable() {
4208      *     return hasLock || (hasLock = lock.tryLock());
4209      *   }
4210      * }}</pre>
4211      *
4212      * <p>Here is a class that possibly blocks waiting for an
4213      * item on a given queue:
4214      * <pre> {@code
4215      * class QueueTaker<E> implements ManagedBlocker {
4216      *   final BlockingQueue<E> queue;
4217      *   volatile E item = null;
4218      *   QueueTaker(BlockingQueue<E> q) { this.queue = q; }
4219      *   public boolean block() throws InterruptedException {
4220      *     if (item == null)
4221      *       item = queue.take();
4222      *     return true;
4223      *   }
4224      *   public boolean isReleasable() {
4225      *     return item != null || (item = queue.poll()) != null;
4226      *   }
4227      *   public E getItem() { // call after pool.managedBlock completes
4228      *     return item;
4229      *   }
4230      * }}</pre>
4231      */
4232     public static interface ManagedBlocker {
4233         /**
4234          * Possibly blocks the current thread, for example waiting for
4235          * a lock or condition.
4236          *
4237          * @return {@code true} if no additional blocking is necessary
4238          * (i.e., if isReleasable would return true)
4239          * @throws InterruptedException if interrupted while waiting
4240          * (the method is not required to do so, but is allowed to)
4241          */
4242         boolean block() throws InterruptedException;
4243 
4244         /**
4245          * Returns {@code true} if blocking is unnecessary.
4246          * @return {@code true} if blocking is unnecessary
4247          */
4248         boolean isReleasable();
4249     }
4250 
4251     /**
4252      * Runs the given possibly blocking task.  When {@linkplain
4253      * ForkJoinTask#inForkJoinPool() running in a ForkJoinPool}, this
4254      * method possibly arranges for a spare thread to be activated if
4255      * necessary to ensure sufficient parallelism while the current
4256      * thread is blocked in {@link ManagedBlocker#block blocker.block()}.
4257      *
4258      * <p>This method repeatedly calls {@code blocker.isReleasable()} and
4259      * {@code blocker.block()} until either method returns {@code true}.
4260      * Every call to {@code blocker.block()} is preceded by a call to
4261      * {@code blocker.isReleasable()} that returned {@code false}.
4262      *
4263      * <p>If not running in a ForkJoinPool, this method is
4264      * behaviorally equivalent to
4265      * <pre> {@code
4266      * while (!blocker.isReleasable())
4267      *   if (blocker.block())
4268      *     break;}</pre>
4269      *
4270      * If running in a ForkJoinPool, the pool may first be expanded to
4271      * ensure sufficient parallelism available during the call to
4272      * {@code blocker.block()}.
4273      *
4274      * @param blocker the blocker task
4275      * @throws InterruptedException if {@code blocker.block()} did so
4276      */
4277     public static void managedBlock(ManagedBlocker blocker)
4278         throws InterruptedException {
4279         Thread t; ForkJoinPool p;
4280         if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread &&
4281             (p = ((ForkJoinWorkerThread)t).pool) != null)
4282             p.compensatedBlock(blocker);
4283         else
4284             unmanagedBlock(blocker);
4285     }
4286 
4287     /** ManagedBlock for ForkJoinWorkerThreads */
4288     private void compensatedBlock(ManagedBlocker blocker)
4289         throws InterruptedException {
4290         Objects.requireNonNull(blocker);
4291         for (;;) {
4292             int comp; boolean done;
4293             long c = ctl;
4294             if (blocker.isReleasable())
4295                 break;
4296             if ((runState & STOP) != 0L)
4297                 throw new InterruptedException();
4298             if ((comp = tryCompensate(c)) >= 0) {
4299                 try {
4300                     done = blocker.block();
4301                 } finally {
4302                     if (comp > 0)
4303                         getAndAddCtl(RC_UNIT);
4304                 }
4305                 if (done)
4306                     break;
4307             }
4308         }
4309     }
4310 
4311     /**
4312      * Invokes tryCompensate to create or re-activate a spare thread to
4313      * compensate for a thread that performs a blocking operation. When the
4314      * blocking operation is done then endCompensatedBlock must be invoked
4315      * with the value returned by this method to re-adjust the parallelism.
4316      * @return value to use in endCompensatedBlock
4317      */
4318     final long beginCompensatedBlock() {
4319         int c;
4320         do {} while ((c = tryCompensate(ctl)) < 0);
4321         return (c == 0) ? 0L : RC_UNIT;
4322     }
4323 
4324     /**
4325      * Re-adjusts parallelism after a blocking operation completes.
4326      * @param post value from beginCompensatedBlock
4327      */
4328     void endCompensatedBlock(long post) {
4329         if (post > 0L) {
4330             getAndAddCtl(post);
4331         }
4332     }
4333 
4334     /** ManagedBlock for external threads */
4335     private static void unmanagedBlock(ManagedBlocker blocker)
4336         throws InterruptedException {
4337         Objects.requireNonNull(blocker);
4338         do {} while (!blocker.isReleasable() && !blocker.block());
4339     }
4340 
4341     @Override
4342     protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
4343         Objects.requireNonNull(runnable);
4344         return (Thread.currentThread() instanceof ForkJoinWorkerThread) ?
4345             new ForkJoinTask.AdaptedRunnable<T>(runnable, value) :
4346             new ForkJoinTask.AdaptedInterruptibleRunnable<T>(runnable, value);
4347     }
4348 
4349     @Override
4350     protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
4351         Objects.requireNonNull(callable);
4352         return (Thread.currentThread() instanceof ForkJoinWorkerThread) ?
4353             new ForkJoinTask.AdaptedCallable<T>(callable) :
4354             new ForkJoinTask.AdaptedInterruptibleCallable<T>(callable);
4355     }
4356 
4357     static {
4358         U = Unsafe.getUnsafe();
4359         Class<ForkJoinPool> klass = ForkJoinPool.class;
4360         try {
4361             Field poolIdsField = klass.getDeclaredField("poolIds");
4362             POOLIDS_BASE = U.staticFieldBase(poolIdsField);
4363             POOLIDS = U.staticFieldOffset(poolIdsField);
4364         } catch (NoSuchFieldException e) {
4365             throw new ExceptionInInitializerError(e);
4366         }
4367         CTL = U.objectFieldOffset(klass, "ctl");
4368         RUNSTATE = U.objectFieldOffset(klass, "runState");
4369         PARALLELISM =  U.objectFieldOffset(klass, "parallelism");
4370         THREADIDS = U.objectFieldOffset(klass, "threadIds");
4371         TERMINATION = U.objectFieldOffset(klass, "termination");
4372         Class<ForkJoinTask[]> aklass = ForkJoinTask[].class;
4373         ABASE = U.arrayBaseOffset(aklass);
4374         int scale = U.arrayIndexScale(aklass);
4375         ASHIFT = 31 - Integer.numberOfLeadingZeros(scale);
4376         if ((scale & (scale - 1)) != 0)
4377             throw new Error("array index scale not a power of two");
4378 
4379         Class<?> dep = LockSupport.class; // ensure loaded
4380         // allow access to non-public methods
4381         JLA = SharedSecrets.getJavaLangAccess();
4382         SharedSecrets.setJavaUtilConcurrentFJPAccess(
4383             new JavaUtilConcurrentFJPAccess() {
4384                 @Override
4385                 public long beginCompensatedBlock(ForkJoinPool pool) {
4386                     return pool.beginCompensatedBlock();
4387                 }
4388                 public void endCompensatedBlock(ForkJoinPool pool, long post) {
4389                     pool.endCompensatedBlock(post);
4390                 }
4391             });
4392         defaultForkJoinWorkerThreadFactory =
4393             new DefaultForkJoinWorkerThreadFactory();
4394         common = new ForkJoinPool((byte)0);
4395     }
4396 }