ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jsr166y/ForkJoinPool.java
(Generate patch)

Comparing jsr166/src/jsr166y/ForkJoinPool.java (file contents):
Revision 1.137 by dl, Tue Oct 30 14:23:11 2012 UTC vs.
Revision 1.148 by jsr166, Tue Nov 20 06:18:39 2012 UTC

# Line 11 | Line 11 | import java.util.Arrays;
11   import java.util.Collection;
12   import java.util.Collections;
13   import java.util.List;
14 import java.util.Random;
14   import java.util.concurrent.AbstractExecutorService;
15   import java.util.concurrent.Callable;
16   import java.util.concurrent.ExecutorService;
# Line 19 | Line 18 | import java.util.concurrent.Future;
18   import java.util.concurrent.RejectedExecutionException;
19   import java.util.concurrent.RunnableFuture;
20   import java.util.concurrent.TimeUnit;
22 import java.util.concurrent.atomic.AtomicInteger;
23 import java.util.concurrent.atomic.AtomicLong;
24 import java.util.concurrent.locks.AbstractQueuedSynchronizer;
25 import java.util.concurrent.locks.Condition;
21  
22   /**
23   * An {@link ExecutorService} for running {@link ForkJoinTask}s.
# Line 42 | Line 37 | import java.util.concurrent.locks.Condit
37   * ForkJoinPool}s may also be appropriate for use with event-style
38   * tasks that are never joined.
39   *
40 < * <p>A static {@link #commonPool} is available and appropriate for
40 > * <p>A static {@link #commonPool()} is available and appropriate for
41   * most applications. The common pool is used by any ForkJoinTask that
42   * is not explicitly submitted to a specified pool. Using the common
43   * pool normally reduces resource usage (its threads are slowly
44   * reclaimed during periods of non-use, and reinstated upon subsequent
45 < * use).  The common pool is by default constructed with default
51 < * parameters, but these may be controlled by setting any or all of
52 < * the three properties {@code
53 < * java.util.concurrent.ForkJoinPool.common.{parallelism,
54 < * threadFactory, exceptionHandler}}.
45 > * use).
46   *
47   * <p>For applications that require separate or custom pools, a {@code
48   * ForkJoinPool} may be constructed with a given target parallelism
# Line 71 | Line 62 | import java.util.concurrent.locks.Condit
62   * {@link #toString} returns indications of pool state in a
63   * convenient form for informal monitoring.
64   *
65 < * <p> As is the case with other ExecutorServices, there are three
65 > * <p>As is the case with other ExecutorServices, there are three
66   * main task execution methods summarized in the following table.
67   * These are designed to be used primarily by clients not already
68   * engaged in fork/join computations in the current pool.  The main
# Line 106 | Line 97 | import java.util.concurrent.locks.Condit
97   *  </tr>
98   * </table>
99   *
100 + * <p>The common pool is by default constructed with default
101 + * parameters, but these may be controlled by setting three {@link
102 + * System#getProperty properties} with prefix {@code
103 + * java.util.concurrent.ForkJoinPool.common}: {@code parallelism} --
104 + * an integer greater than zero, {@code threadFactory} -- the class
105 + * name of a {@link ForkJoinWorkerThreadFactory}, and {@code
106 + * exceptionHandler} -- the class name of a {@link
107 + * java.lang.Thread.UncaughtExceptionHandler
108 + * Thread.UncaughtExceptionHandler}. Upon any error in establishing
109 + * these settings, default parameters are used.
110 + *
111   * <p><b>Implementation notes</b>: This implementation restricts the
112   * maximum number of running threads to 32767. Attempts to create
113   * pools with greater than the maximum number result in
# Line 192 | Line 194 | public class ForkJoinPool extends Abstra
194       * WorkQueues are also used in a similar way for tasks submitted
195       * to the pool. We cannot mix these tasks in the same queues used
196       * for work-stealing (this would contaminate lifo/fifo
197 <     * processing). Instead, we loosely associate submission queues
197 >     * processing). Instead, we randomly associate submission queues
198       * with submitting threads, using a form of hashing.  The
199       * ThreadLocal Submitter class contains a value initially used as
200       * a hash code for choosing existing queues, but may be randomly
201       * repositioned upon contention with other submitters.  In
202 <     * essence, submitters act like workers except that they never
203 <     * take tasks, and they are multiplexed on to a finite number of
204 <     * shared work queues. However, classes are set up so that future
205 <     * extensions could allow submitters to optionally help perform
206 <     * tasks as well. Insertion of tasks in shared mode requires a
207 <     * lock (mainly to protect in the case of resizing) but we use
208 <     * only a simple spinlock (using bits in field runState), because
209 <     * submitters encountering a busy queue move on to try or create
210 <     * other queues -- they block only when creating and registering
211 <     * new queues.
202 >     * essence, submitters act like workers except that they are
203 >     * restricted to executing local tasks that they submitted (or in
204 >     * the case of CountedCompleters, others with the same root task).
205 >     * However, because most shared/external queue operations are more
206 >     * expensive than internal, and because, at steady state, external
207 >     * submitters will compete for CPU with workers, ForkJoinTask.join
208 >     * and related methods disable them from repeatedly helping to
209 >     * process tasks if all workers are active.  Insertion of tasks in
210 >     * shared mode requires a lock (mainly to protect in the case of
211 >     * resizing) but we use only a simple spinlock (using bits in
212 >     * field qlock), because submitters encountering a busy queue move
213 >     * on to try or create other queues -- they block only when
214 >     * creating and registering new queues.
215       *
216       * Management
217       * ==========
# Line 228 | Line 233 | public class ForkJoinPool extends Abstra
233       * and their negations (used for thresholding) to fit into 16bit
234       * fields.
235       *
236 <     * Field "runState" contains 32 bits needed to register and
237 <     * deregister WorkQueues, as well as to enable shutdown. It is
238 <     * only modified under a lock (normally briefly held, but
239 <     * occasionally protecting allocations and resizings) but even
240 <     * when locked remains available to check consistency.
236 >     * Field "plock" is a form of sequence lock with a saturating
237 >     * shutdown bit (similarly for per-queue "qlocks"), mainly
238 >     * protecting updates to the workQueues array, as well as to
239 >     * enable shutdown.  When used as a lock, it is normally only very
240 >     * briefly held, so is nearly always available after at most a
241 >     * brief spin, but we use a monitor-based backup strategy to
242 >     * block when needed.
243       *
244       * Recording WorkQueues.  WorkQueues are recorded in the
245       * "workQueues" array that is created upon first use and expanded
# Line 241 | Line 248 | public class ForkJoinPool extends Abstra
248       * by a lock but the array is otherwise concurrently readable, and
249       * accessed directly.  To simplify index-based operations, the
250       * array size is always a power of two, and all readers must
251 <     * tolerate null slots. Shared (submission) queues are at even
252 <     * indices, worker queues at odd indices. Grouping them together
253 <     * in this way simplifies and speeds up task scanning.
251 >     * tolerate null slots. Worker queues are at odd indices. Shared
252 >     * (submission) queues are at even indices, up to a maximum of 64
253 >     * slots, to limit growth even if array needs to expand to add
254 >     * more workers. Grouping them together in this way simplifies and
255 >     * speeds up task scanning.
256       *
257       * All worker thread creation is on-demand, triggered by task
258       * submissions, replacement of terminated workers, and/or
# Line 304 | Line 313 | public class ForkJoinPool extends Abstra
313       *
314       * Signalling.  We create or wake up workers only when there
315       * appears to be at least one task they might be able to find and
316 <     * execute.  When a submission is added or another worker adds a
317 <     * task to a queue that previously had fewer than two tasks, they
318 <     * signal waiting workers (or trigger creation of new ones if
319 <     * fewer than the given parallelism level -- see signalWork).
320 <     * These primary signals are buttressed by signals during rescans;
321 <     * together these cover the signals needed in cases when more
322 <     * tasks are pushed but untaken, and improve performance compared
323 <     * to having one thread wake up all workers.
316 >     * execute. However, many other threads may notice the same task
317 >     * and each signal to wake up a thread that might take it. So in
318 >     * general, pools will be over-signalled.  When a submission is
319 >     * added or another worker adds a task to a queue that is
320 >     * apparently empty, they signal waiting workers (or trigger
321 >     * creation of new ones if fewer than the given parallelism
322 >     * level).  These primary signals are buttressed by signals
323 >     * whenever other threads scan for work or do not have a task to
324 >     * process (including the case of leaving a hint to unparked
325 >     * threads to help signal others upon wakeup).  On most platforms,
326 >     * signalling (unpark) overhead time is noticeably long, and the
327 >     * time between signalling a thread and it actually making
328 >     * progress can be very noticeably long, so it is worth offloading
329 >     * these delays from critical paths as much as possible.
330       *
331       * Trimming workers. To release resources after periods of lack of
332       * use, a worker starting to wait when the pool is quiescent will
# Line 322 | Line 337 | public class ForkJoinPool extends Abstra
337       * periods of non-use.
338       *
339       * Shutdown and Termination. A call to shutdownNow atomically sets
340 <     * a runState bit and then (non-atomically) sets each worker's
341 <     * runState status, cancels all unprocessed tasks, and wakes up
340 >     * a plock bit and then (non-atomically) sets each worker's
341 >     * qlock status, cancels all unprocessed tasks, and wakes up
342       * all waiting workers.  Detecting whether termination should
343       * commence after a non-abrupt shutdown() call requires more work
344       * and bookkeeping. We need consensus about quiescence (i.e., that
# Line 351 | Line 366 | public class ForkJoinPool extends Abstra
366       *      method tryCompensate() may create or re-activate a spare
367       *      thread to compensate for blocked joiners until they unblock.
368       *
369 <     * A third form (implemented in tryRemoveAndExec and
370 <     * tryPollForAndExec) amounts to helping a hypothetical
371 <     * compensator: If we can readily tell that a possible action of a
372 <     * compensator is to steal and execute the task being joined, the
373 <     * joining thread can do so directly, without the need for a
374 <     * compensation thread (although at the expense of larger run-time
375 <     * stacks, but the tradeoff is typically worthwhile).
369 >     * A third form (implemented in tryRemoveAndExec) amounts to
370 >     * helping a hypothetical compensator: If we can readily tell that
371 >     * a possible action of a compensator is to steal and execute the
372 >     * task being joined, the joining thread can do so directly,
373 >     * without the need for a compensation thread (although at the
374 >     * expense of larger run-time stacks, but the tradeoff is
375 >     * typically worthwhile).
376       *
377       * The ManagedBlocker extension API can't use helping so relies
378       * only on compensation in method awaitBlocker.
# Line 379 | Line 394 | public class ForkJoinPool extends Abstra
394       * steals, rather than use per-task bookkeeping.  This sometimes
395       * requires a linear scan of workQueues array to locate stealers,
396       * but often doesn't because stealers leave hints (that may become
397 <     * stale/wrong) of where to locate them.  A stealHint is only a
398 <     * hint because a worker might have had multiple steals and the
399 <     * hint records only one of them (usually the most current).
400 <     * Hinting isolates cost to when it is needed, rather than adding
401 <     * to per-task overhead.  (2) It is "shallow", ignoring nesting
402 <     * and potentially cyclic mutual steals.  (3) It is intentionally
397 >     * stale/wrong) of where to locate them.  It is only a hint
398 >     * because a worker might have had multiple steals and the hint
399 >     * records only one of them (usually the most current).  Hinting
400 >     * isolates cost to when it is needed, rather than adding to
401 >     * per-task overhead.  (2) It is "shallow", ignoring nesting and
402 >     * potentially cyclic mutual steals.  (3) It is intentionally
403       * racy: field currentJoin is updated only while actively joining,
404       * which means that we miss links in the chain during long-lived
405       * tasks, GC stalls etc (which is OK since blocking in such cases
# Line 392 | Line 407 | public class ForkJoinPool extends Abstra
407       * to find work (see MAX_HELP) and fall back to suspending the
408       * worker and if necessary replacing it with another.
409       *
410 +     * Helping actions for CountedCompleters are much simpler: Method
411 +     * helpComplete can take and execute any task with the same root
412 +     * as the task being waited on. However, this still entails some
413 +     * traversal of completer chains, so is less efficient than using
414 +     * CountedCompleters without explicit joins.
415 +     *
416       * It is impossible to keep exactly the target parallelism number
417       * of threads running at any given time.  Determining the
418       * existence of conservatively safe helping targets, the
# Line 413 | Line 434 | public class ForkJoinPool extends Abstra
434       * intractable) game with an opponent that may choose the worst
435       * (for us) active thread to stall at any time.  We take several
436       * precautions to bound losses (and thus bound gains), mainly in
437 <     * methods tryCompensate and awaitJoin: (1) We only try
438 <     * compensation after attempting enough helping steps (measured
439 <     * via counting and timing) that we have already consumed the
440 <     * estimated cost of creating and activating a new thread.  (2) We
441 <     * allow up to 50% of threads to be blocked before initially
442 <     * adding any others, and unless completely saturated, check that
443 <     * some work is available for a new worker before adding. Also, we
444 <     * create up to only 50% more threads until entering a mode that
445 <     * only adds a thread if all others are possibly blocked.  All
446 <     * together, this means that we might be half as fast to react,
447 <     * and create half as many threads as possible in the ideal case,
448 <     * but present vastly fewer anomalies in all other cases compared
449 <     * to both more aggressive and more conservative alternatives.
450 <     *
451 <     * Style notes: There is a lot of representation-level coupling
452 <     * among classes ForkJoinPool, ForkJoinWorkerThread, and
453 <     * ForkJoinTask.  The fields of WorkQueue maintain data structures
454 <     * managed by ForkJoinPool, so are directly accessed.  There is
455 <     * little point trying to reduce this, since any associated future
456 <     * changes in representations will need to be accompanied by
457 <     * algorithmic changes anyway. Several methods intrinsically
458 <     * sprawl because they must accumulate sets of consistent reads of
459 <     * volatiles held in local variables.  Methods signalWork() and
460 <     * scan() are the main bottlenecks, so are especially heavily
437 >     * methods tryCompensate and awaitJoin.
438 >     *
439 >     * Common Pool
440 >     * ===========
441 >     *
442 >     * The static commonPool always exists after static
443 >     * initialization.  Since it (or any other created pool) need
444 >     * never be used, we minimize initial construction overhead and
445 >     * footprint to the setup of about a dozen fields, with no nested
446 >     * allocation. Most bootstrapping occurs within method
447 >     * fullExternalPush during the first submission to the pool.
448 >     *
449 >     * When external threads submit to the common pool, they can
450 >     * perform some subtask processing (see externalHelpJoin and
451 >     * related methods).  We do not need to record whether these
452 >     * submissions are to the common pool -- if not, externalHelpJoin
453 >     * returns quickly (at the most helping to signal some common pool
454 >     * workers). These submitters would otherwise be blocked waiting
455 >     * for completion, so the extra effort (with liberally sprinkled
456 >     * task status checks) in inapplicable cases amounts to an odd
457 >     * form of limited spin-wait before blocking in ForkJoinTask.join.
458 >     *
459 >     * Style notes
460 >     * ===========
461 >     *
462 >     * There is a lot of representation-level coupling among classes
463 >     * ForkJoinPool, ForkJoinWorkerThread, and ForkJoinTask.  The
464 >     * fields of WorkQueue maintain data structures managed by
465 >     * ForkJoinPool, so are directly accessed.  There is little point
466 >     * trying to reduce this, since any associated future changes in
467 >     * representations will need to be accompanied by algorithmic
468 >     * changes anyway. Several methods intrinsically sprawl because
469 >     * they must accumulate sets of consistent reads of volatiles held
470 >     * in local variables.  Methods signalWork() and scan() are the
471 >     * main bottlenecks, so are especially heavily
472       * micro-optimized/mangled.  There are lots of inline assignments
473       * (of form "while ((local = field) != 0)") which are usually the
474       * simplest way to ensure the required read orderings (which are
# Line 444 | Line 476 | public class ForkJoinPool extends Abstra
476       * declarations of these locals at the heads of methods or blocks.
477       * There are several occurrences of the unusual "do {} while
478       * (!cas...)"  which is the simplest way to force an update of a
479 <     * CAS'ed variable. There are also other coding oddities that help
479 >     * CAS'ed variable. There are also other coding oddities (including
480 >     * several unnecessary-looking hoisted null checks) that help
481       * some methods perform reasonably even when interpreted (not
482       * compiled).
483       *
# Line 493 | Line 526 | public class ForkJoinPool extends Abstra
526       * Default ForkJoinWorkerThreadFactory implementation; creates a
527       * new ForkJoinWorkerThread.
528       */
529 <    static class DefaultForkJoinWorkerThreadFactory
529 >    static final class DefaultForkJoinWorkerThreadFactory
530          implements ForkJoinWorkerThreadFactory {
531 <        public ForkJoinWorkerThread newThread(ForkJoinPool pool) {
531 >        public final ForkJoinWorkerThread newThread(ForkJoinPool pool) {
532              return new ForkJoinWorkerThread(pool);
533          }
534      }
# Line 507 | Line 540 | public class ForkJoinPool extends Abstra
540       * actually do anything beyond having a unique identity.
541       */
542      static final class EmptyTask extends ForkJoinTask<Void> {
543 +        private static final long serialVersionUID = -7721805057305804111L;
544          EmptyTask() { status = ForkJoinTask.NORMAL; } // force done
545          public final Void getRawResult() { return null; }
546          public final void setRawResult(Void x) {}
# Line 527 | Line 561 | public class ForkJoinPool extends Abstra
561       *
562       * Field "top" is the index (mod array.length) of the next queue
563       * slot to push to or pop from. It is written only by owner thread
564 <     * for push, or under lock for trySharedPush, and accessed by
565 <     * other threads only after reading (volatile) base.  Both top and
566 <     * base are allowed to wrap around on overflow, but (top - base)
567 <     * (or more commonly -(base - top) to force volatile read of base
568 <     * before top) still estimates size.
564 >     * for push, or under lock for external/shared push, and accessed
565 >     * by other threads only after reading (volatile) base.  Both top
566 >     * and base are allowed to wrap around on overflow, but (top -
567 >     * base) (or more commonly -(base - top) to force volatile read of
568 >     * base before top) still estimates size. The lock ("qlock") is
569 >     * forced to -1 on termination, causing all further lock attempts
570 >     * to fail. (Note: we don't need CAS for termination state because
571 >     * upon pool shutdown, all shared-queues will stop being used
572 >     * anyway.)  Nearly all lock bodies are set up so that exceptions
573 >     * within lock bodies are "impossible" (modulo JVM errors that
574 >     * would cause failure anyway.)
575       *
576       * The array slots are read and written using the emulation of
577       * volatiles/atomics provided by Unsafe. Insertions must in
578       * general use putOrderedObject as a form of releasing store to
579       * ensure that all writes to the task object are ordered before
580 <     * its publication in the queue. (Although we can avoid one case
581 <     * of this when locked in trySharedPush.) All removals entail a
582 <     * CAS to null.  The array is always a power of two. To ensure
583 <     * safety of Unsafe array operations, all accesses perform
544 <     * explicit null checks and implicit bounds checks via
545 <     * power-of-two masking.
580 >     * its publication in the queue.  All removals entail a CAS to
581 >     * null.  The array is always a power of two. To ensure safety of
582 >     * Unsafe array operations, all accesses perform explicit null
583 >     * checks and implicit bounds checks via power-of-two masking.
584       *
585       * In addition to basic queuing support, this class contains
586       * fields described elsewhere to control execution. It turns out
587 <     * to work better memory-layout-wise to include them in this
588 <     * class rather than a separate class.
587 >     * to work better memory-layout-wise to include them in this class
588 >     * rather than a separate class.
589       *
590       * Performance on most platforms is very sensitive to placement of
591       * instances of both WorkQueues and their arrays -- we absolutely
# Line 561 | Line 599 | public class ForkJoinPool extends Abstra
599       * trades off slightly slower average field access for the sake of
600       * avoiding really bad worst-case access. (Until better JVM
601       * support is in place, this padding is dependent on transient
602 <     * properties of JVM field layout rules.)  We also take care in
565 <     * allocating, sizing and resizing the array. Non-shared queue
566 <     * arrays are initialized (via method growArray) by workers before
567 <     * use. Others are allocated on first use.
602 >     * properties of JVM field layout rules.)
603       */
604      static final class WorkQueue {
605          /**
# Line 587 | Line 622 | public class ForkJoinPool extends Abstra
622           */
623          static final int MAXIMUM_QUEUE_CAPACITY = 1 << 26; // 64M
624  
590        volatile long totalSteals; // cumulative number of steals
625          int seed;                  // for random scanning; initialize nonzero
626          volatile int eventCount;   // encoded inactivation count; < 0 if inactive
627          int nextWait;              // encoded record of next event waiter
628 <        int rescans;               // remaining scans until block
595 <        int nsteals;               // top-level task executions since last idle
596 <        final int mode;            // lifo, fifo, or shared
628 >        int hint;                  // steal or signal hint (index)
629          int poolIndex;             // index of this queue in pool (or 0)
630 <        int stealHint;             // index of most recent known stealer
631 <        volatile int runState;     // 1: locked, -1: terminate; else 0
630 >        final int mode;            // 0: lifo, > 0: fifo, < 0: shared
631 >        int nsteals;               // number of steals
632 >        volatile int qlock;        // 1: locked, -1: terminate; else 0
633          volatile int base;         // index of next slot for poll
634          int top;                   // index of next slot for push
635          ForkJoinTask<?>[] array;   // the elements (initially unallocated)
# Line 605 | Line 638 | public class ForkJoinPool extends Abstra
638          volatile Thread parker;    // == owner during call to park; else null
639          volatile ForkJoinTask<?> currentJoin;  // task being joined in awaitJoin
640          ForkJoinTask<?> currentSteal; // current non-local task being executed
641 +
642          // Heuristic padding to ameliorate unfortunate memory placements
643          Object p00, p01, p02, p03, p04, p05, p06, p07;
644 <        Object p08, p09, p0a, p0b, p0c, p0d, p0e;
644 >        Object p08, p09, p0a, p0b, p0c;
645  
646 <        WorkQueue(ForkJoinPool pool, ForkJoinWorkerThread owner, int mode) {
647 <            this.mode = mode;
646 >        WorkQueue(ForkJoinPool pool, ForkJoinWorkerThread owner, int mode,
647 >                  int seed) {
648 >            this.array = new ForkJoinTask<?>[WorkQueue.INITIAL_QUEUE_CAPACITY];
649              this.pool = pool;
650              this.owner = owner;
651 <            // Place indices in the center of array (that is not yet allocated)
651 >            this.mode = mode;
652 >            this.seed = seed;
653 >            // Place indices in the center of array
654              base = top = INITIAL_QUEUE_CAPACITY >>> 1;
655          }
656  
657          /**
621         * Returns the approximate number of tasks in the queue.
622         */
623        final int queueSize() {
624            int n = base - top;       // non-owner callers must read base first
625            return (n >= 0) ? 0 : -n; // ignore transient negative
626        }
627
628        /**
629         * Provides a more accurate estimate of whether this queue has
630         * any tasks than does queueSize, by checking whether a
631         * near-empty queue has at least one unclaimed task.
632         */
633        final boolean isEmpty() {
634            ForkJoinTask<?>[] a; int m, s;
635            int n = base - (s = top);
636            return (n >= 0 ||
637                    (n == -1 &&
638                     ((a = array) == null ||
639                      (m = a.length - 1) < 0 ||
640                      U.getObjectVolatile
641                      (a, ((m & (s - 1)) << ASHIFT) + ABASE) == null)));
642        }
643
644        /**
658           * Pushes a task. Call only by owner in unshared queues.
659 +         * Cases needing resizing or rejection are relayed to fullPush
660 +         * (that also handles shared queues).
661           *
662           * @param task the task. Caller must ensure non-null.
663           * @throw RejectedExecutionException if array cannot be resized
# Line 653 | Line 668 | public class ForkJoinPool extends Abstra
668              if ((a = array) != null) {    // ignore if queue removed
669                  U.putOrderedObject
670                      (a, (((m = a.length - 1) & s) << ASHIFT) + ABASE, task);
671 <                if ((n = (top = s + 1) - base) <= 2) {
671 >                if ((n = (top = s + 1) - base) <= 1) {
672                      if ((p = pool) != null)
673 <                        p.signalWork();
673 >                        p.signalWork(this, 0);
674                  }
675                  else if (n >= m)
676 <                    growArray(true);
676 >                    growArray();
677              }
678          }
679  
# Line 671 | Line 686 | public class ForkJoinPool extends Abstra
686           */
687          final boolean trySharedPush(ForkJoinTask<?> task) {
688              boolean submitted = false;
689 <            if (runState == 0 && U.compareAndSwapInt(this, RUNSTATE, 0, 1)) {
690 <                ForkJoinTask<?>[] a = array;
689 >            if (qlock == 0 && U.compareAndSwapInt(this, QLOCK, 0, 1)) {
690 >                ForkJoinTask<?>[] a = array;  ForkJoinPool p;
691                  int s = top;
692                  try {
693                      if ((a != null && a.length > s + 1 - base) ||
694 <                        (a = growArray(false)) != null) { // must presize
694 >                        (a = growArray()) != null) {   // must presize
695                          int j = (((a.length - 1) & s) << ASHIFT) + ABASE;
696 <                        U.putObject(a, (long)j, task);    // don't need "ordered"
696 >                        U.putOrderedObject(a, j, task);
697                          top = s + 1;
698                          submitted = true;
699                      }
700                  } finally {
701 <                    runState = 0;                         // unlock
701 >                    qlock = 0;                         // unlock
702                  }
703 +                if (submitted && (p = pool) != null)
704 +                    p.signalWork(this, 0);
705              }
706              return submitted;
707          }
708  
709 +       /**
710 +         * Initializes or doubles the capacity of array. Call either
711 +         * by owner or with lock held -- it is OK for base, but not
712 +         * top, to move while resizings are in progress.
713 +         */
714 +        final ForkJoinTask<?>[] growArray() {
715 +            ForkJoinTask<?>[] oldA = array;
716 +            int size = oldA != null ? oldA.length << 1 : INITIAL_QUEUE_CAPACITY;
717 +            if (size > MAXIMUM_QUEUE_CAPACITY)
718 +                throw new RejectedExecutionException("Queue capacity exceeded");
719 +            int oldMask, t, b;
720 +            ForkJoinTask<?>[] a = array = new ForkJoinTask<?>[size];
721 +            if (oldA != null && (oldMask = oldA.length - 1) >= 0 &&
722 +                (t = top) - (b = base) > 0) {
723 +                int mask = size - 1;
724 +                do {
725 +                    ForkJoinTask<?> x;
726 +                    int oldj = ((b & oldMask) << ASHIFT) + ABASE;
727 +                    int j    = ((b &    mask) << ASHIFT) + ABASE;
728 +                    x = (ForkJoinTask<?>)U.getObjectVolatile(oldA, oldj);
729 +                    if (x != null &&
730 +                        U.compareAndSwapObject(oldA, oldj, x, null))
731 +                        U.putObjectVolatile(a, j, x);
732 +                } while (++b != t);
733 +            }
734 +            return a;
735 +        }
736 +
737          /**
738           * Takes next task, if one exists, in LIFO order.  Call only
739           * by owner in unshared queues.
# Line 709 | Line 754 | public class ForkJoinPool extends Abstra
754              return null;
755          }
756  
712        final ForkJoinTask<?> sharedPop() {
713            ForkJoinTask<?> task = null;
714            if (runState == 0 && U.compareAndSwapInt(this, RUNSTATE, 0, 1)) {
715                try {
716                    ForkJoinTask<?>[] a; int m;
717                    if ((a = array) != null && (m = a.length - 1) >= 0) {
718                        for (int s; (s = top - 1) - base >= 0;) {
719                            long j = ((m & s) << ASHIFT) + ABASE;
720                            ForkJoinTask<?> t =
721                                (ForkJoinTask<?>)U.getObject(a, j);
722                            if (t == null)
723                                break;
724                            if (U.compareAndSwapObject(a, j, t, null)) {
725                                top = s;
726                                task = t;
727                                break;
728                            }
729                        }
730                    }
731                } finally {
732                    runState = 0;
733                }
734            }
735            return task;
736        }
737
738        /**
739         * Version of pop that takes top element only if it
740         * its root is the given CountedCompleter.
741         */
742        final ForkJoinTask<?> popCC(CountedCompleter<?> root) {
743            ForkJoinTask<?>[] a; int m;
744            if (root != null && (a = array) != null && (m = a.length - 1) >= 0) {
745                for (int s; (s = top - 1) - base >= 0;) {
746                    long j = ((m & s) << ASHIFT) + ABASE;
747                    ForkJoinTask<?> t =
748                        (ForkJoinTask<?>)U.getObject(a, j);
749                    if (t == null || !(t instanceof CountedCompleter) ||
750                        ((CountedCompleter<?>)t).getRoot() != root)
751                        break;
752                    if (U.compareAndSwapObject(a, j, t, null)) {
753                        top = s;
754                        return t;
755                    }
756                    if (root.status < 0)
757                        break;
758                }
759            }
760            return null;
761        }
762
763        /**
764         * Shared version of popCC
765         */
766        final ForkJoinTask<?> sharedPopCC(CountedCompleter<?> root) {
767            ForkJoinTask<?> task = null;
768            if (root != null &&
769                runState == 0 && U.compareAndSwapInt(this, RUNSTATE, 0, 1)) {
770                try {
771                    ForkJoinTask<?>[] a; int m;
772                    if ((a = array) != null && (m = a.length - 1) >= 0) {
773                        for (int s; (s = top - 1) - base >= 0;) {
774                            long j = ((m & s) << ASHIFT) + ABASE;
775                            ForkJoinTask<?> t =
776                                (ForkJoinTask<?>)U.getObject(a, j);
777                            if (t == null || !(t instanceof CountedCompleter) ||
778                                ((CountedCompleter<?>)t).getRoot() != root)
779                                break;
780                            if (U.compareAndSwapObject(a, j, t, null)) {
781                                top = s;
782                                task = t;
783                                break;
784                            }
785                            if (root.status < 0)
786                                break;
787                        }
788                    }
789                } finally {
790                    runState = 0;
791                }
792            }
793            return task;
794        }
795
757          /**
758           * Takes a task in FIFO order if b is base of queue and a task
759           * can be claimed without contention. Specialized versions
# Line 830 | Line 791 | public class ForkJoinPool extends Abstra
791                  else if (base == b) {
792                      if (b + 1 == top)
793                          break;
794 <                    Thread.yield(); // wait for lagging update
794 >                    Thread.yield(); // wait for lagging update (very rare)
795                  }
796              }
797              return null;
# Line 857 | Line 818 | public class ForkJoinPool extends Abstra
818  
819          /**
820           * Pops the given task only if it is at the current top.
821 +         * (A shared version is available only via FJP.tryExternalUnpush)
822           */
823          final boolean tryUnpush(ForkJoinTask<?> t) {
824              ForkJoinTask<?>[] a; int s;
# Line 870 | Line 832 | public class ForkJoinPool extends Abstra
832          }
833  
834          /**
873         * Version of tryUnpush for shared queues; called by non-FJ
874         * submitters after prechecking that task probably exists.
875         */
876        final boolean trySharedUnpush(ForkJoinTask<?> t) {
877            boolean success = false;
878            if (runState == 0 && U.compareAndSwapInt(this, RUNSTATE, 0, 1)) {
879                try {
880                    ForkJoinTask<?>[] a; int s;
881                    if ((a = array) != null && (s = top) != base &&
882                        U.compareAndSwapObject
883                        (a, (((a.length - 1) & --s) << ASHIFT) + ABASE, t, null)) {
884                        top = s;
885                        success = true;
886                    }
887                } finally {
888                    runState = 0;                         // unlock
889                }
890            }
891            return success;
892        }
893
894        /**
895         * Polls the given task only if it is at the current base.
896         */
897        final boolean pollFor(ForkJoinTask<?> task) {
898            ForkJoinTask<?>[] a; int b;
899            if ((b = base) - top < 0 && (a = array) != null) {
900                int j = (((a.length - 1) & b) << ASHIFT) + ABASE;
901                if (U.getObjectVolatile(a, j) == task && base == b &&
902                    U.compareAndSwapObject(a, j, task, null)) {
903                    base = b + 1;
904                    return true;
905                }
906            }
907            return false;
908        }
909
910        /**
911         * Initializes or doubles the capacity of array. Call either
912         * by owner or with lock held -- it is OK for base, but not
913         * top, to move while resizings are in progress.
914         *
915         * @param rejectOnFailure if true, throw exception if capacity
916         * exceeded (relayed ultimately to user); else return null.
917         */
918        final ForkJoinTask<?>[] growArray(boolean rejectOnFailure) {
919            ForkJoinTask<?>[] oldA = array;
920            int size = oldA != null ? oldA.length << 1 : INITIAL_QUEUE_CAPACITY;
921            if (size <= MAXIMUM_QUEUE_CAPACITY) {
922                int oldMask, t, b;
923                ForkJoinTask<?>[] a = array = new ForkJoinTask<?>[size];
924                if (oldA != null && (oldMask = oldA.length - 1) >= 0 &&
925                    (t = top) - (b = base) > 0) {
926                    int mask = size - 1;
927                    do {
928                        ForkJoinTask<?> x;
929                        int oldj = ((b & oldMask) << ASHIFT) + ABASE;
930                        int j    = ((b &    mask) << ASHIFT) + ABASE;
931                        x = (ForkJoinTask<?>)U.getObjectVolatile(oldA, oldj);
932                        if (x != null &&
933                            U.compareAndSwapObject(oldA, oldj, x, null))
934                            U.putObjectVolatile(a, j, x);
935                    } while (++b != t);
936                }
937                return a;
938            }
939            else if (!rejectOnFailure)
940                return null;
941            else
942                throw new RejectedExecutionException("Queue capacity exceeded");
943        }
944
945        /**
835           * Removes and cancels all known tasks, ignoring any exceptions.
836           */
837          final void cancelAll() {
# Line 966 | Line 855 | public class ForkJoinPool extends Abstra
855              return seed = r ^= r << 5;
856          }
857  
858 <        // Execution methods
858 >        /**
859 >         * Provides a more accurate estimate of size than (top - base)
860 >         * by ordering reads and checking whether a near-empty queue
861 >         * has at least one unclaimed task.
862 >         */
863 >        final int queueSize() {
864 >            ForkJoinTask<?>[] a; int k, s, n;
865 >            return ((n = base - (s = top)) < 0 &&
866 >                    (n != -1 ||
867 >                     ((a = array) != null && (k = a.length) > 0 &&
868 >                      U.getObject
869 >                      (a, (long)((((k - 1) & (s - 1)) << ASHIFT) + ABASE)) != null))) ?
870 >                -n : 0;
871 >        }
872 >
873 >        // Specialized execution methods
874  
875          /**
876           * Pops and runs tasks until empty.
# Line 995 | Line 899 | public class ForkJoinPool extends Abstra
899          }
900  
901          /**
902 <         * If present, removes from queue and executes the given task, or
903 <         * any other cancelled task. Returns (true) immediately on any CAS
902 >         * If present, removes from queue and executes the given task,
903 >         * or any other cancelled task. Returns (true) on any CAS
904           * or consistency check failure so caller can retry.
905           *
906 <         * @return 0 if no progress can be made, else positive
1003 <         * (this unusual convention simplifies use with tryHelpStealer.)
906 >         * @return false if no progress can be made, else true;
907           */
908 <        final int tryRemoveAndExec(ForkJoinTask<?> task) {
909 <            int stat = 1;
1007 <            boolean removed = false, empty = true;
908 >        final boolean tryRemoveAndExec(ForkJoinTask<?> task) {
909 >            boolean stat = true, removed = false, empty = true;
910              ForkJoinTask<?>[] a; int m, s, b, n;
911              if ((a = array) != null && (m = a.length - 1) >= 0 &&
912                  (n = (s = top) - (b = base)) > 0) {
# Line 1034 | Line 936 | public class ForkJoinPool extends Abstra
936                      }
937                      if (--n == 0) {
938                          if (!empty && base == b)
939 <                            stat = 0;
939 >                            stat = false;
940                          break;
941                      }
942                  }
# Line 1045 | Line 947 | public class ForkJoinPool extends Abstra
947          }
948  
949          /**
950 +         * Polls for and executes the given task or any other task in
951 +         * its CountedCompleter computation
952 +         */
953 +        final boolean pollAndExecCC(ForkJoinTask<?> root) {
954 +            ForkJoinTask<?>[] a; int b; Object o;
955 +            outer: while ((b = base) - top < 0 && (a = array) != null) {
956 +                long j = (((a.length - 1) & b) << ASHIFT) + ABASE;
957 +                if ((o = U.getObject(a, j)) == null ||
958 +                    !(o instanceof CountedCompleter))
959 +                    break;
960 +                for (CountedCompleter<?> t = (CountedCompleter<?>)o, r = t;;) {
961 +                    if (r == root) {
962 +                        if (base == b &&
963 +                            U.compareAndSwapObject(a, j, t, null)) {
964 +                            base = b + 1;
965 +                            t.doExec();
966 +                            return true;
967 +                        }
968 +                        else
969 +                            break; // restart
970 +                    }
971 +                    if ((r = r.completer) == null)
972 +                        break outer; // not part of root computation
973 +                }
974 +            }
975 +            return false;
976 +        }
977 +
978 +        /**
979           * Executes a top-level task and any local tasks remaining
980           * after execution.
981           */
982          final void runTask(ForkJoinTask<?> t) {
983              if (t != null) {
984 <                currentSteal = t;
985 <                t.doExec();
984 >                (currentSteal = t).doExec();
985 >                currentSteal = null;
986 >                ++nsteals;
987                  if (top != base) {       // process remaining local tasks
988                      if (mode == 0)
989                          popAndExecAll();
990                      else
991                          pollAndExecAll();
992                  }
1061                ++nsteals;
1062                currentSteal = null;
993              }
994          }
995  
# Line 1069 | Line 999 | public class ForkJoinPool extends Abstra
999          final void runSubtask(ForkJoinTask<?> t) {
1000              if (t != null) {
1001                  ForkJoinTask<?> ps = currentSteal;
1002 <                currentSteal = t;
1073 <                t.doExec();
1002 >                (currentSteal = t).doExec();
1003                  currentSteal = ps;
1004              }
1005          }
# Line 1105 | Line 1034 | public class ForkJoinPool extends Abstra
1034  
1035          // Unsafe mechanics
1036          private static final sun.misc.Unsafe U;
1037 <        private static final long RUNSTATE;
1037 >        private static final long QLOCK;
1038          private static final int ABASE;
1039          private static final int ASHIFT;
1040          static {
# Line 1114 | Line 1043 | public class ForkJoinPool extends Abstra
1043                  U = getUnsafe();
1044                  Class<?> k = WorkQueue.class;
1045                  Class<?> ak = ForkJoinTask[].class;
1046 <                RUNSTATE = U.objectFieldOffset
1047 <                    (k.getDeclaredField("runState"));
1046 >                QLOCK = U.objectFieldOffset
1047 >                    (k.getDeclaredField("qlock"));
1048                  ABASE = U.arrayBaseOffset(ak);
1049                  s = U.arrayIndexScale(ak);
1050              } catch (Exception e) {
# Line 1127 | Line 1056 | public class ForkJoinPool extends Abstra
1056          }
1057      }
1058  
1059 +    // static fields (initialized in static initializer below)
1060 +
1061 +    /**
1062 +     * Creates a new ForkJoinWorkerThread. This factory is used unless
1063 +     * overridden in ForkJoinPool constructors.
1064 +     */
1065 +    public static final ForkJoinWorkerThreadFactory
1066 +        defaultForkJoinWorkerThreadFactory;
1067 +
1068      /**
1069       * Per-thread records for threads that submit to pools. Currently
1070       * holds only pseudo-random seed / index that is used to choose
1071 <     * submission queues in method doSubmit. In the future, this may
1071 >     * submission queues in method externalPush. In the future, this may
1072       * also incorporate a means to implement different task rejection
1073       * and resubmission policies.
1074       *
# Line 1138 | Line 1076 | public class ForkJoinPool extends Abstra
1076       * the same way but are initialized and updated using slightly
1077       * different mechanics. Both are initialized using the same
1078       * approach as in class ThreadLocal, where successive values are
1079 <     * unlikely to collide with previous values. This is done during
1080 <     * registration for workers, but requires a separate AtomicInteger
1081 <     * for submitters. Seeds are then randomly modified upon
1144 <     * collisions using xorshifts, which requires a non-zero seed.
1079 >     * unlikely to collide with previous values. Seeds are then
1080 >     * randomly modified upon collisions using xorshifts, which
1081 >     * requires a non-zero seed.
1082       */
1083      static final class Submitter {
1084          int seed;
1085 <        Submitter() {
1149 <            int s = nextSubmitterSeed.getAndAdd(SEED_INCREMENT);
1150 <            seed = (s == 0) ? 1 : s; // ensure non-zero
1151 <        }
1152 <    }
1153 <
1154 <    /** ThreadLocal class for Submitters */
1155 <    static final class ThreadSubmitter extends ThreadLocal<Submitter> {
1156 <        public Submitter initialValue() { return new Submitter(); }
1085 >        Submitter(int s) { seed = s; }
1086      }
1087  
1159    // static fields (initialized in static initializer below)
1160
1088      /**
1089 <     * Creates a new ForkJoinWorkerThread. This factory is used unless
1090 <     * overridden in ForkJoinPool constructors.
1089 >     * Per-thread submission bookkeeping. Shared across all pools
1090 >     * to reduce ThreadLocal pollution and because random motion
1091 >     * to avoid contention in one pool is likely to hold for others.
1092 >     * Lazily initialized on first submission (but null-checked
1093 >     * in other contexts to avoid unnecessary initialization).
1094       */
1095 <    public static final ForkJoinWorkerThreadFactory
1166 <        defaultForkJoinWorkerThreadFactory;
1167 <
1168 <
1169 <    /** Property prefix for constructing common pool */
1170 <    private static final String propPrefix =
1171 <        "java.util.concurrent.ForkJoinPool.common.";
1095 >    static final ThreadLocal<Submitter> submitters;
1096  
1097      /**
1098       * Common (static) pool. Non-null for public use unless a static
1099 <     * construction exception, but internal usages must null-check on
1100 <     * use.
1099 >     * construction exception, but internal usages null-check on use
1100 >     * to paranoically avoid potential initialization circularities
1101 >     * as well as to simplify generated code.
1102       */
1103      static final ForkJoinPool commonPool;
1104  
1105      /**
1106 <     * Common pool parallelism. Must equal commonPool.parallelism.
1107 <     */
1183 <    static final int commonPoolParallelism;
1184 <
1185 <    /**
1186 <     * Generator for assigning sequence numbers as pool names.
1106 >     * Permission required for callers of methods that may start or
1107 >     * kill threads.
1108       */
1109 <    private static final AtomicInteger poolNumberGenerator;
1109 >    private static final RuntimePermission modifyThreadPermission;
1110  
1111      /**
1112 <     * Generator for initial hashes/seeds for submitters. Accessed by
1192 <     * Submitter class constructor.
1112 >     * Common pool parallelism. Must equal commonPool.parallelism.
1113       */
1114 <    static final AtomicInteger nextSubmitterSeed;
1114 >    static final int commonPoolParallelism;
1115  
1116      /**
1117 <     * Permission required for callers of methods that may start or
1198 <     * kill threads.
1117 >     * Sequence number for creating workerNamePrefix.
1118       */
1119 <    private static final RuntimePermission modifyThreadPermission;
1119 >    private static int poolNumberSequence;
1120  
1121      /**
1122 <     * Per-thread submission bookkeeping. Shared across all pools
1123 <     * to reduce ThreadLocal pollution and because random motion
1205 <     * to avoid contention in one pool is likely to hold for others.
1122 >     * Return the next sequence number. We don't expect this to
1123 >     * ever contend so use simple builtin sync.
1124       */
1125 <    private static final ThreadSubmitter submitters;
1125 >    private static final synchronized int nextPoolId() {
1126 >        return ++poolNumberSequence;
1127 >    }
1128  
1129      // static constants
1130  
1131      /**
1132 <     * Initial timeout value (in nanoseconds) for the thread triggering
1133 <     * quiescence to park waiting for new work. On timeout, the thread
1134 <     * will instead try to shrink the number of workers.
1132 >     * Initial timeout value (in nanoseconds) for the thread
1133 >     * triggering quiescence to park waiting for new work. On timeout,
1134 >     * the thread will instead try to shrink the number of
1135 >     * workers. The value should be large enough to avoid overly
1136 >     * aggressive shrinkage during most transient stalls (long GCs
1137 >     * etc).
1138       */
1139 <    private static final long IDLE_TIMEOUT      = 1000L * 1000L * 1000L; // 1sec
1139 >    private static final long IDLE_TIMEOUT      = 2000L * 1000L * 1000L; // 2sec
1140  
1141      /**
1142       * Timeout value when there are more threads than parallelism level
1143       */
1144 <    private static final long FAST_IDLE_TIMEOUT =  100L * 1000L * 1000L;
1144 >    private static final long FAST_IDLE_TIMEOUT =  200L * 1000L * 1000L;
1145  
1146      /**
1147       * The maximum stolen->joining link depth allowed in method
1148 <     * tryHelpStealer.  Must be a power of two. This value also
1226 <     * controls the maximum number of times to try to help join a task
1227 <     * without any apparent progress or change in pool state before
1228 <     * giving up and blocking (see awaitJoin).  Depths for legitimate
1148 >     * tryHelpStealer.  Must be a power of two.  Depths for legitimate
1149       * chains are unbounded, but we use a fixed constant to avoid
1150       * (otherwise unchecked) cycles and to bound staleness of
1151       * traversal parameters at the expense of sometimes blocking when
# Line 1234 | Line 1154 | public class ForkJoinPool extends Abstra
1154      private static final int MAX_HELP = 64;
1155  
1156      /**
1237     * Secondary time-based bound (in nanosecs) for helping attempts
1238     * before trying compensated blocking in awaitJoin. Used in
1239     * conjunction with MAX_HELP to reduce variance due to different
1240     * polling rates associated with different helping options. The
1241     * value should roughly approximate the time required to create
1242     * and/or activate a worker thread.
1243     */
1244    private static final long COMPENSATION_DELAY = 1L << 18; // ~0.25 millisec
1245
1246    /**
1157       * Increment for seed generators. See class ThreadLocal for
1158       * explanation.
1159       */
# Line 1277 | Line 1187 | public class ForkJoinPool extends Abstra
1187       * scan for them to avoid queuing races. Note however that
1188       * eventCount updates lag releases so usage requires care.
1189       *
1190 <     * Field runState is an int packed with:
1190 >     * Field plock is an int packed with:
1191       * SHUTDOWN: true if shutdown is enabled (1 bit)
1192 <     * SEQ:  a sequence number updated upon (de)registering workers (30 bits)
1193 <     * INIT: set true after workQueues array construction (1 bit)
1192 >     * SEQ:  a sequence lock, with PL_LOCK bit set if locked (30 bits)
1193 >     * SIGNAL: set when threads may be waiting on the lock (1 bit)
1194       *
1195       * The sequence number enables simple consistency checks:
1196       * Staleness of read-only operations on the workQueues array can
1197 <     * be checked by comparing runState before vs after the reads.
1197 >     * be checked by comparing plock before vs after the reads.
1198       */
1199  
1200      // bit positions/shifts for fields
# Line 1296 | Line 1206 | public class ForkJoinPool extends Abstra
1206      // bounds
1207      private static final int  SMASK      = 0xffff;  // short bits
1208      private static final int  MAX_CAP    = 0x7fff;  // max #workers - 1
1209 <    private static final int  SQMASK     = 0xfffe;  // even short bits
1209 >    private static final int  EVENMASK   = 0xfffe;  // even short bits
1210 >    private static final int  SQMASK     = 0x007e;  // max 64 (even) slots
1211      private static final int  SHORT_SIGN = 1 << 15;
1212      private static final int  INT_SIGN   = 1 << 31;
1213  
# Line 1321 | Line 1232 | public class ForkJoinPool extends Abstra
1232      private static final int E_MASK      = 0x7fffffff; // no STOP_BIT
1233      private static final int E_SEQ       = 1 << EC_SHIFT;
1234  
1235 <    // runState bits
1235 >    // plock bits
1236      private static final int SHUTDOWN    = 1 << 31;
1237 +    private static final int PL_LOCK     = 2;
1238 +    private static final int PL_SIGNAL   = 1;
1239 +    private static final int PL_SPINS    = 1 << 8;
1240  
1241      // access mode for WorkQueue
1242      static final int LIFO_QUEUE          =  0;
1243      static final int FIFO_QUEUE          =  1;
1244      static final int SHARED_QUEUE        = -1;
1245  
1246 +    // bounds for #steps in scan loop -- must be power 2 minus 1
1247 +    private static final int MIN_SCAN    = 0x1ff;   // cover estimation slop
1248 +    private static final int MAX_SCAN    = 0x1ffff; // 4 * max workers
1249 +
1250      // Instance fields
1251  
1252      /*
1253 <     * Field layout order in this class tends to matter more than one
1254 <     * would like. Runtime layout order is only loosely related to
1253 >     * Field layout of this class tends to matter more than one would
1254 >     * like. Runtime layout order is only loosely related to
1255       * declaration order and may differ across JVMs, but the following
1256       * empirically works OK on current JVMs.
1257       */
1340
1258      volatile long stealCount;                  // collects worker counts
1259      volatile long ctl;                         // main pool control
1260 <    final int parallelism;                     // parallelism level
1261 <    final int localMode;                       // per-worker scheduling mode
1262 <    volatile int nextWorkerNumber;             // to create worker name string
1346 <    final int submitMask;                      // submit queue index bound
1347 <    int nextSeed;                              // for initializing worker seeds
1348 <    volatile int mainLock;                     // spinlock for array updates
1349 <    volatile int runState;                     // shutdown status and seq
1260 >    volatile int plock;                        // shutdown status and seqLock
1261 >    volatile int indexSeed;                    // worker/submitter index seed
1262 >    final int config;                          // mode and parallelism level
1263      WorkQueue[] workQueues;                    // main registry
1264 <    final ForkJoinWorkerThreadFactory factory; // factory for new workers
1264 >    final ForkJoinWorkerThreadFactory factory;
1265      final Thread.UncaughtExceptionHandler ueh; // per-worker UEH
1266      final String workerNamePrefix;             // to create worker name string
1267  
1268      /*
1269 <     * Mechanics for main lock protecting worker array updates.  Uses
1270 <     * the same strategy as ConcurrentHashMap bins -- a spinLock for
1271 <     * normal cases, but falling back to builtin lock when (rarely)
1272 <     * needed.  See internal ConcurrentHashMap documentation for
1273 <     * explanation.
1274 <     */
1275 <
1276 <    static final int LOCK_WAITING = 2; // bit to indicate need for signal
1277 <    static final int MAX_LOCK_SPINS = 1 << 8;
1278 <
1279 <    private void tryAwaitMainLock() {
1280 <        int spins = MAX_LOCK_SPINS, r = 0, h;
1281 <        while (((h = mainLock) & 1) != 0) {
1282 <            if (r == 0)
1283 <                r = ThreadLocalRandom.current().nextInt(); // randomize spins
1269 >     * Acquires the plock lock to protect worker array and related
1270 >     * updates. This method is called only if an initial CAS on plock
1271 >     * fails. This acts as a spinLock for normal cases, but falls back
1272 >     * to builtin monitor to block when (rarely) needed. This would be
1273 >     * a terrible idea for a highly contended lock, but works fine as
1274 >     * a more conservative alternative to a pure spinlock.  See
1275 >     * internal ConcurrentHashMap documentation for further
1276 >     * explanation of nearly the same construction.
1277 >     */
1278 >    private int acquirePlock() {
1279 >        int spins = PL_SPINS, r = 0, ps, nps;
1280 >        for (;;) {
1281 >            if (((ps = plock) & PL_LOCK) == 0 &&
1282 >                U.compareAndSwapInt(this, PLOCK, ps, nps = ps + PL_LOCK))
1283 >                return nps;
1284 >            else if (r == 0) { // randomize spins if possible
1285 >                Thread t = Thread.currentThread(); WorkQueue w; Submitter z;
1286 >                if ((t instanceof ForkJoinWorkerThread) &&
1287 >                    (w = ((ForkJoinWorkerThread)t).workQueue) != null)
1288 >                    r = w.seed;
1289 >                else if ((z = submitters.get()) != null)
1290 >                    r = z.seed;
1291 >                else
1292 >                    r = 1;
1293 >            }
1294              else if (spins >= 0) {
1295                  r ^= r << 1; r ^= r >>> 3; r ^= r << 10; // xorshift
1296                  if (r >= 0)
1297                      --spins;
1298              }
1299 <            else if (U.compareAndSwapInt(this, MAINLOCK, h, h | LOCK_WAITING)) {
1299 >            else if (U.compareAndSwapInt(this, PLOCK, ps, ps | PL_SIGNAL)) {
1300                  synchronized (this) {
1301 <                    if ((mainLock & LOCK_WAITING) != 0) {
1301 >                    if ((plock & PL_SIGNAL) != 0) {
1302                          try {
1303                              wait();
1304                          } catch (InterruptedException ie) {
1305 <                            Thread.currentThread().interrupt();
1305 >                            try {
1306 >                                Thread.currentThread().interrupt();
1307 >                            } catch (SecurityException ignore) {
1308 >                            }
1309                          }
1310                      }
1311                      else
1312 <                        notifyAll(); // possibly won race vs signaller
1312 >                        notifyAll();
1313                  }
1388                break;
1314              }
1315          }
1316      }
1317  
1318 <    //  Creating, registering, and deregistering workers
1318 >    /**
1319 >     * Unlocks and signals any thread waiting for plock. Called only
1320 >     * when CAS of seq value for unlock fails.
1321 >     */
1322 >    private void releasePlock(int ps) {
1323 >        plock = ps;
1324 >        synchronized (this) { notifyAll(); }
1325 >    }
1326  
1327      /**
1328 <     * Tries to create and start a worker
1328 >     * Tries to create and start a worker; adjusts counts etc on failure
1329       */
1330      private void addWorker() {
1399        Throwable ex = null;
1331          ForkJoinWorkerThread wt = null;
1332          try {
1333 <            if ((wt = factory.newThread(this)) != null) {
1334 <                wt.start();
1335 <                return;
1405 <            }
1406 <        } catch (Throwable e) {
1407 <            ex = e;
1333 >            (wt = factory.newThread(this)).start();
1334 >        } catch (Throwable ex) {
1335 >            deregisterWorker(wt, ex); // adjust on failure
1336          }
1409        deregisterWorker(wt, ex); // adjust counts etc on failure
1337      }
1338  
1339      /**
1340 <     * Callback from ForkJoinWorkerThread constructor to assign a
1341 <     * public name. This must be separate from registerWorker because
1342 <     * it is called during the "super" constructor call in
1343 <     * ForkJoinWorkerThread.
1344 <     */
1345 <    final String nextWorkerName() {
1346 <        int n;
1347 <        do {} while(!U.compareAndSwapInt(this, NEXTWORKERNUMBER,
1348 <                                         n = nextWorkerNumber, ++n));
1349 <        return workerNamePrefix.concat(Integer.toString(n));
1340 >     * Performs secondary initialization, called when plock is zero.
1341 >     * Creates workQueue array and sets plock to a valid value.  The
1342 >     * lock body must be exception-free (so no try/finally) so we
1343 >     * optimistically allocate new array outside the lock and throw
1344 >     * away if (very rarely) not needed. (A similar tactic is used in
1345 >     * fullExternalPush.)  Because the plock seq value can eventually
1346 >     * wrap around zero, this method harmlessly fails to reinitialize
1347 >     * if workQueues exists, while still advancing plock.
1348 >     */
1349 >    private void initWorkQueuesArray() {
1350 >        WorkQueue[] ws; int ps;
1351 >        int p = config & SMASK;        // find power of two table size
1352 >        int n = (p > 1) ? p - 1 : 1;   // ensure at least 2 slots
1353 >        n |= n >>> 1; n |= n >>> 2; n |= n >>> 4; n |= n >>> 8; n |= n >>> 16;
1354 >        WorkQueue[] nws = new WorkQueue[(n + 1) << 1];
1355 >        if (((ps = plock) & PL_LOCK) != 0 ||
1356 >            !U.compareAndSwapInt(this, PLOCK, ps, ps += PL_LOCK))
1357 >            ps = acquirePlock();
1358 >        if ((ws = workQueues) == null || ws.length == 0)
1359 >            workQueues = nws;
1360 >        int nps = (ps & SHUTDOWN) | ((ps + PL_LOCK) & ~SHUTDOWN);
1361 >        if (!U.compareAndSwapInt(this, PLOCK, ps, nps))
1362 >            releasePlock(nps);
1363 >        long c; int u;
1364 >        if ((u = (int)((c = ctl) >>> 32)) < 0 && (int)c == 0) {
1365 >            long nc = (long)(((u + UTC_UNIT) & UTC_MASK) |
1366 >                             ((u + UAC_UNIT) & UAC_MASK)) << 32;
1367 >            if (U.compareAndSwapLong(this, CTL, c, nc))
1368 >                addWorker();
1369 >        }
1370 >
1371      }
1372  
1373 +    //  Registering and deregistering workers
1374 +
1375      /**
1376 <     * Callback from ForkJoinWorkerThread constructor to establish its
1377 <     * poolIndex and record its WorkQueue. To avoid scanning bias due
1378 <     * to packing entries in front of the workQueues array, we treat
1379 <     * the array as a simple power-of-two hash table using per-thread
1380 <     * seed as hash, expanding as needed.
1376 >     * Callback from ForkJoinWorkerThread to establish and record its
1377 >     * WorkQueue. To avoid scanning bias due to packing entries in
1378 >     * front of the workQueues array, we treat the array as a simple
1379 >     * power-of-two hash table using per-thread seed as hash,
1380 >     * expanding as needed.
1381       *
1382 <     * @param w the worker's queue
1382 >     * @param wt the worker thread
1383       */
1384 <    final void registerWorker(WorkQueue w) {
1385 <        while (!U.compareAndSwapInt(this, MAINLOCK, 0, 1))
1386 <            tryAwaitMainLock();
1387 <        try {
1388 <            WorkQueue[] ws;
1389 <            if ((ws = workQueues) == null)
1390 <                ws = workQueues = new WorkQueue[submitMask + 1];
1391 <            if (w != null) {
1392 <                int rs, n =  ws.length, m = n - 1;
1393 <                int s = nextSeed += SEED_INCREMENT; // rarely-colliding sequence
1394 <                w.seed = (s == 0) ? 1 : s;          // ensure non-zero seed
1395 <                int r = (s << 1) | 1;               // use odd-numbered indices
1396 <                if (ws[r &= m] != null) {           // collision
1397 <                    int probes = 0;                 // step by approx half size
1398 <                    int step = (n <= 4) ? 2 : ((n >>> 1) & SQMASK) + 2;
1399 <                    while (ws[r = (r + step) & m] != null) {
1400 <                        if (++probes >= n) {
1401 <                            workQueues = ws = Arrays.copyOf(ws, n <<= 1);
1402 <                            m = n - 1;
1403 <                            probes = 0;
1384 >    final void registerWorker(ForkJoinWorkerThread wt) {
1385 >        if (wt != null && wt.workQueue == null) {
1386 >            int s, ps;    // generate a rarely colliding candidate index seed
1387 >            do {} while (!U.compareAndSwapInt(this, INDEXSEED, s = indexSeed,
1388 >                                              s += SEED_INCREMENT) ||
1389 >                         s == 0); // skip 0
1390 >            WorkQueue w = new WorkQueue(this, wt, config >>> 16, s);
1391 >            if (((ps = plock) & PL_LOCK) != 0 ||
1392 >                !U.compareAndSwapInt(this, PLOCK, ps, ps += PL_LOCK))
1393 >                ps = acquirePlock();
1394 >            int nps = (ps & SHUTDOWN) | ((ps + PL_LOCK) & ~SHUTDOWN);
1395 >            try {
1396 >                WorkQueue[] ws;
1397 >                if ((ws = workQueues) != null && wt.workQueue == null) {
1398 >                    int n = ws.length, m = n - 1;
1399 >                    int r = (s << 1) | 1;           // use odd-numbered indices
1400 >                    if (ws[r &= m] != null) {       // collision
1401 >                        int probes = 0;             // step by approx half size
1402 >                        int step = (n <= 4) ? 2 : ((n >>> 1) & EVENMASK) + 2;
1403 >                        while (ws[r = (r + step) & m] != null) {
1404 >                            if (++probes >= n) {
1405 >                                workQueues = ws = Arrays.copyOf(ws, n <<= 1);
1406 >                                m = n - 1;
1407 >                                probes = 0;
1408 >                            }
1409                          }
1410                      }
1411 +                    w.eventCount = w.poolIndex = r; // volatile write orders
1412 +                    wt.workQueue = ws[r] = w;
1413                  }
1414 <                w.eventCount = w.poolIndex = r;     // establish before recording
1415 <                ws[r] = w;                          // also update seq
1416 <                runState = ((rs = runState) & SHUTDOWN) | ((rs + 2) & ~SHUTDOWN);
1460 <            }
1461 <        } finally {
1462 <            if (!U.compareAndSwapInt(this, MAINLOCK, 1, 0)) {
1463 <                mainLock = 0;
1464 <                synchronized (this) { notifyAll(); };
1414 >            } finally {
1415 >                if (!U.compareAndSwapInt(this, PLOCK, ps, nps))
1416 >                    releasePlock(nps);
1417              }
1418          }
1467
1419      }
1420  
1421      /**
1422       * Final callback from terminating worker, as well as upon failure
1423 <     * to construct or start a worker in addWorker.  Removes record of
1424 <     * worker from array, and adjusts counts. If pool is shutting
1425 <     * down, tries to complete termination.
1423 >     * to construct or start a worker.  Removes record of worker from
1424 >     * array, and adjusts counts. If pool is shutting down, tries to
1425 >     * complete termination.
1426       *
1427 <     * @param wt the worker thread or null if addWorker failed
1427 >     * @param wt the worker thread or null if construction failed
1428       * @param ex the exception causing failure, or null if none
1429       */
1430      final void deregisterWorker(ForkJoinWorkerThread wt, Throwable ex) {
1431          WorkQueue w = null;
1432          if (wt != null && (w = wt.workQueue) != null) {
1433 <            w.runState = -1;                // ensure runState is set
1434 <            long steals = w.totalSteals + w.nsteals, sc;
1435 <            do {} while(!U.compareAndSwapLong(this, STEALCOUNT,
1436 <                                              sc = stealCount, sc + steals));
1437 <            int idx = w.poolIndex;
1438 <            while (!U.compareAndSwapInt(this, MAINLOCK, 0, 1))
1439 <                tryAwaitMainLock();
1433 >            int ps;
1434 >            w.qlock = -1;                // ensure set
1435 >            long ns = w.nsteals, sc;     // collect steal count
1436 >            do {} while (!U.compareAndSwapLong(this, STEALCOUNT,
1437 >                                               sc = stealCount, sc + ns));
1438 >            if (((ps = plock) & PL_LOCK) != 0 ||
1439 >                !U.compareAndSwapInt(this, PLOCK, ps, ps += PL_LOCK))
1440 >                ps = acquirePlock();
1441 >            int nps = (ps & SHUTDOWN) | ((ps + PL_LOCK) & ~SHUTDOWN);
1442              try {
1443 +                int idx = w.poolIndex;
1444                  WorkQueue[] ws = workQueues;
1445                  if (ws != null && idx >= 0 && idx < ws.length && ws[idx] == w)
1446                      ws[idx] = null;
1447              } finally {
1448 <                if (!U.compareAndSwapInt(this, MAINLOCK, 1, 0)) {
1449 <                    mainLock = 0;
1496 <                    synchronized (this) { notifyAll(); };
1497 <                }
1448 >                if (!U.compareAndSwapInt(this, PLOCK, ps, nps))
1449 >                    releasePlock(nps);
1450              }
1451          }
1452  
# Line 1507 | Line 1459 | public class ForkJoinPool extends Abstra
1459          if (!tryTerminate(false, false) && w != null) {
1460              w.cancelAll();                  // cancel remaining tasks
1461              if (w.array != null)            // suppress signal if never ran
1462 <                signalWork();               // wake up or create replacement
1462 >                helpSignal(null, 0);        // wake up or create replacement
1463              if (ex == null)                 // help clean refs on way out
1464                  ForkJoinTask.helpExpungeStaleExceptions();
1465          }
1466  
1467          if (ex != null)                     // rethrow
1468 <            U.throwException(ex);
1468 >            ForkJoinTask.rethrow(ex);
1469      }
1470  
1471      // Submissions
# Line 1521 | Line 1473 | public class ForkJoinPool extends Abstra
1473      /**
1474       * Unless shutting down, adds the given task to a submission queue
1475       * at submitter's current queue index (modulo submission
1476 <     * range). If no queue exists at the index, one is created.  If
1477 <     * the queue is busy, another index is randomly chosen. The
1526 <     * submitMask bounds the effective number of queues to the
1527 <     * (nearest power of two for) parallelism level.
1476 >     * range). Only the most common path is directly handled in this
1477 >     * method. All others are relayed to fullExternalPush.
1478       *
1479       * @param task the task. Caller must ensure non-null.
1480       */
1481 <    private void doSubmit(ForkJoinTask<?> task) {
1482 <        Submitter s = submitters.get();
1483 <        for (int r = s.seed, m = submitMask;;) {
1484 <            WorkQueue[] ws; WorkQueue q;
1485 <            int k = r & m & SQMASK;          // use only even indices
1486 <            if (runState < 0)
1487 <                throw new RejectedExecutionException(); // shutting down
1488 <            else if ((ws = workQueues) == null || ws.length <= k) {
1489 <                while (!U.compareAndSwapInt(this, MAINLOCK, 0, 1))
1490 <                    tryAwaitMainLock();
1491 <                try {
1492 <                    if (workQueues == null)
1493 <                        workQueues = new WorkQueue[submitMask + 1];
1544 <                } finally {
1545 <                    if (!U.compareAndSwapInt(this, MAINLOCK, 1, 0)) {
1546 <                        mainLock = 0;
1547 <                        synchronized (this) { notifyAll(); };
1548 <                    }
1549 <                }
1550 <            }
1551 <            else if ((q = ws[k]) == null) {  // create new queue
1552 <                WorkQueue nq = new WorkQueue(this, null, SHARED_QUEUE);
1553 <                while (!U.compareAndSwapInt(this, MAINLOCK, 0, 1))
1554 <                    tryAwaitMainLock();
1555 <                try {
1556 <                    int rs = runState;       // to update seq
1557 <                    if (ws == workQueues && ws[k] == null) {
1558 <                        ws[k] = nq;
1559 <                        runState = ((rs & SHUTDOWN) | ((rs + 2) & ~SHUTDOWN));
1560 <                    }
1561 <                } finally {
1562 <                    if (!U.compareAndSwapInt(this, MAINLOCK, 1, 0)) {
1563 <                        mainLock = 0;
1564 <                        synchronized (this) { notifyAll(); };
1565 <                    }
1566 <                }
1567 <            }
1568 <            else if (q.trySharedPush(task)) {
1569 <                signalWork();
1481 >    final void externalPush(ForkJoinTask<?> task) {
1482 >        WorkQueue[] ws; WorkQueue q; Submitter z; int m; ForkJoinTask<?>[] a;
1483 >        if ((z = submitters.get()) != null && plock > 0 &&
1484 >            (ws = workQueues) != null && (m = (ws.length - 1)) >= 0 &&
1485 >            (q = ws[m & z.seed & SQMASK]) != null &&
1486 >            U.compareAndSwapInt(q, QLOCK, 0, 1)) { // lock
1487 >            int b = q.base, s = q.top, n, an;
1488 >            if ((a = q.array) != null && (an = a.length) > (n = s + 1 - b)) {
1489 >                U.putObject(a, (long)(((an - 1) & s) << ASHIFT) + ABASE, task);
1490 >                q.top = s + 1;                     // push on to deque
1491 >                q.qlock = 0;
1492 >                if (n <= 2)
1493 >                    signalWork(q, 0);
1494                  return;
1495              }
1496 <            else if (m > 1) {                // move to a different index
1496 >            q.qlock = 0;
1497 >        }
1498 >        fullExternalPush(task);
1499 >    }
1500 >
1501 >    /**
1502 >     * Full version of externalPush. This method is called, among
1503 >     * other times, upon the first submission of the first task to the
1504 >     * pool, so must perform secondary initialization (via
1505 >     * initWorkQueuesArray). It also detects first submission by an
1506 >     * external thread by looking up its ThreadLocal, and creates a
1507 >     * new shared queue if the one at index if empty or contended. The
1508 >     * lock body must be exception-free (so no try/finally) so we
1509 >     * optimistically allocate new queues outside the lock and throw
1510 >     * them away if (very rarely) not needed.
1511 >     */
1512 >    private void fullExternalPush(ForkJoinTask<?> task) {
1513 >        int r = 0;
1514 >        for (Submitter z = submitters.get();;) {
1515 >            WorkQueue[] ws; WorkQueue q; int ps, m, k;
1516 >            if (z == null) {
1517 >                if (U.compareAndSwapInt(this, INDEXSEED, r = indexSeed,
1518 >                                        r += SEED_INCREMENT) && r != 0)
1519 >                    submitters.set(z = new Submitter(r));
1520 >            }
1521 >            else if (r == 0) {               // move to a different index
1522 >                r = z.seed;
1523                  r ^= r << 13;                // same xorshift as WorkQueues
1524                  r ^= r >>> 17;
1525 <                s.seed = r ^= r << 5;
1525 >                z.seed = r ^ (r << 5);
1526 >            }
1527 >            else if ((ps = plock) < 0)
1528 >                throw new RejectedExecutionException();
1529 >            else if (ps == 0 || (ws = workQueues) == null ||
1530 >                     (m = ws.length - 1) < 0)
1531 >                initWorkQueuesArray();
1532 >            else if ((q = ws[k = r & m & SQMASK]) != null) {
1533 >                if (q.trySharedPush(task))
1534 >                    return;
1535 >                else
1536 >                    r = 0; // move on contention
1537 >            }
1538 >            else if (((ps = plock) & PL_LOCK) == 0) { // create new queue
1539 >                q = new WorkQueue(this, null, SHARED_QUEUE, r);
1540 >                if (((ps = plock) & PL_LOCK) != 0 ||
1541 >                    !U.compareAndSwapInt(this, PLOCK, ps, ps += PL_LOCK))
1542 >                    ps = acquirePlock();
1543 >                if ((ws = workQueues) != null && k < ws.length && ws[k] == null)
1544 >                    ws[k] = q;
1545 >                int nps = (ps & SHUTDOWN) | ((ps + PL_LOCK) & ~SHUTDOWN);
1546 >                if (!U.compareAndSwapInt(this, PLOCK, ps, nps))
1547 >                    releasePlock(nps);
1548              }
1549              else
1550 <                Thread.yield();              // yield if no alternatives
1550 >                r = 0; // try elsewhere while lock held
1551          }
1552      }
1553  
1582    /**
1583     * Submits the given (non-null) task to the common pool, if possible.
1584     */
1585    static void submitToCommonPool(ForkJoinTask<?> task) {
1586        ForkJoinPool p;
1587        if ((p = commonPool) == null)
1588            throw new RejectedExecutionException("Common Pool Unavailable");
1589        p.doSubmit(task);
1590    }
1591
1592    /**
1593     * Returns true if caller is (or may be) submitter to the common
1594     * pool, and not all workers are active, and there appear to be
1595     * tasks in the associated submission queue.
1596     */
1597    static boolean canHelpCommonPool() {
1598        ForkJoinPool p; WorkQueue[] ws; WorkQueue q;
1599        int k = submitters.get().seed & SQMASK;
1600        return ((p = commonPool) != null &&
1601                (int)(p.ctl >> AC_SHIFT) < 0 &&
1602                (ws = p.workQueues) != null &&
1603                ws.length > (k &= p.submitMask) &&
1604                (q = ws[k]) != null &&
1605                q.top - q.base > 0);
1606    }
1607
1608    /**
1609     * Returns true if the given task was submitted to common pool
1610     * and has not yet commenced execution, and is available for
1611     * removal according to execution policies; if so removing the
1612     * submission from the pool.
1613     *
1614     * @param task the task
1615     * @return true if successful
1616     */
1617    static boolean tryUnsubmitFromCommonPool(ForkJoinTask<?> task) {
1618        // Peek, looking for task and eligibility before
1619        // using trySharedUnpush to actually take it under lock
1620        ForkJoinPool p; WorkQueue[] ws; WorkQueue q;
1621        ForkJoinTask<?>[] a; int s;
1622        int k = submitters.get().seed & SQMASK;
1623        return ((p = commonPool) != null &&
1624                (int)(p.ctl >> AC_SHIFT) < 0 &&
1625                (ws = p.workQueues) != null &&
1626                ws.length > (k &= p.submitMask) &&
1627                (q = ws[k]) != null &&
1628                (a = q.array) != null &&
1629                (s = q.top - 1) - q.base >= 0 &&
1630                s >= 0 && s < a.length &&
1631                a[s] == task &&
1632                q.trySharedUnpush(task));
1633    }
1634
1635    /**
1636     * Tries to pop a task from common pool with given root
1637     */
1638    static ForkJoinTask<?> popCCFromCommonPool(CountedCompleter<?> root) {
1639        ForkJoinPool p; WorkQueue[] ws; WorkQueue q;
1640        ForkJoinTask<?> t;
1641        int k = submitters.get().seed & SQMASK;
1642        if (root != null &&
1643            (p = commonPool) != null &&
1644            (int)(p.ctl >> AC_SHIFT) < 0 &&
1645            (ws = p.workQueues) != null &&
1646            ws.length > (k &= p.submitMask) &&
1647            (q = ws[k]) != null && q.top - q.base > 0 &&
1648            root.status < 0 &&
1649            (t = q.sharedPopCC(root)) != null)
1650            return t;
1651        return null;
1652    }
1653
1654
1554      // Maintaining ctl counts
1555  
1556      /**
# Line 1663 | Line 1562 | public class ForkJoinPool extends Abstra
1562      }
1563  
1564      /**
1565 <     * Tries to create one or activate one or more workers if too few are active.
1566 <     */
1567 <    final void signalWork() {
1568 <        long c; int u;
1569 <        while ((u = (int)((c = ctl) >>> 32)) < 0) {     // too few active
1570 <            WorkQueue[] ws = workQueues; int e, i; WorkQueue w; Thread p;
1571 <            if ((e = (int)c) > 0) {                     // at least one waiting
1572 <                if (ws != null && (i = e & SMASK) < ws.length &&
1565 >     * Tries to create (at most one) or activate (possibly several)
1566 >     * workers if too few are active. On contention failure, continues
1567 >     * until at least one worker is signalled or the given queue is
1568 >     * empty or all workers are active.
1569 >     *
1570 >     * @param q if non-null, the queue holding tasks to be signalled
1571 >     * @param signals the target number of signals (at least one --
1572 >     * if argument is zero also sets signallee hint if parked).
1573 >     */
1574 >    final void signalWork(WorkQueue q, int signals) {
1575 >        long c; int e, u, i, s; WorkQueue[] ws; WorkQueue w; Thread p;
1576 >        while ((u = (int)((c = ctl) >>> 32)) < 0) {
1577 >            if ((e = (int)c) > 0) {
1578 >                if ((ws = workQueues) != null && ws.length > (i = e & SMASK) &&
1579                      (w = ws[i]) != null && w.eventCount == (e | INT_SIGN)) {
1580                      long nc = (((long)(w.nextWait & E_MASK)) |
1581                                 ((long)(u + UAC_UNIT) << 32));
1582                      if (U.compareAndSwapLong(this, CTL, c, nc)) {
1583                          w.eventCount = (e + E_SEQ) & E_MASK;
1584 <                        if ((p = w.parker) != null)
1585 <                            U.unpark(p);                // activate and release
1586 <                        break;
1584 >                        if ((p = w.parker) != null) {
1585 >                            if (q != null && signals == 0)
1586 >                                w.hint = q.poolIndex;
1587 >                            U.unpark(p);
1588 >                        }
1589 >                        if (--signals <= 0)
1590 >                            break;
1591                      }
1592 +                    if (q != null && (s = q.queueSize()) <= signals &&
1593 +                         (signals = s) <= 0)
1594 +                        break;
1595                  }
1596                  else
1597                      break;
1598              }
1599 <            else if (e == 0 && (u & SHORT_SIGN) != 0) { // too few total
1599 >            else if (e == 0 && (u & SHORT_SIGN) != 0) {
1600                  long nc = (long)(((u + UTC_UNIT) & UTC_MASK) |
1601                                   ((u + UAC_UNIT) & UAC_MASK)) << 32;
1602                  if (U.compareAndSwapLong(this, CTL, c, nc)) {
# Line 1703 | Line 1615 | public class ForkJoinPool extends Abstra
1615       * Top-level runloop for workers, called by ForkJoinWorkerThread.run.
1616       */
1617      final void runWorker(WorkQueue w) {
1618 <        w.growArray(false);         // initialize queue array in this thread
1619 <        do { w.runTask(scan(w)); } while (w.runState >= 0);
1618 >        if (w != null) // skip on initialization failure
1619 >            do { w.runTask(scan(w)); } while (w.qlock >= 0);
1620      }
1621  
1622      /**
# Line 1715 | Line 1627 | public class ForkJoinPool extends Abstra
1627       * contention, or state changes that indicate possible success on
1628       * re-invocation.
1629       *
1630 <     * The scan searches for tasks across a random permutation of
1631 <     * queues (starting at a random index and stepping by a random
1632 <     * relative prime, checking each at least once).  The scan
1633 <     * terminates upon either finding a non-empty queue, or completing
1634 <     * the sweep. If the worker is not inactivated, it takes and
1635 <     * returns a task from this queue.  On failure to find a task, we
1636 <     * take one of the following actions, after which the caller will
1637 <     * retry calling this method unless terminated.
1630 >     * The scan searches for tasks across queues (starting at a random
1631 >     * index, and relying on registerWorker to irregularly scatter
1632 >     * them within array to avoid bias), checking each at least twice.
1633 >     * The scan terminates upon either finding a non-empty queue, or
1634 >     * completing the sweep. If the worker is not inactivated, it
1635 >     * takes and returns a task from this queue. Otherwise, if not
1636 >     * activated, it signals workers (that may include itself) and
1637 >     * returns so caller can retry. Also returns for true if the
1638 >     * worker array may have changed during an empty scan.  On failure
1639 >     * to find a task, we take one of the following actions, after
1640 >     * which the caller will retry calling this method unless
1641 >     * terminated.
1642       *
1643       * * If pool is terminating, terminate the worker.
1644       *
1729     * * If not a complete sweep, try to release a waiting worker.  If
1730     * the scan terminated because the worker is inactivated, then the
1731     * released worker will often be the calling worker, and it can
1732     * succeed obtaining a task on the next call. Or maybe it is
1733     * another worker, but with same net effect. Releasing in other
1734     * cases as well ensures that we have enough workers running.
1735     *
1645       * * If not already enqueued, try to inactivate and enqueue the
1646       * worker on wait queue. Or, if inactivating has caused the pool
1647       * to be quiescent, relay to idleAwaitWork to check for
1648       * termination and possibly shrink pool.
1649       *
1650 <     * * If already inactive, and the caller has run a task since the
1651 <     * last empty scan, return (to allow rescan) unless others are
1652 <     * also inactivated.  Field WorkQueue.rescans counts down on each
1744 <     * scan to ensure eventual inactivation and blocking.
1745 <     *
1746 <     * * If already enqueued and none of the above apply, park
1747 <     * awaiting signal,
1650 >     * * If already enqueued and none of the above apply, possibly
1651 >     * (with 1/2 probability) park awaiting signal, else lingering to
1652 >     * help scan and signal.
1653       *
1654       * @param w the worker (via its WorkQueue)
1655       * @return a task or null if none found
1656       */
1657      private final ForkJoinTask<?> scan(WorkQueue w) {
1658 <        WorkQueue[] ws;                       // first update random seed
1659 <        int r = w.seed; r ^= r << 13; r ^= r >>> 17; w.seed = r ^= r << 5;
1660 <        int rs = runState, m;                 // volatile read order matters
1661 <        if ((ws = workQueues) != null && (m = ws.length - 1) > 0) {
1662 <            int ec = w.eventCount;            // ec is negative if inactive
1663 <            int step = (r >>> 16) | 1;        // relative prime
1664 <            for (int j = (m + 1) << 2; ; r += step) {
1665 <                WorkQueue q; ForkJoinTask<?> t; ForkJoinTask<?>[] a; int b;
1666 <                if ((q = ws[r & m]) != null && (b = q.base) - q.top < 0 &&
1762 <                    (a = q.array) != null) {  // probably nonempty
1658 >        WorkQueue[] ws; int m, hint;
1659 >        int ps = plock;                          // read plock before ws
1660 >        if (w != null && (ws = workQueues) != null && (m = ws.length - 1) >= 0) {
1661 >            int ec = w.eventCount;               // ec is negative if inactive
1662 >            int r = w.seed; r ^= r << 13; r ^= r >>> 17; w.seed = r ^= r << 5;
1663 >            for (int j = ((m + m + 1) | MIN_SCAN) & MAX_SCAN; ; --j) {
1664 >                WorkQueue q; ForkJoinTask<?>[] a; int b;
1665 >                if ((q = ws[(r + j) & m]) != null && (b = q.base) - q.top < 0 &&
1666 >                    (a = q.array) != null) {     // probably nonempty
1667                      int i = (((a.length - 1) & b) << ASHIFT) + ABASE;
1668 <                    t = (ForkJoinTask<?>)U.getObjectVolatile(a, i);
1668 >                    ForkJoinTask<?> t = (ForkJoinTask<?>)
1669 >                        U.getObjectVolatile(a, i);
1670                      if (q.base == b && ec >= 0 && t != null &&
1671                          U.compareAndSwapObject(a, i, t, null)) {
1672 <                        if (q.top - (q.base = b + 1) > 0)
1673 <                            signalWork();    // help pushes signal
1674 <                        return t;
1672 >                        if ((q.base = b + 1) - q.top < 0)
1673 >                            signalWork(q, 0);
1674 >                        return t;                // taken
1675                      }
1676 <                    else if (ec < 0 || j <= m) {
1677 <                        rs = 0;               // mark scan as imcomplete
1678 <                        break;                // caller can retry after release
1676 >                    else if (ec < 0 || j < m) {  // cannot take or cannot rescan
1677 >                        w.hint = q.poolIndex;    // use hint below
1678 >                        break;                   // let caller retry after signal
1679                      }
1680                  }
1681 <                if (--j < 0)
1682 <                    break;
1683 <            }
1684 <
1685 <            long c = ctl; int e = (int)c, a = (int)(c >> AC_SHIFT), nr, ns;
1686 <            if (e < 0)                        // decode ctl on empty scan
1782 <                w.runState = -1;              // pool is terminating
1783 <            else if (rs == 0 || rs != runState) { // incomplete scan
1784 <                WorkQueue v; Thread p;        // try to release a waiter
1785 <                if (e > 0 && a < 0 && w.eventCount == ec &&
1786 <                    (v = ws[e & m]) != null && v.eventCount == (e | INT_SIGN)) {
1787 <                    long nc = ((long)(v.nextWait & E_MASK) |
1788 <                               ((c + AC_UNIT) & (AC_MASK|TC_MASK)));
1789 <                    if (ctl == c && U.compareAndSwapLong(this, CTL, c, nc)) {
1790 <                        v.eventCount = (e + E_SEQ) & E_MASK;
1791 <                        if ((p = v.parker) != null)
1792 <                            U.unpark(p);
1681 >                else if (j < 0) { // end of scan; in loop to simplify code
1682 >                    long c, sc; int e, ns;
1683 >                    if ((ns = w.nsteals) != 0) {
1684 >                        if (U.compareAndSwapLong(this, STEALCOUNT,
1685 >                                                 sc = stealCount, sc + ns))
1686 >                            w.nsteals = 0;       // collect steals
1687                      }
1688 +                    else if (plock != ps)        // ws may have changed
1689 +                        break;
1690 +                    else if ((e = (int)(c = ctl)) < 0)
1691 +                        w.qlock = -1;            // pool is terminating
1692 +                    else if (ec >= 0) {          // try to enqueue/inactivate
1693 +                        long nc = ((long)ec |
1694 +                                   ((c - AC_UNIT) & (AC_MASK|TC_MASK)));
1695 +                        w.nextWait = e;          // link and mark inactive
1696 +                        w.hint = -1;             // use hint if set while parked
1697 +                        w.eventCount = ec | INT_SIGN;
1698 +                        if (ctl != c ||
1699 +                            !U.compareAndSwapLong(this, CTL, c, nc))
1700 +                            w.eventCount = ec;  // unmark on CAS failure
1701 +                        else if ((int)(c >> AC_SHIFT) == 1 - (config & SMASK))
1702 +                            idleAwaitWork(w, nc, c);
1703 +                    }
1704 +                    else if (w.eventCount < 0) { // block
1705 +                        Thread wt = Thread.currentThread();
1706 +                        Thread.interrupted();    // clear status
1707 +                        U.putObject(wt, PARKBLOCKER, this);
1708 +                        w.parker = wt;           // emulate LockSupport.park
1709 +                        if (w.eventCount < 0)    // recheck
1710 +                            U.park(false, 0L);
1711 +                        w.parker = null;
1712 +                        U.putObject(wt, PARKBLOCKER, null);
1713 +                    }
1714 +                    break;
1715                  }
1716              }
1717 <            else if (ec >= 0) {               // try to enqueue/inactivate
1718 <                long nc = (long)ec | ((c - AC_UNIT) & (AC_MASK|TC_MASK));
1719 <                w.nextWait = e;
1720 <                w.eventCount = ec | INT_SIGN; // mark as inactive
1721 <                if (ctl != c || !U.compareAndSwapLong(this, CTL, c, nc))
1722 <                    w.eventCount = ec;        // unmark on CAS failure
1802 <                else {
1803 <                    if ((ns = w.nsteals) != 0) {
1804 <                        w.nsteals = 0;        // set rescans if ran task
1805 <                        w.rescans = (a > 0) ? 0 : a + parallelism;
1806 <                        w.totalSteals += ns;
1807 <                    }
1808 <                    if (a == 1 - parallelism) // quiescent
1809 <                        idleAwaitWork(w, nc, c);
1810 <                }
1811 <            }
1812 <            else if (w.eventCount < 0) {      // already queued
1813 <                int ac = a + parallelism;
1814 <                if ((nr = w.rescans) > 0)     // continue rescanning
1815 <                    w.rescans = (ac < nr) ? ac : nr - 1;
1816 <                else if (((w.seed >>> 16) & ac) == 0) { // randomize park
1817 <                    Thread.interrupted();     // clear status
1818 <                    Thread wt = Thread.currentThread();
1819 <                    U.putObject(wt, PARKBLOCKER, this);
1820 <                    w.parker = wt;            // emulate LockSupport.park
1821 <                    if (w.eventCount < 0)     // recheck
1822 <                        U.park(false, 0L);
1823 <                    w.parker = null;
1824 <                    U.putObject(wt, PARKBLOCKER, null);
1825 <                }
1717 >            if ((hint = w.hint) >= 0) {          // help signal
1718 >                WorkQueue[] vs; WorkQueue v; int k;
1719 >                w.hint = -1;                     // suppress resignal
1720 >                if ((vs = workQueues) != null && hint < vs.length &&
1721 >                    (v = vs[hint]) != null && (k = v.base - v.top) < -1)
1722 >                    signalWork(v, 1 - k);
1723              }
1724          }
1725          return null;
# Line 1841 | Line 1738 | public class ForkJoinPool extends Abstra
1738       * @param prevCtl the ctl value to restore if thread is terminated
1739       */
1740      private void idleAwaitWork(WorkQueue w, long currentCtl, long prevCtl) {
1741 <        if (w.eventCount < 0 && !tryTerminate(false, false) &&
1742 <            (int)prevCtl != 0 && !hasQueuedSubmissions() && ctl == currentCtl) {
1741 >        if (w != null && w.eventCount < 0 &&
1742 >            !tryTerminate(false, false) && (int)prevCtl != 0) {
1743              int dc = -(short)(currentCtl >>> TC_SHIFT);
1744              long parkTime = dc < 0 ? FAST_IDLE_TIMEOUT: (dc + 1) * IDLE_TIMEOUT;
1745              long deadline = System.nanoTime() + parkTime - 100000L; // 1ms slop
# Line 1860 | Line 1757 | public class ForkJoinPool extends Abstra
1757                  if (deadline - System.nanoTime() <= 0L &&
1758                      U.compareAndSwapLong(this, CTL, currentCtl, prevCtl)) {
1759                      w.eventCount = (w.eventCount + E_SEQ) | E_MASK;
1760 <                    w.runState = -1;   // shrink
1760 >                    w.qlock = -1;   // shrink
1761 >                    w.hint = -1;    // suppress helping
1762                      break;
1763                  }
1764              }
# Line 1868 | Line 1766 | public class ForkJoinPool extends Abstra
1766      }
1767  
1768      /**
1769 +     * Scans through queues looking for work (optionally, while
1770 +     * joining a task); if any are present, signals. May return early
1771 +     * if more signalling is detectably unneeded.
1772 +     *
1773 +     * @param task if non-null, return early if done
1774 +     * @param origin an index to start scan
1775 +     */
1776 +    final int helpSignal(ForkJoinTask<?> task, int origin) {
1777 +        WorkQueue[] ws; WorkQueue q; int m, n, s, u;
1778 +        if ((ws = workQueues) != null && (m = ws.length - 1) >= 0) {
1779 +            for (int i = 0; i <= m; ++i) {
1780 +                if (task != null && (s = task.status) < 0)
1781 +                    return s;
1782 +                if ((q = ws[(i + origin) & m]) != null &&
1783 +                    (n = q.queueSize()) > 0) {
1784 +                    signalWork(q, n);
1785 +                    if ((u = (int)(ctl >>> 32)) >= 0 || (u >> UAC_SHIFT) >= 0)
1786 +                        break;
1787 +                }
1788 +            }
1789 +        }
1790 +        return 0;
1791 +    }
1792 +
1793 +    /**
1794       * Tries to locate and execute tasks for a stealer of the given
1795       * task, or in turn one of its stealers, Traces currentSteal ->
1796       * currentJoin links looking for a thread working on a descendant
# Line 1898 | Line 1821 | public class ForkJoinPool extends Abstra
1821                      }
1822                      if ((ws = workQueues) == null || (m = ws.length - 1) <= 0)
1823                          break restart;              // shutting down
1824 <                    if ((v = ws[h = (j.stealHint | 1) & m]) == null ||
1824 >                    if ((v = ws[h = (j.hint | 1) & m]) == null ||
1825                          v.currentSteal != subtask) {
1826                          for (int origin = h;;) {    // find stealer
1827                              if (((h = (h + 2) & m) & 15) == 1 &&
# Line 1906 | Line 1829 | public class ForkJoinPool extends Abstra
1829                                  continue restart;   // occasional staleness check
1830                              if ((v = ws[h]) != null &&
1831                                  v.currentSteal == subtask) {
1832 <                                j.stealHint = h;    // save hint
1832 >                                j.hint = h;        // save hint
1833                                  break;
1834                              }
1835                              if (h == origin)
# Line 1954 | Line 1877 | public class ForkJoinPool extends Abstra
1877      }
1878  
1879      /**
1880 <     * If task is at base of some steal queue, steals and executes it.
1880 >     * Analog of tryHelpStealer for CountedCompleters. Tries to steal
1881 >     * and run tasks within the target's computation.
1882 >     *
1883 >     * @param task the task to join
1884 >     * @param mode if shared, exit upon completing any task
1885 >     * if all workers are active
1886       *
1959     * @param joiner the joining worker
1960     * @param task the task
1887       */
1888 <    private void tryPollForAndExec(WorkQueue joiner, ForkJoinTask<?> task) {
1889 <        WorkQueue[] ws;
1890 <        if ((ws = workQueues) != null) {
1891 <            for (int j = 1; j < ws.length && task.status >= 0; j += 2) {
1892 <                WorkQueue q = ws[j];
1893 <                if (q != null && q.pollFor(task)) {
1894 <                    joiner.runSubtask(task);
1895 <                    break;
1888 >    private int helpComplete(ForkJoinTask<?> task, int mode) {
1889 >        WorkQueue[] ws; WorkQueue q; int m, n, s, u;
1890 >        if (task != null && (ws = workQueues) != null &&
1891 >            (m = ws.length - 1) >= 0) {
1892 >            for (int j = 1, origin = j;;) {
1893 >                if ((s = task.status) < 0)
1894 >                    return s;
1895 >                if ((q = ws[j & m]) != null && q.pollAndExecCC(task)) {
1896 >                    origin = j;
1897 >                    if (mode == SHARED_QUEUE &&
1898 >                        ((u = (int)(ctl >>> 32)) >= 0 || (u >> UAC_SHIFT) >= 0))
1899 >                        break;
1900                  }
1901 +                else if ((j = (j + 2) & m) == origin)
1902 +                    break;
1903              }
1904          }
1905 +        return 0;
1906      }
1907  
1908      /**
1909       * Tries to decrement active count (sometimes implicitly) and
1910       * possibly release or create a compensating worker in preparation
1911       * for blocking. Fails on contention or termination. Otherwise,
1912 <     * adds a new thread if no idle workers are available and either
1913 <     * pool would become completely starved or: (at least half
1981 <     * starved, and fewer than 50% spares exist, and there is at least
1982 <     * one task apparently available). Even though the availability
1983 <     * check requires a full scan, it is worthwhile in reducing false
1984 <     * alarms.
1985 <     *
1986 <     * @param task if non-null, a task being waited for
1987 <     * @param blocker if non-null, a blocker being waited for
1988 <     * @return true if the caller can block, else should recheck and retry
1912 >     * adds a new thread if no idle workers are available and pool
1913 >     * may become starved.
1914       */
1915 <    final boolean tryCompensate(ForkJoinTask<?> task, ManagedBlocker blocker) {
1916 <        int pc = parallelism, e;
1917 <        long c = ctl;
1918 <        WorkQueue[] ws = workQueues;
1919 <        if ((e = (int)c) >= 0 && ws != null) {
1920 <            int u, a, ac, hc;
1921 <            int tc = (short)((u = (int)(c >>> 32)) >>> UTC_SHIFT) + pc;
1922 <            boolean replace = false;
1923 <            if ((a = u >> UAC_SHIFT) <= 0) {
1924 <                if ((ac = a + pc) <= 1)
1925 <                    replace = true;
1926 <                else if ((e > 0 || (task != null &&
1927 <                                    ac <= (hc = pc >>> 1) && tc < pc + hc))) {
2003 <                    WorkQueue w;
2004 <                    for (int j = 0; j < ws.length; ++j) {
2005 <                        if ((w = ws[j]) != null && !w.isEmpty()) {
2006 <                            replace = true;
2007 <                            break;   // in compensation range and tasks available
2008 <                        }
2009 <                    }
1915 >    final boolean tryCompensate() {
1916 >        int pc = config & SMASK, e, i, tc; long c;
1917 >        WorkQueue[] ws; WorkQueue w; Thread p;
1918 >        if ((ws = workQueues) != null && (e = (int)(c = ctl)) >= 0) {
1919 >            if (e != 0 && (i = e & SMASK) < ws.length &&
1920 >                (w = ws[i]) != null && w.eventCount == (e | INT_SIGN)) {
1921 >                long nc = ((long)(w.nextWait & E_MASK) |
1922 >                           (c & (AC_MASK|TC_MASK)));
1923 >                if (U.compareAndSwapLong(this, CTL, c, nc)) {
1924 >                    w.eventCount = (e + E_SEQ) & E_MASK;
1925 >                    if ((p = w.parker) != null)
1926 >                        U.unpark(p);
1927 >                    return true;   // replace with idle worker
1928                  }
1929              }
1930 <            if ((task == null || task.status >= 0) && // recheck need to block
1931 <                (blocker == null || !blocker.isReleasable()) && ctl == c) {
1932 <                if (!replace) {          // no compensation
1933 <                    long nc = ((c - AC_UNIT) & AC_MASK) | (c & ~AC_MASK);
1934 <                    if (U.compareAndSwapLong(this, CTL, c, nc))
1935 <                        return true;
1936 <                }
1937 <                else if (e != 0) {       // release an idle worker
1938 <                    WorkQueue w; Thread p; int i;
1939 <                    if ((i = e & SMASK) < ws.length && (w = ws[i]) != null) {
1940 <                        long nc = ((long)(w.nextWait & E_MASK) |
2023 <                                   (c & (AC_MASK|TC_MASK)));
2024 <                        if (w.eventCount == (e | INT_SIGN) &&
2025 <                            U.compareAndSwapLong(this, CTL, c, nc)) {
2026 <                            w.eventCount = (e + E_SEQ) & E_MASK;
2027 <                            if ((p = w.parker) != null)
2028 <                                U.unpark(p);
2029 <                            return true;
2030 <                        }
2031 <                    }
2032 <                }
2033 <                else if (tc < MAX_CAP) { // create replacement
2034 <                    long nc = ((c + TC_UNIT) & TC_MASK) | (c & ~TC_MASK);
2035 <                    if (U.compareAndSwapLong(this, CTL, c, nc)) {
2036 <                        addWorker();
2037 <                        return true;
2038 <                    }
1930 >            else if ((tc = (short)(c >>> TC_SHIFT)) >= 0 &&
1931 >                     (int)(c >> AC_SHIFT) + pc > 1) {
1932 >                long nc = ((c - AC_UNIT) & AC_MASK) | (c & ~AC_MASK);
1933 >                if (U.compareAndSwapLong(this, CTL, c, nc))
1934 >                    return true;   // no compensation
1935 >            }
1936 >            else if (tc + pc < MAX_CAP) {
1937 >                long nc = ((c + TC_UNIT) & TC_MASK) | (c & ~TC_MASK);
1938 >                if (U.compareAndSwapLong(this, CTL, c, nc)) {
1939 >                    addWorker();
1940 >                    return true;
1941                  }
1942              }
1943          }
# Line 2050 | Line 1952 | public class ForkJoinPool extends Abstra
1952       * @return task status on exit
1953       */
1954      final int awaitJoin(WorkQueue joiner, ForkJoinTask<?> task) {
1955 <        int s;
1956 <        if ((s = task.status) >= 0) {
1955 >        int s = 0;
1956 >        if (joiner != null && task != null && (s = task.status) >= 0) {
1957              ForkJoinTask<?> prevJoin = joiner.currentJoin;
1958              joiner.currentJoin = task;
1959 <            long startTime = 0L;
1960 <            for (int k = 0;;) {
1961 <                if ((s = (joiner.isEmpty() ?           // try to help
1962 <                          tryHelpStealer(joiner, task) :
1963 <                          joiner.tryRemoveAndExec(task))) == 0 &&
1959 >            do {} while ((s = task.status) >= 0 &&
1960 >                         joiner.queueSize() > 0 &&
1961 >                         joiner.tryRemoveAndExec(task)); // process local tasks
1962 >            if (s >= 0 && (s = task.status) >= 0 &&
1963 >                (s = helpSignal(task, joiner.poolIndex)) >= 0 &&
1964 >                (task instanceof CountedCompleter))
1965 >                s = helpComplete(task, LIFO_QUEUE);
1966 >            int k = 0; // to perform pre-block yield for politeness
1967 >            while (s >= 0 && (s = task.status) >= 0) {
1968 >                if ((joiner.queueSize() > 0 ||           // try helping
1969 >                     (s = tryHelpStealer(joiner, task)) == 0) &&
1970                      (s = task.status) >= 0) {
1971 <                    if (k == 0) {
1972 <                        startTime = System.nanoTime();
1973 <                        tryPollForAndExec(joiner, task); // check uncommon case
1974 <                    }
1975 <                    else if ((k & (MAX_HELP - 1)) == 0 &&
1976 <                             System.nanoTime() - startTime >=
1977 <                             COMPENSATION_DELAY &&
1978 <                             tryCompensate(task, null)) {
1979 <                        if (task.trySetSignal()) {
1971 >                    if (k < 3) {
1972 >                        if (++k < 3)
1973 >                            s = helpSignal(task, joiner.poolIndex);
1974 >                        else
1975 >                            Thread.yield();
1976 >                    }
1977 >                    else if (!tryCompensate())
1978 >                        k = 0;
1979 >                    else {
1980 >                        if (task.trySetSignal() && (s = task.status) >= 0) {
1981                              synchronized (task) {
1982                                  if (task.status >= 0) {
1983                                      try {                // see ForkJoinTask
# Line 2085 | Line 1994 | public class ForkJoinPool extends Abstra
1994                                       (this, CTL, c = ctl, c + AC_UNIT));
1995                      }
1996                  }
2088                if (s < 0 || (s = task.status) < 0) {
2089                    joiner.currentJoin = prevJoin;
2090                    break;
2091                }
2092                else if ((k++ & (MAX_HELP - 1)) == MAX_HELP >>> 1)
2093                    Thread.yield();                     // for politeness
1997              }
1998 +            joiner.currentJoin = prevJoin;
1999          }
2000          return s;
2001      }
# Line 2103 | Line 2007 | public class ForkJoinPool extends Abstra
2007       *
2008       * @param joiner the joining worker
2009       * @param task the task
2106     * @return task status on exit
2010       */
2011 <    final int helpJoinOnce(WorkQueue joiner, ForkJoinTask<?> task) {
2011 >    final void helpJoinOnce(WorkQueue joiner, ForkJoinTask<?> task) {
2012          int s;
2013 <        while ((s = task.status) >= 0 &&
2014 <               (joiner.isEmpty() ?
2015 <                tryHelpStealer(joiner, task) :
2016 <                joiner.tryRemoveAndExec(task)) != 0)
2017 <            ;
2018 <        return s;
2013 >        if (joiner != null && task != null && (s = task.status) >= 0) {
2014 >            ForkJoinTask<?> prevJoin = joiner.currentJoin;
2015 >            joiner.currentJoin = task;
2016 >            do {} while ((s = task.status) >= 0 &&
2017 >                         joiner.queueSize() > 0 &&
2018 >                         joiner.tryRemoveAndExec(task));
2019 >            if (s >= 0 && (s = task.status) >= 0 &&
2020 >                (s = helpSignal(task, joiner.poolIndex)) >= 0 &&
2021 >                (task instanceof CountedCompleter))
2022 >                s = helpComplete(task, LIFO_QUEUE);
2023 >            if (s >= 0 && joiner.queueSize() == 0) {
2024 >                do {} while (task.status >= 0 &&
2025 >                             tryHelpStealer(joiner, task) > 0);
2026 >            }
2027 >            joiner.currentJoin = prevJoin;
2028 >        }
2029      }
2030  
2031      /**
# Line 2120 | Line 2033 | public class ForkJoinPool extends Abstra
2033       * during a random, then cyclic scan, else null.  This method must
2034       * be retried by caller if, by the time it tries to use the queue,
2035       * it is empty.
2036 +     * @param r a (random) seed for scanning
2037       */
2038 <    private WorkQueue findNonEmptyStealQueue(WorkQueue w) {
2125 <        // Similar to loop in scan(), but ignoring submissions
2126 <        int r = w.seed; r ^= r << 13; r ^= r >>> 17; w.seed = r ^= r << 5;
2127 <        int step = (r >>> 16) | 1;
2038 >    private WorkQueue findNonEmptyStealQueue(int r) {
2039          for (WorkQueue[] ws;;) {
2040 <            int rs = runState, m;
2040 >            int ps = plock, m, n;
2041              if ((ws = workQueues) == null || (m = ws.length - 1) < 1)
2042                  return null;
2043 <            for (int j = (m + 1) << 2; ; r += step) {
2044 <                WorkQueue q = ws[((r << 1) | 1) & m];
2045 <                if (q != null && !q.isEmpty())
2043 >            for (int j = (m + 1) << 2; ;) {
2044 >                WorkQueue q = ws[(((r + j) << 1) | 1) & m];
2045 >                if (q != null && (n = q.queueSize()) > 0) {
2046 >                    if (n > 1)
2047 >                        signalWork(q, 0);
2048                      return q;
2049 +                }
2050                  else if (--j < 0) {
2051 <                    if (runState == rs)
2051 >                    if (plock == ps)
2052                          return null;
2053                      break;
2054                  }
# Line 2153 | Line 2067 | public class ForkJoinPool extends Abstra
2067              ForkJoinTask<?> localTask; // exhaust local queue
2068              while ((localTask = w.nextLocalTask()) != null)
2069                  localTask.doExec();
2070 <            WorkQueue q = findNonEmptyStealQueue(w);
2070 >            // Similar to loop in scan(), but ignoring submissions
2071 >            WorkQueue q = findNonEmptyStealQueue(w.nextSeed());
2072              if (q != null) {
2073                  ForkJoinTask<?> t; int b;
2074                  if (!active) {      // re-establish active count
# Line 2174 | Line 2089 | public class ForkJoinPool extends Abstra
2089                  }
2090                  else
2091                      c = ctl;        // re-increment on exit
2092 <                if ((int)(c >> AC_SHIFT) + parallelism == 0) {
2092 >                if ((int)(c >> AC_SHIFT) + (config & SMASK) == 0) {
2093                      do {} while (!U.compareAndSwapLong
2094                                   (this, CTL, c = ctl, c + AC_UNIT));
2095                      break;
# Line 2184 | Line 2099 | public class ForkJoinPool extends Abstra
2099      }
2100  
2101      /**
2187     * Restricted version of helpQuiescePool for non-FJ callers
2188     */
2189    static void externalHelpQuiescePool() {
2190        ForkJoinPool p; WorkQueue[] ws; WorkQueue q, sq;
2191        ForkJoinTask<?>[] a; int b;
2192        ForkJoinTask<?> t = null;
2193        int k = submitters.get().seed & SQMASK;
2194        if ((p = commonPool) != null &&
2195            (int)(p.ctl >> AC_SHIFT) < 0 &&
2196            (ws = p.workQueues) != null &&
2197            ws.length > (k &= p.submitMask) &&
2198            (q = ws[k]) != null) {
2199            while (q.top - q.base > 0) {
2200                if ((t = q.sharedPop()) != null)
2201                    break;
2202            }
2203            if (t == null && (sq = p.findNonEmptyStealQueue(q)) != null &&
2204                (b = sq.base) - sq.top < 0)
2205                t = sq.pollAt(b);
2206            if (t != null)
2207                t.doExec();
2208        }
2209    }
2210
2211    /**
2102       * Gets and removes a local or stolen task for the given worker.
2103       *
2104       * @return a task, if available
# Line 2218 | Line 2108 | public class ForkJoinPool extends Abstra
2108              WorkQueue q; int b;
2109              if ((t = w.nextLocalTask()) != null)
2110                  return t;
2111 <            if ((q = findNonEmptyStealQueue(w)) == null)
2111 >            if ((q = findNonEmptyStealQueue(w.nextSeed())) == null)
2112                  return null;
2113              if ((b = q.base) - q.top < 0 && (t = q.pollAt(b)) != null)
2114                  return t;
# Line 2226 | Line 2116 | public class ForkJoinPool extends Abstra
2116      }
2117  
2118      /**
2119 <     * Returns the approximate (non-atomic) number of idle threads per
2120 <     * active thread to offset steal queue size for method
2121 <     * ForkJoinTask.getSurplusQueuedTaskCount().
2122 <     */
2123 <    final int idlePerActive() {
2124 <        // Approximate at powers of two for small values, saturate past 4
2125 <        int p = parallelism;
2126 <        int a = p + (int)(ctl >> AC_SHIFT);
2127 <        return (a > (p >>>= 1) ? 0 :
2128 <                a > (p >>>= 1) ? 1 :
2129 <                a > (p >>>= 1) ? 2 :
2130 <                a > (p >>>= 1) ? 4 :
2131 <                8);
2132 <    }
2133 <
2134 <    /**
2135 <     * Returns approximate submission queue length for the given caller
2136 <     */
2137 <    static int getEstimatedSubmitterQueueLength() {
2138 <        ForkJoinPool p; WorkQueue[] ws; WorkQueue q;
2139 <        int k = submitters.get().seed & SQMASK;
2140 <        return ((p = commonPool) != null &&
2141 <                p.runState >= 0 &&
2142 <                (ws = p.workQueues) != null &&
2143 <                ws.length > (k &= p.submitMask) &&
2144 <                (q = ws[k]) != null) ?
2145 <            q.queueSize() : 0;
2119 >     * Returns a cheap heuristic guide for task partitioning when
2120 >     * programmers, frameworks, tools, or languages have little or no
2121 >     * idea about task granularity.  In essence by offering this
2122 >     * method, we ask users only about tradeoffs in overhead vs
2123 >     * expected throughput and its variance, rather than how finely to
2124 >     * partition tasks.
2125 >     *
2126 >     * In a steady state strict (tree-structured) computation, each
2127 >     * thread makes available for stealing enough tasks for other
2128 >     * threads to remain active. Inductively, if all threads play by
2129 >     * the same rules, each thread should make available only a
2130 >     * constant number of tasks.
2131 >     *
2132 >     * The minimum useful constant is just 1. But using a value of 1
2133 >     * would require immediate replenishment upon each steal to
2134 >     * maintain enough tasks, which is infeasible.  Further,
2135 >     * partitionings/granularities of offered tasks should minimize
2136 >     * steal rates, which in general means that threads nearer the top
2137 >     * of computation tree should generate more than those nearer the
2138 >     * bottom. In perfect steady state, each thread is at
2139 >     * approximately the same level of computation tree. However,
2140 >     * producing extra tasks amortizes the uncertainty of progress and
2141 >     * diffusion assumptions.
2142 >     *
2143 >     * So, users will want to use values larger, but not much larger
2144 >     * than 1 to both smooth over transient shortages and hedge
2145 >     * against uneven progress; as traded off against the cost of
2146 >     * extra task overhead. We leave the user to pick a threshold
2147 >     * value to compare with the results of this call to guide
2148 >     * decisions, but recommend values such as 3.
2149 >     *
2150 >     * When all threads are active, it is on average OK to estimate
2151 >     * surplus strictly locally. In steady-state, if one thread is
2152 >     * maintaining say 2 surplus tasks, then so are others. So we can
2153 >     * just use estimated queue length.  However, this strategy alone
2154 >     * leads to serious mis-estimates in some non-steady-state
2155 >     * conditions (ramp-up, ramp-down, other stalls). We can detect
2156 >     * many of these by further considering the number of "idle"
2157 >     * threads, that are known to have zero queued tasks, so
2158 >     * compensate by a factor of (#idle/#active) threads.
2159 >     *
2160 >     * Note: The approximation of #busy workers as #active workers is
2161 >     * not very good under current signalling scheme, and should be
2162 >     * improved.
2163 >     */
2164 >    static int getSurplusQueuedTaskCount() {
2165 >        Thread t; ForkJoinWorkerThread wt; ForkJoinPool pool; WorkQueue q;
2166 >        if (((t = Thread.currentThread()) instanceof ForkJoinWorkerThread)) {
2167 >            int p = (pool = (wt = (ForkJoinWorkerThread)t).pool).config & SMASK;
2168 >            int n = (q = wt.workQueue).top - q.base;
2169 >            int a = (int)(pool.ctl >> AC_SHIFT) + p;
2170 >            return n - (a > (p >>>= 1) ? 0 :
2171 >                        a > (p >>>= 1) ? 1 :
2172 >                        a > (p >>>= 1) ? 2 :
2173 >                        a > (p >>>= 1) ? 4 :
2174 >                        8);
2175 >        }
2176 >        return 0;
2177      }
2178  
2179      //  Termination
# Line 2272 | Line 2193 | public class ForkJoinPool extends Abstra
2193       * @return true if now terminating or terminated
2194       */
2195      private boolean tryTerminate(boolean now, boolean enable) {
2196 +        if (this == commonPool)                     // cannot shut down
2197 +            return false;
2198          for (long c;;) {
2199              if (((c = ctl) & STOP_BIT) != 0) {      // already terminating
2200 <                if ((short)(c >>> TC_SHIFT) == -parallelism) {
2201 <                    synchronized(this) {
2200 >                if ((short)(c >>> TC_SHIFT) == -(config & SMASK)) {
2201 >                    synchronized (this) {
2202                          notifyAll();                // signal when 0 workers
2203                      }
2204                  }
2205                  return true;
2206              }
2207 <            if (runState >= 0) {                    // not yet enabled
2207 >            if (plock >= 0) {                       // not yet enabled
2208 >                int ps;
2209                  if (!enable)
2210                      return false;
2211 <                while (!U.compareAndSwapInt(this, MAINLOCK, 0, 1))
2212 <                    tryAwaitMainLock();
2213 <                try {
2214 <                    runState |= SHUTDOWN;
2215 <                } finally {
2216 <                    if (!U.compareAndSwapInt(this, MAINLOCK, 1, 0)) {
2293 <                        mainLock = 0;
2294 <                        synchronized (this) { notifyAll(); };
2295 <                    }
2296 <                }
2211 >                if (((ps = plock) & PL_LOCK) != 0 ||
2212 >                    !U.compareAndSwapInt(this, PLOCK, ps, ps += PL_LOCK))
2213 >                    ps = acquirePlock();
2214 >                int nps = SHUTDOWN;
2215 >                if (!U.compareAndSwapInt(this, PLOCK, ps, nps))
2216 >                    releasePlock(nps);
2217              }
2218              if (!now) {                             // check if idle & no tasks
2219 <                if ((int)(c >> AC_SHIFT) != -parallelism ||
2219 >                if ((int)(c >> AC_SHIFT) != -(config & SMASK) ||
2220                      hasQueuedSubmissions())
2221                      return false;
2222                  // Check for unqueued inactive workers. One pass suffices.
# Line 2316 | Line 2236 | public class ForkJoinPool extends Abstra
2236                          int n = ws.length;
2237                          for (int i = 0; i < n; ++i) {
2238                              if ((w = ws[i]) != null) {
2239 <                                w.runState = -1;
2239 >                                w.qlock = -1;
2240                                  if (pass > 0) {
2241                                      w.cancelAll();
2242                                      if (pass > 1)
# Line 2335 | Line 2255 | public class ForkJoinPool extends Abstra
2255                              if (w.eventCount == (e | INT_SIGN) &&
2256                                  U.compareAndSwapLong(this, CTL, cc, nc)) {
2257                                  w.eventCount = (e + E_SEQ) & E_MASK;
2258 <                                w.runState = -1;
2258 >                                w.qlock = -1;
2259                                  if ((p = w.parker) != null)
2260                                      U.unpark(p);
2261                              }
# Line 2346 | Line 2266 | public class ForkJoinPool extends Abstra
2266          }
2267      }
2268  
2269 +    // external operations on common pool
2270 +
2271 +    /**
2272 +     * Returns common pool queue for a thread that has submitted at
2273 +     * least one task.
2274 +     */
2275 +    static WorkQueue commonSubmitterQueue() {
2276 +        ForkJoinPool p; WorkQueue[] ws; int m; Submitter z;
2277 +        return ((z = submitters.get()) != null &&
2278 +                (p = commonPool) != null &&
2279 +                (ws = p.workQueues) != null &&
2280 +                (m = ws.length - 1) >= 0) ?
2281 +            ws[m & z.seed & SQMASK] : null;
2282 +    }
2283 +
2284 +    /**
2285 +     * Tries to pop the given task from submitter's queue in common pool.
2286 +     */
2287 +    static boolean tryExternalUnpush(ForkJoinTask<?> t) {
2288 +        ForkJoinPool p; WorkQueue[] ws; WorkQueue q; Submitter z;
2289 +        ForkJoinTask<?>[] a;  int m, s; long j;
2290 +        if ((z = submitters.get()) != null &&
2291 +            (p = commonPool) != null &&
2292 +            (ws = p.workQueues) != null &&
2293 +            (m = ws.length - 1) >= 0 &&
2294 +            (q = ws[m & z.seed & SQMASK]) != null &&
2295 +            (s = q.top) != q.base &&
2296 +            (a = q.array) != null &&
2297 +            U.getObjectVolatile
2298 +            (a, j = (((a.length - 1) & (s - 1)) << ASHIFT) + ABASE) == t &&
2299 +            U.compareAndSwapInt(q, QLOCK, 0, 1)) {
2300 +            if (q.array == a && q.top == s && // recheck
2301 +                U.compareAndSwapObject(a, j, t, null)) {
2302 +                q.top = s - 1;
2303 +                q.qlock = 0;
2304 +                return true;
2305 +            }
2306 +            q.qlock = 0;
2307 +        }
2308 +        return false;
2309 +    }
2310 +
2311 +    /**
2312 +     * Tries to pop and run local tasks within the same computation
2313 +     * as the given root. On failure, tries to help complete from
2314 +     * other queues via helpComplete.
2315 +     */
2316 +    private void externalHelpComplete(WorkQueue q, ForkJoinTask<?> root) {
2317 +        ForkJoinTask<?>[] a; int m;
2318 +        if (q != null && (a = q.array) != null && (m = (a.length - 1)) >= 0 &&
2319 +            root != null && root.status >= 0) {
2320 +            for (;;) {
2321 +                int s, u; Object o; CountedCompleter<?> task = null;
2322 +                if ((s = q.top) - q.base > 0) {
2323 +                    long j = ((m & (s - 1)) << ASHIFT) + ABASE;
2324 +                    if ((o = U.getObject(a, j)) != null &&
2325 +                        (o instanceof CountedCompleter)) {
2326 +                        CountedCompleter<?> t = (CountedCompleter<?>)o, r = t;
2327 +                        do {
2328 +                            if (r == root) {
2329 +                                if (U.compareAndSwapInt(q, QLOCK, 0, 1)) {
2330 +                                    if (q.array == a && q.top == s &&
2331 +                                        U.compareAndSwapObject(a, j, t, null)) {
2332 +                                        q.top = s - 1;
2333 +                                        task = t;
2334 +                                    }
2335 +                                    q.qlock = 0;
2336 +                                }
2337 +                                break;
2338 +                            }
2339 +                        } while ((r = r.completer) != null);
2340 +                    }
2341 +                }
2342 +                if (task != null)
2343 +                    task.doExec();
2344 +                if (root.status < 0 ||
2345 +                    (u = (int)(ctl >>> 32)) >= 0 || (u >> UAC_SHIFT) >= 0)
2346 +                    break;
2347 +                if (task == null) {
2348 +                    if (helpSignal(root, q.poolIndex) >= 0)
2349 +                        helpComplete(root, SHARED_QUEUE);
2350 +                    break;
2351 +                }
2352 +            }
2353 +        }
2354 +    }
2355 +
2356 +    /**
2357 +     * Tries to help execute or signal availability of the given task
2358 +     * from submitter's queue in common pool.
2359 +     */
2360 +    static void externalHelpJoin(ForkJoinTask<?> t) {
2361 +        // Some hard-to-avoid overlap with tryExternalUnpush
2362 +        ForkJoinPool p; WorkQueue[] ws; WorkQueue q, w; Submitter z;
2363 +        ForkJoinTask<?>[] a;  int m, s, n; long j;
2364 +        if (t != null &&
2365 +            (z = submitters.get()) != null &&
2366 +            (p = commonPool) != null &&
2367 +            (ws = p.workQueues) != null &&
2368 +            (m = ws.length - 1) >= 0 &&
2369 +            (q = ws[m & z.seed & SQMASK]) != null &&
2370 +            (a = q.array) != null &&
2371 +            t.status >= 0) {
2372 +            if ((s = q.top) != q.base &&
2373 +                U.getObjectVolatile
2374 +                (a, j = (((a.length - 1) & (s - 1)) << ASHIFT) + ABASE) == t &&
2375 +                U.compareAndSwapInt(q, QLOCK, 0, 1)) {
2376 +                if (q.array == a && q.top == s &&
2377 +                    U.compareAndSwapObject(a, j, t, null)) {
2378 +                    q.top = s - 1;
2379 +                    q.qlock = 0;
2380 +                    t.doExec();
2381 +                }
2382 +                else
2383 +                    q.qlock = 0;
2384 +            }
2385 +            if (t.status >= 0) {
2386 +                if (t instanceof CountedCompleter)
2387 +                    p.externalHelpComplete(q, t);
2388 +                else
2389 +                    p.helpSignal(t, q.poolIndex);
2390 +            }
2391 +        }
2392 +    }
2393 +
2394 +    /**
2395 +     * Restricted version of helpQuiescePool for external callers
2396 +     */
2397 +    static void externalHelpQuiescePool() {
2398 +        ForkJoinPool p; ForkJoinTask<?> t; WorkQueue q; int b;
2399 +        if ((p = commonPool) != null &&
2400 +            (q = p.findNonEmptyStealQueue(1)) != null &&
2401 +            (b = q.base) - q.top < 0 &&
2402 +            (t = q.pollAt(b)) != null)
2403 +            t.doExec();
2404 +    }
2405 +
2406      // Exported methods
2407  
2408      // Constructors
# Line 2417 | Line 2474 | public class ForkJoinPool extends Abstra
2474              throw new NullPointerException();
2475          if (parallelism <= 0 || parallelism > MAX_CAP)
2476              throw new IllegalArgumentException();
2420        this.parallelism = parallelism;
2477          this.factory = factory;
2478          this.ueh = handler;
2479 <        this.localMode = asyncMode ? FIFO_QUEUE : LIFO_QUEUE;
2479 >        this.config = parallelism | (asyncMode ? (FIFO_QUEUE << 16) : 0);
2480          long np = (long)(-parallelism); // offset ctl counts
2481          this.ctl = ((np << AC_SHIFT) & AC_MASK) | ((np << TC_SHIFT) & TC_MASK);
2482 <        // Use nearest power 2 for workQueues size. See Hackers Delight sec 3.2.
2427 <        int n = parallelism - 1;
2428 <        n |= n >>> 1; n |= n >>> 2; n |= n >>> 4; n |= n >>> 8; n |= n >>> 16;
2429 <        this.submitMask = ((n + 1) << 1) - 1;
2430 <        int pn = poolNumberGenerator.incrementAndGet();
2482 >        int pn = nextPoolId();
2483          StringBuilder sb = new StringBuilder("ForkJoinPool-");
2484          sb.append(Integer.toString(pn));
2485          sb.append("-worker-");
2486          this.workerNamePrefix = sb.toString();
2435        this.runState = 1;              // set init flag
2487      }
2488  
2489      /**
2490       * Constructor for common pool, suitable only for static initialization.
2491       * Basically the same as above, but uses smallest possible initial footprint.
2492       */
2493 <    ForkJoinPool(int parallelism, int submitMask,
2493 >    ForkJoinPool(int parallelism, long ctl,
2494                   ForkJoinWorkerThreadFactory factory,
2495                   Thread.UncaughtExceptionHandler handler) {
2496 +        this.config = parallelism;
2497 +        this.ctl = ctl;
2498          this.factory = factory;
2499          this.ueh = handler;
2447        this.submitMask = submitMask;
2448        this.parallelism = parallelism;
2449        long np = (long)(-parallelism);
2450        this.ctl = ((np << AC_SHIFT) & AC_MASK) | ((np << TC_SHIFT) & TC_MASK);
2451        this.localMode = LIFO_QUEUE;
2500          this.workerNamePrefix = "ForkJoinPool.commonPool-worker-";
2453        this.runState = 1;
2501      }
2502  
2503      /**
# Line 2459 | Line 2506 | public class ForkJoinPool extends Abstra
2506       * @return the common pool instance
2507       */
2508      public static ForkJoinPool commonPool() {
2509 <        ForkJoinPool p;
2510 <        if ((p = commonPool) == null)
2464 <            throw new Error("Common Pool Unavailable");
2465 <        return p;
2509 >        // assert commonPool != null : "static init error";
2510 >        return commonPool;
2511      }
2512  
2513      // Execution methods
# Line 2486 | Line 2531 | public class ForkJoinPool extends Abstra
2531      public <T> T invoke(ForkJoinTask<T> task) {
2532          if (task == null)
2533              throw new NullPointerException();
2534 <        doSubmit(task);
2534 >        externalPush(task);
2535          return task.join();
2536      }
2537  
# Line 2501 | Line 2546 | public class ForkJoinPool extends Abstra
2546      public void execute(ForkJoinTask<?> task) {
2547          if (task == null)
2548              throw new NullPointerException();
2549 <        doSubmit(task);
2549 >        externalPush(task);
2550      }
2551  
2552      // AbstractExecutorService methods
# Line 2519 | Line 2564 | public class ForkJoinPool extends Abstra
2564              job = (ForkJoinTask<?>) task;
2565          else
2566              job = new ForkJoinTask.AdaptedRunnableAction(task);
2567 <        doSubmit(job);
2567 >        externalPush(job);
2568      }
2569  
2570      /**
# Line 2534 | Line 2579 | public class ForkJoinPool extends Abstra
2579      public <T> ForkJoinTask<T> submit(ForkJoinTask<T> task) {
2580          if (task == null)
2581              throw new NullPointerException();
2582 <        doSubmit(task);
2582 >        externalPush(task);
2583          return task;
2584      }
2585  
# Line 2545 | Line 2590 | public class ForkJoinPool extends Abstra
2590       */
2591      public <T> ForkJoinTask<T> submit(Callable<T> task) {
2592          ForkJoinTask<T> job = new ForkJoinTask.AdaptedCallable<T>(task);
2593 <        doSubmit(job);
2593 >        externalPush(job);
2594          return job;
2595      }
2596  
# Line 2556 | Line 2601 | public class ForkJoinPool extends Abstra
2601       */
2602      public <T> ForkJoinTask<T> submit(Runnable task, T result) {
2603          ForkJoinTask<T> job = new ForkJoinTask.AdaptedRunnable<T>(task, result);
2604 <        doSubmit(job);
2604 >        externalPush(job);
2605          return job;
2606      }
2607  
# Line 2573 | Line 2618 | public class ForkJoinPool extends Abstra
2618              job = (ForkJoinTask<?>) task;
2619          else
2620              job = new ForkJoinTask.AdaptedRunnableAction(task);
2621 <        doSubmit(job);
2621 >        externalPush(job);
2622          return job;
2623      }
2624  
# Line 2595 | Line 2640 | public class ForkJoinPool extends Abstra
2640          try {
2641              for (Callable<T> t : tasks) {
2642                  ForkJoinTask<T> f = new ForkJoinTask.AdaptedCallable<T>(t);
2643 <                doSubmit(f);
2643 >                externalPush(f);
2644                  fs.add(f);
2645              }
2646              for (ForkJoinTask<T> f : fs)
# Line 2634 | Line 2679 | public class ForkJoinPool extends Abstra
2679       * @return the targeted parallelism level of this pool
2680       */
2681      public int getParallelism() {
2682 <        return parallelism;
2682 >        return config & SMASK;
2683      }
2684  
2685      /**
# Line 2655 | Line 2700 | public class ForkJoinPool extends Abstra
2700       * @return the number of worker threads
2701       */
2702      public int getPoolSize() {
2703 <        return parallelism + (short)(ctl >>> TC_SHIFT);
2703 >        return (config & SMASK) + (short)(ctl >>> TC_SHIFT);
2704      }
2705  
2706      /**
# Line 2665 | Line 2710 | public class ForkJoinPool extends Abstra
2710       * @return {@code true} if this pool uses async mode
2711       */
2712      public boolean getAsyncMode() {
2713 <        return localMode != 0;
2713 >        return (config >>> 16) == FIFO_QUEUE;
2714      }
2715  
2716      /**
# Line 2696 | Line 2741 | public class ForkJoinPool extends Abstra
2741       * @return the number of active threads
2742       */
2743      public int getActiveThreadCount() {
2744 <        int r = parallelism + (int)(ctl >> AC_SHIFT);
2744 >        int r = (config & SMASK) + (int)(ctl >> AC_SHIFT);
2745          return (r <= 0) ? 0 : r; // suppress momentarily negative values
2746      }
2747  
# Line 2712 | Line 2757 | public class ForkJoinPool extends Abstra
2757       * @return {@code true} if all threads are currently idle
2758       */
2759      public boolean isQuiescent() {
2760 <        return (int)(ctl >> AC_SHIFT) + parallelism == 0;
2760 >        return (int)(ctl >> AC_SHIFT) + (config & SMASK) == 0;
2761      }
2762  
2763      /**
# Line 2732 | Line 2777 | public class ForkJoinPool extends Abstra
2777          if ((ws = workQueues) != null) {
2778              for (int i = 1; i < ws.length; i += 2) {
2779                  if ((w = ws[i]) != null)
2780 <                    count += w.totalSteals;
2780 >                    count += w.nsteals;
2781              }
2782          }
2783          return count;
# Line 2789 | Line 2834 | public class ForkJoinPool extends Abstra
2834          WorkQueue[] ws; WorkQueue w;
2835          if ((ws = workQueues) != null) {
2836              for (int i = 0; i < ws.length; i += 2) {
2837 <                if ((w = ws[i]) != null && !w.isEmpty())
2837 >                if ((w = ws[i]) != null && w.queueSize() != 0)
2838                      return true;
2839              }
2840          }
# Line 2868 | Line 2913 | public class ForkJoinPool extends Abstra
2913                          qs += size;
2914                      else {
2915                          qt += size;
2916 <                        st += w.totalSteals;
2916 >                        st += w.nsteals;
2917                          if (w.isApparentlyUnblocked())
2918                              ++rc;
2919                      }
2920                  }
2921              }
2922          }
2923 <        int pc = parallelism;
2923 >        int pc = (config & SMASK);
2924          int tc = pc + (short)(c >>> TC_SHIFT);
2925          int ac = pc + (int)(c >> AC_SHIFT);
2926          if (ac < 0) // ignore transient negative
# Line 2884 | Line 2929 | public class ForkJoinPool extends Abstra
2929          if ((c & STOP_BIT) != 0)
2930              level = (tc == 0) ? "Terminated" : "Terminating";
2931          else
2932 <            level = runState < 0 ? "Shutting down" : "Running";
2932 >            level = plock < 0 ? "Shutting down" : "Running";
2933          return super.toString() +
2934              "[" + level +
2935              ", parallelism = " + pc +
# Line 2913 | Line 2958 | public class ForkJoinPool extends Abstra
2958       */
2959      public void shutdown() {
2960          checkPermission();
2961 <        if (this != commonPool)
2917 <            tryTerminate(false, true);
2961 >        tryTerminate(false, true);
2962      }
2963  
2964      /**
# Line 2937 | Line 2981 | public class ForkJoinPool extends Abstra
2981       */
2982      public List<Runnable> shutdownNow() {
2983          checkPermission();
2984 <        if (this != commonPool)
2941 <            tryTerminate(true, true);
2984 >        tryTerminate(true, true);
2985          return Collections.emptyList();
2986      }
2987  
# Line 2950 | Line 2993 | public class ForkJoinPool extends Abstra
2993      public boolean isTerminated() {
2994          long c = ctl;
2995          return ((c & STOP_BIT) != 0L &&
2996 <                (short)(c >>> TC_SHIFT) == -parallelism);
2996 >                (short)(c >>> TC_SHIFT) == -(config & SMASK));
2997      }
2998  
2999      /**
# Line 2969 | Line 3012 | public class ForkJoinPool extends Abstra
3012      public boolean isTerminating() {
3013          long c = ctl;
3014          return ((c & STOP_BIT) != 0L &&
3015 <                (short)(c >>> TC_SHIFT) != -parallelism);
3015 >                (short)(c >>> TC_SHIFT) != -(config & SMASK));
3016      }
3017  
3018      /**
# Line 2978 | Line 3021 | public class ForkJoinPool extends Abstra
3021       * @return {@code true} if this pool has been shut down
3022       */
3023      public boolean isShutdown() {
3024 <        return runState < 0;
3024 >        return plock < 0;
3025      }
3026  
3027      /**
3028 <     * Blocks until all tasks have completed execution after a shutdown
3029 <     * request, or the timeout occurs, or the current thread is
3030 <     * interrupted, whichever happens first.
3028 >     * Blocks until all tasks have completed execution after a
3029 >     * shutdown request, or the timeout occurs, or the current thread
3030 >     * is interrupted, whichever happens first. Note that the {@link
3031 >     * #commonPool()} never terminates until program shutdown so
3032 >     * this method will always time out.
3033       *
3034       * @param timeout the maximum time to wait
3035       * @param unit the time unit of the timeout argument
# Line 2999 | Line 3044 | public class ForkJoinPool extends Abstra
3044              return true;
3045          long startTime = System.nanoTime();
3046          boolean terminated = false;
3047 <        synchronized(this) {
3047 >        synchronized (this) {
3048              for (long waitTime = nanos, millis = 0L;;) {
3049                  if (terminated = isTerminated() ||
3050                      waitTime <= 0L ||
# Line 3108 | Line 3153 | public class ForkJoinPool extends Abstra
3153      public static void managedBlock(ManagedBlocker blocker)
3154          throws InterruptedException {
3155          Thread t = Thread.currentThread();
3156 <        ForkJoinPool p = ((t instanceof ForkJoinWorkerThread) ?
3157 <                          ((ForkJoinWorkerThread)t).pool : null);
3158 <        while (!blocker.isReleasable()) {
3159 <            if (p == null || p.tryCompensate(null, blocker)) {
3160 <                try {
3161 <                    do {} while (!blocker.isReleasable() && !blocker.block());
3162 <                } finally {
3163 <                    if (p != null)
3156 >        if (t instanceof ForkJoinWorkerThread) {
3157 >            ForkJoinPool p = ((ForkJoinWorkerThread)t).pool;
3158 >            while (!blocker.isReleasable()) { // variant of helpSignal
3159 >                WorkQueue[] ws; WorkQueue q; int m, n, u;
3160 >                if ((ws = p.workQueues) != null && (m = ws.length - 1) >= 0) {
3161 >                    for (int i = 0; i <= m; ++i) {
3162 >                        if (blocker.isReleasable())
3163 >                            return;
3164 >                        if ((q = ws[i]) != null && (n = q.queueSize()) > 0) {
3165 >                            p.signalWork(q, n);
3166 >                            if ((u = (int)(p.ctl >>> 32)) >= 0 ||
3167 >                                (u >> UAC_SHIFT) >= 0)
3168 >                                break;
3169 >                        }
3170 >                    }
3171 >                }
3172 >                if (p.tryCompensate()) {
3173 >                    try {
3174 >                        do {} while (!blocker.isReleasable() &&
3175 >                                     !blocker.block());
3176 >                    } finally {
3177                          p.incrementActiveCount();
3178 +                    }
3179 +                    break;
3180                  }
3121                break;
3181              }
3182          }
3183 +        else {
3184 +            do {} while (!blocker.isReleasable() &&
3185 +                         !blocker.block());
3186 +        }
3187      }
3188  
3189      // AbstractExecutorService overrides.  These rely on undocumented
# Line 3141 | Line 3204 | public class ForkJoinPool extends Abstra
3204      private static final long PARKBLOCKER;
3205      private static final int ABASE;
3206      private static final int ASHIFT;
3144    private static final long NEXTWORKERNUMBER;
3207      private static final long STEALCOUNT;
3208 <    private static final long MAINLOCK;
3208 >    private static final long PLOCK;
3209 >    private static final long INDEXSEED;
3210 >    private static final long QLOCK;
3211  
3212      static {
3213 <        poolNumberGenerator = new AtomicInteger();
3150 <        nextSubmitterSeed = new AtomicInteger(0x55555555);
3151 <        modifyThreadPermission = new RuntimePermission("modifyThread");
3152 <        defaultForkJoinWorkerThreadFactory =
3153 <            new DefaultForkJoinWorkerThreadFactory();
3154 <        submitters = new ThreadSubmitter();
3155 <        int s;
3213 >        int s; // initialize field offsets for CAS etc
3214          try {
3215              U = getUnsafe();
3216              Class<?> k = ForkJoinPool.class;
3159            Class<?> ak = ForkJoinTask[].class;
3217              CTL = U.objectFieldOffset
3218                  (k.getDeclaredField("ctl"));
3162            NEXTWORKERNUMBER = U.objectFieldOffset
3163                (k.getDeclaredField("nextWorkerNumber"));
3219              STEALCOUNT = U.objectFieldOffset
3220                  (k.getDeclaredField("stealCount"));
3221 <            MAINLOCK = U.objectFieldOffset
3222 <                (k.getDeclaredField("mainLock"));
3221 >            PLOCK = U.objectFieldOffset
3222 >                (k.getDeclaredField("plock"));
3223 >            INDEXSEED = U.objectFieldOffset
3224 >                (k.getDeclaredField("indexSeed"));
3225              Class<?> tk = Thread.class;
3226              PARKBLOCKER = U.objectFieldOffset
3227                  (tk.getDeclaredField("parkBlocker"));
3228 +            Class<?> wk = WorkQueue.class;
3229 +            QLOCK = U.objectFieldOffset
3230 +                (wk.getDeclaredField("qlock"));
3231 +            Class<?> ak = ForkJoinTask[].class;
3232              ABASE = U.arrayBaseOffset(ak);
3233              s = U.arrayIndexScale(ak);
3234              ASHIFT = 31 - Integer.numberOfLeadingZeros(s);
# Line 3176 | Line 3237 | public class ForkJoinPool extends Abstra
3237          }
3238          if ((s & (s-1)) != 0)
3239              throw new Error("data type scale not a power of two");
3240 <        try { // Establish common pool
3241 <            String pp = System.getProperty(propPrefix + "parallelism");
3242 <            String fp = System.getProperty(propPrefix + "threadFactory");
3243 <            String up = System.getProperty(propPrefix + "exceptionHandler");
3244 <            ForkJoinWorkerThreadFactory fac = (fp == null) ?
3245 <                defaultForkJoinWorkerThreadFactory :
3246 <                ((ForkJoinWorkerThreadFactory)ClassLoader.
3247 <                 getSystemClassLoader().loadClass(fp).newInstance());
3248 <            Thread.UncaughtExceptionHandler ueh = (up == null)? null :
3249 <                ((Thread.UncaughtExceptionHandler)ClassLoader.
3250 <                 getSystemClassLoader().loadClass(up).newInstance());
3251 <            int par;
3252 <            if ((pp == null || (par = Integer.parseInt(pp)) <= 0))
3253 <                par = Runtime.getRuntime().availableProcessors();
3254 <            if (par > MAX_CAP)
3255 <                par = MAX_CAP;
3256 <            commonPoolParallelism = par;
3257 <            int n = par - 1; // precompute submit mask
3258 <            n |= n >>> 1; n |= n >>> 2; n |= n >>> 4;
3259 <            n |= n >>> 8; n |= n >>> 16;
3260 <            int mask = ((n + 1) << 1) - 1;
3261 <            commonPool = new ForkJoinPool(par, mask, fac, ueh);
3262 <        } catch (Exception e) {
3263 <            throw new Error(e);
3264 <        }
3240 >
3241 >        submitters = new ThreadLocal<Submitter>();
3242 >        ForkJoinWorkerThreadFactory fac = defaultForkJoinWorkerThreadFactory =
3243 >            new DefaultForkJoinWorkerThreadFactory();
3244 >        /*
3245 >         * Establish common pool parameters.  For extra caution,
3246 >         * computations to set up common pool state are here; the
3247 >         * constructor just assigns these values to fields.
3248 >         */
3249 >
3250 >        int par = 0;
3251 >        Thread.UncaughtExceptionHandler handler = null;
3252 >        try {  // TBD: limit or report ignored exceptions?
3253 >            String pp = System.getProperty
3254 >                ("java.util.concurrent.ForkJoinPool.common.parallelism");
3255 >            String hp = System.getProperty
3256 >                ("java.util.concurrent.ForkJoinPool.common.exceptionHandler");
3257 >            String fp = System.getProperty
3258 >                ("java.util.concurrent.ForkJoinPool.common.threadFactory");
3259 >            if (fp != null)
3260 >                fac = ((ForkJoinWorkerThreadFactory)ClassLoader.
3261 >                       getSystemClassLoader().loadClass(fp).newInstance());
3262 >            if (hp != null)
3263 >                handler = ((Thread.UncaughtExceptionHandler)ClassLoader.
3264 >                           getSystemClassLoader().loadClass(hp).newInstance());
3265 >            if (pp != null)
3266 >                par = Integer.parseInt(pp);
3267 >        } catch (Exception ignore) {
3268 >        }
3269 >
3270 >        if (par <= 0)
3271 >            par = Runtime.getRuntime().availableProcessors();
3272 >        if (par > MAX_CAP)
3273 >            par = MAX_CAP;
3274 >        commonPoolParallelism = par;
3275 >        long np = (long)(-par); // precompute initial ctl value
3276 >        long ct = ((np << AC_SHIFT) & AC_MASK) | ((np << TC_SHIFT) & TC_MASK);
3277 >
3278 >        commonPool = new ForkJoinPool(par, ct, fac, handler);
3279 >        modifyThreadPermission = new RuntimePermission("modifyThread");
3280      }
3281  
3282      /**

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines