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.117 by jsr166, Sat Jan 28 04:32:25 2012 UTC vs.
Revision 1.123 by dl, Mon Feb 20 18:20:06 2012 UTC

# Line 5 | Line 5
5   */
6  
7   package jsr166y;
8
8   import java.util.ArrayList;
9   import java.util.Arrays;
10   import java.util.Collection;
# Line 21 | Line 20 | import java.util.concurrent.RunnableFutu
20   import java.util.concurrent.TimeUnit;
21   import java.util.concurrent.atomic.AtomicInteger;
22   import java.util.concurrent.atomic.AtomicLong;
23 < import java.util.concurrent.locks.ReentrantLock;
23 > import java.util.concurrent.locks.AbstractQueuedSynchronizer;
24   import java.util.concurrent.locks.Condition;
25  
26   /**
# Line 177 | Line 176 | public class ForkJoinPool extends Abstra
176       * If an attempted steal fails, a thief always chooses a different
177       * random victim target to try next. So, in order for one thief to
178       * progress, it suffices for any in-progress poll or new push on
179 <     * any empty queue to complete.
179 >     * any empty queue to complete. (This is why we normally use
180 >     * method pollAt and its variants that try once at the apparent
181 >     * base index, else consider alternative actions, rather than
182 >     * method poll.)
183       *
184       * This approach also enables support of a user mode in which local
185       * task processing is in FIFO, not LIFO order, simply by using
# Line 203 | Line 205 | public class ForkJoinPool extends Abstra
205       * take tasks, and they are multiplexed on to a finite number of
206       * shared work queues. However, classes are set up so that future
207       * extensions could allow submitters to optionally help perform
208 <     * tasks as well. Pool submissions from internal workers are also
209 <     * allowed, but use randomized rather than thread-hashed queue
210 <     * indices to avoid imbalance.  Insertion of tasks in shared mode
211 <     * requires a lock (mainly to protect in the case of resizing) but
212 <     * we use only a simple spinlock (using bits in field runState),
213 <     * because submitters encountering a busy queue try or create
212 <     * others so never block.
208 >     * tasks as well. Insertion of tasks in shared mode requires a
209 >     * lock (mainly to protect in the case of resizing) but we use
210 >     * only a simple spinlock (using bits in field runState), because
211 >     * submitters encountering a busy queue move on to try or create
212 >     * other queues -- they block only when creating and registering
213 >     * new queues.
214       *
215       * Management
216       * ==========
# Line 247 | Line 248 | public class ForkJoinPool extends Abstra
248       * readers must tolerate null slots. Shared (submission) queues
249       * are at even indices, worker queues at odd indices. Grouping
250       * them together in this way simplifies and speeds up task
251 <     * scanning. To avoid flailing during start-up, the array is
252 <     * presized to hold twice #parallelism workers (which is unlikely
253 <     * to need further resizing during execution). But to avoid
254 <     * dealing with so many null slots, variable runState includes a
254 <     * mask for the nearest power of two that contains all current
255 <     * workers.  All worker thread creation is on-demand, triggered by
256 <     * task submissions, replacement of terminated workers, and/or
251 >     * scanning.
252 >     *
253 >     * All worker thread creation is on-demand, triggered by task
254 >     * submissions, replacement of terminated workers, and/or
255       * compensation for blocked workers. However, all other support
256       * code is set up to work with other policies.  To ensure that we
257       * do not hold on to worker references that would prevent GC, ALL
# Line 266 | Line 264 | public class ForkJoinPool extends Abstra
264       * both index-check and null-check the IDs. All such accesses
265       * ignore bad IDs by returning out early from what they are doing,
266       * since this can only be associated with termination, in which
267 <     * case it is OK to give up.
268 <     *
269 <     * All uses of the workQueues array check that it is non-null
270 <     * (even if previously non-null). This allows nulling during
271 <     * termination, which is currently not necessary, but remains an
272 <     * option for resource-revocation-based shutdown schemes. It also
275 <     * helps reduce JIT issuance of uncommon-trap code, which tends to
267 >     * case it is OK to give up.  All uses of the workQueues array
268 >     * also check that it is non-null (even if previously
269 >     * non-null). This allows nulling during termination, which is
270 >     * currently not necessary, but remains an option for
271 >     * resource-revocation-based shutdown schemes. It also helps
272 >     * reduce JIT issuance of uncommon-trap code, which tends to
273       * unnecessarily complicate control flow in some methods.
274       *
275       * Event Queuing. Unlike HPC work-stealing frameworks, we cannot
# Line 383 | Line 380 | public class ForkJoinPool extends Abstra
380       * (http://portal.acm.org/citation.cfm?id=155354). It differs in
381       * that: (1) We only maintain dependency links across workers upon
382       * steals, rather than use per-task bookkeeping.  This sometimes
383 <     * requires a linear scan of workers array to locate stealers, but
384 <     * often doesn't because stealers leave hints (that may become
383 >     * requires a linear scan of workQueues array to locate stealers,
384 >     * but often doesn't because stealers leave hints (that may become
385       * stale/wrong) of where to locate them.  A stealHint is only a
386       * hint because a worker might have had multiple steals and the
387       * hint records only one of them (usually the most current).
# Line 395 | Line 392 | public class ForkJoinPool extends Abstra
392       * which means that we miss links in the chain during long-lived
393       * tasks, GC stalls etc (which is OK since blocking in such cases
394       * is usually a good idea).  (4) We bound the number of attempts
395 <     * to find work (see MAX_HELP_DEPTH) and fall back to suspending
396 <     * the worker and if necessary replacing it with another.
395 >     * to find work (see MAX_HELP) and fall back to suspending the
396 >     * worker and if necessary replacing it with another.
397       *
398       * It is impossible to keep exactly the target parallelism number
399       * of threads running at any given time.  Determining the
400       * existence of conservatively safe helping targets, the
401       * availability of already-created spares, and the apparent need
402       * to create new spares are all racy, so we rely on multiple
403 <     * retries of each.  Currently, in keeping with on-demand
404 <     * signalling policy, we compensate only if blocking would leave
405 <     * less than one active (non-waiting, non-blocked) worker.
406 <     * Additionally, to avoid some false alarms due to GC, lagging
407 <     * counters, system activity, etc, compensated blocking for joins
408 <     * is only attempted after rechecks stabilize in
409 <     * ForkJoinTask.awaitJoin. (Retries are interspersed with
410 <     * Thread.yield, for good citizenship.)
403 >     * retries of each.  Compensation in the apparent absence of
404 >     * helping opportunities is challenging to control on JVMs, where
405 >     * GC and other activities can stall progress of tasks that in
406 >     * turn stall out many other dependent tasks, without us being
407 >     * able to determine whether they will ever require compensation.
408 >     * Even though work-stealing otherwise encounters little
409 >     * degradation in the presence of more threads than cores,
410 >     * aggressively adding new threads in such cases entails risk of
411 >     * unwanted positive feedback control loops in which more threads
412 >     * cause more dependent stalls (as well as delayed progress of
413 >     * unblocked threads to the point that we know they are available)
414 >     * leading to more situations requiring more threads, and so
415 >     * on. This aspect of control can be seen as an (analytically
416 >     * intractible) game with an opponent that may choose the worst
417 >     * (for us) active thread to stall at any time.  We take several
418 >     * precautions to bound losses (and thus bound gains), mainly in
419 >     * methods tryCompensate and awaitJoin: (1) We only try
420 >     * compensation after attempting enough helping steps (measured
421 >     * via counting and timing) that we have already consumed the
422 >     * estimated cost of creating and activating a new thread.  (2) We
423 >     * allow up to 50% of threads to be blocked before initially
424 >     * adding any others, and unless completely saturated, check that
425 >     * some work is available for a new worker before adding. Also, we
426 >     * create up to only 50% more threads until entering a mode that
427 >     * only adds a thread if all others are possibly blocked.  All
428 >     * together, this means that we might be half as fast to react,
429 >     * and create half as many threads as possible in the ideal case,
430 >     * but present vastly fewer anomalies in all other cases compared
431 >     * to both more aggressive and more conservative alternatives.
432       *
433       * Style notes: There is a lot of representation-level coupling
434       * among classes ForkJoinPool, ForkJoinWorkerThread, and
# Line 418 | Line 436 | public class ForkJoinPool extends Abstra
436       * managed by ForkJoinPool, so are directly accessed.  There is
437       * little point trying to reduce this, since any associated future
438       * changes in representations will need to be accompanied by
439 <     * algorithmic changes anyway. All together, these low-level
440 <     * implementation choices produce as much as a factor of 4
441 <     * performance improvement compared to naive implementations, and
442 <     * enable the processing of billions of tasks per second, at the
443 <     * expense of some ugliness.
444 <     *
445 <     * Methods signalWork() and scan() are the main bottlenecks, so are
446 <     * especially heavily micro-optimized/mangled.  There are lots of
447 <     * inline assignments (of form "while ((local = field) != 0)")
448 <     * which are usually the simplest way to ensure the required read
449 <     * orderings (which are sometimes critical). This leads to a
450 <     * "C"-like style of listing declarations of these locals at the
451 <     * heads of methods or blocks.  There are several occurrences of
452 <     * the unusual "do {} while (!cas...)"  which is the simplest way
435 <     * to force an update of a CAS'ed variable. There are also other
436 <     * coding oddities that help some methods perform reasonably even
437 <     * when interpreted (not compiled).
439 >     * algorithmic changes anyway. Several methods intrinsically
440 >     * sprawl because they must accumulate sets of consistent reads of
441 >     * volatiles held in local variables.  Methods signalWork() and
442 >     * scan() are the main bottlenecks, so are especially heavily
443 >     * micro-optimized/mangled.  There are lots of inline assignments
444 >     * (of form "while ((local = field) != 0)") which are usually the
445 >     * simplest way to ensure the required read orderings (which are
446 >     * sometimes critical). This leads to a "C"-like style of listing
447 >     * declarations of these locals at the heads of methods or blocks.
448 >     * There are several occurrences of the unusual "do {} while
449 >     * (!cas...)"  which is the simplest way to force an update of a
450 >     * CAS'ed variable. There are also other coding oddities that help
451 >     * some methods perform reasonably even when interpreted (not
452 >     * compiled).
453       *
454       * The order of declarations in this file is:
455 <     * (1) statics
456 <     * (2) fields (along with constants used when unpacking some of
457 <     *     them), listed in an order that tends to reduce contention
458 <     *     among them a bit under most JVMs;
459 <     * (3) nested classes
460 <     * (4) internal control methods
461 <     * (5) callbacks and other support for ForkJoinTask methods
462 <     * (6) exported methods (plus a few little helpers)
448 <     * (7) static block initializing all statics in a minimally
449 <     *     dependent order.
455 >     * (1) Static utility functions
456 >     * (2) Nested (static) classes
457 >     * (3) Static fields
458 >     * (4) Fields, along with constants used when unpacking some of them
459 >     * (5) Internal control methods
460 >     * (6) Callbacks and other support for ForkJoinTask methods
461 >     * (7) Exported methods
462 >     * (8) Static block initializing statics in minimally dependent order
463       */
464  
465 +    // Static utilities
466 +
467 +    /**
468 +     * If there is a security manager, makes sure caller has
469 +     * permission to modify threads.
470 +     */
471 +    private static void checkPermission() {
472 +        SecurityManager security = System.getSecurityManager();
473 +        if (security != null)
474 +            security.checkPermission(modifyThreadPermission);
475 +    }
476 +
477 +    // Nested classes
478 +
479      /**
480       * Factory for creating new {@link ForkJoinWorkerThread}s.
481       * A {@code ForkJoinWorkerThreadFactory} must be defined and used
# Line 477 | Line 504 | public class ForkJoinPool extends Abstra
504      }
505  
506      /**
507 <     * Creates a new ForkJoinWorkerThread. This factory is used unless
508 <     * overridden in ForkJoinPool constructors.
509 <     */
510 <    public static final ForkJoinWorkerThreadFactory
511 <        defaultForkJoinWorkerThreadFactory;
512 <
513 <    /**
514 <     * Permission required for callers of methods that may start or
515 <     * kill threads.
516 <     */
517 <    private static final RuntimePermission modifyThreadPermission;
518 <
519 <    /**
520 <     * If there is a security manager, makes sure caller has
521 <     * permission to modify threads.
522 <     */
523 <    private static void checkPermission() {
524 <        SecurityManager security = System.getSecurityManager();
525 <        if (security != null)
526 <            security.checkPermission(modifyThreadPermission);
507 >     * A simple non-reentrant lock used for exclusion when managing
508 >     * queues and workers. We use a custom lock so that we can readily
509 >     * probe lock state in constructions that check among alternative
510 >     * actions. The lock is normally only very briefly held, and
511 >     * sometimes treated as a spinlock, but other usages block to
512 >     * reduce overall contention in those cases where locked code
513 >     * bodies perform allocation/resizing.
514 >     */
515 >    static final class Mutex extends AbstractQueuedSynchronizer {
516 >        public final boolean tryAcquire(int ignore) {
517 >            return compareAndSetState(0, 1);
518 >        }
519 >        public final boolean tryRelease(int ignore) {
520 >            setState(0);
521 >            return true;
522 >        }
523 >        public final void lock() { acquire(0); }
524 >        public final void unlock() { release(0); }
525 >        public final boolean isHeldExclusively() { return getState() == 1; }
526 >        public final Condition newCondition() { return new ConditionObject(); }
527      }
528  
529      /**
530 <     * Generator for assigning sequence numbers as pool names.
531 <     */
532 <    private static final AtomicInteger poolNumberGenerator;
533 <
507 <    /**
508 <     * Bits and masks for control variables
509 <     *
510 <     * Field ctl is a long packed with:
511 <     * AC: Number of active running workers minus target parallelism (16 bits)
512 <     * TC: Number of total workers minus target parallelism (16 bits)
513 <     * ST: true if pool is terminating (1 bit)
514 <     * EC: the wait count of top waiting thread (15 bits)
515 <     * ID: ~(poolIndex >>> 1) of top of Treiber stack of waiters (16 bits)
516 <     *
517 <     * When convenient, we can extract the upper 32 bits of counts and
518 <     * the lower 32 bits of queue state, u = (int)(ctl >>> 32) and e =
519 <     * (int)ctl.  The ec field is never accessed alone, but always
520 <     * together with id and st. The offsets of counts by the target
521 <     * parallelism and the positionings of fields makes it possible to
522 <     * perform the most common checks via sign tests of fields: When
523 <     * ac is negative, there are not enough active workers, when tc is
524 <     * negative, there are not enough total workers, when id is
525 <     * negative, there is at least one waiting worker, and when e is
526 <     * negative, the pool is terminating.  To deal with these possibly
527 <     * negative fields, we use casts in and out of "short" and/or
528 <     * signed shifts to maintain signedness.
529 <     *
530 <     * When a thread is queued (inactivated), its eventCount field is
531 <     * negative, which is the only way to tell if a worker is
532 <     * prevented from executing tasks, even though it must continue to
533 <     * scan for them to avoid queuing races.
534 <     *
535 <     * Field runState is an int packed with:
536 <     * SHUTDOWN: true if shutdown is enabled (1 bit)
537 <     * SEQ:  a sequence number updated upon (de)registering workers (15 bits)
538 <     * MASK: mask (power of 2 - 1) covering all registered poolIndexes (16 bits)
539 <     *
540 <     * The combination of mask and sequence number enables simple
541 <     * consistency checks: Staleness of read-only operations on the
542 <     * workers and queues arrays can be checked by comparing runState
543 <     * before vs after the reads. The low 16 bits (i.e, anding with
544 <     * SMASK) hold the smallest power of two covering all worker
545 <     * indices, minus one.  The mask for queues (vs workers) is twice
546 <     * this value plus 1.
547 <     */
548 <
549 <    // bit positions/shifts for fields
550 <    private static final int  AC_SHIFT   = 48;
551 <    private static final int  TC_SHIFT   = 32;
552 <    private static final int  ST_SHIFT   = 31;
553 <    private static final int  EC_SHIFT   = 16;
554 <
555 <    // bounds
556 <    private static final int  MAX_ID     = 0x7fff;  // max poolIndex
557 <    private static final int  SMASK      = 0xffff;  // mask short bits
558 <    private static final int  SHORT_SIGN = 1 << 15;
559 <    private static final int  INT_SIGN   = 1 << 31;
560 <
561 <    // masks
562 <    private static final long STOP_BIT   = 0x0001L << ST_SHIFT;
563 <    private static final long AC_MASK    = ((long)SMASK) << AC_SHIFT;
564 <    private static final long TC_MASK    = ((long)SMASK) << TC_SHIFT;
565 <
566 <    // units for incrementing and decrementing
567 <    private static final long TC_UNIT    = 1L << TC_SHIFT;
568 <    private static final long AC_UNIT    = 1L << AC_SHIFT;
569 <
570 <    // masks and units for dealing with u = (int)(ctl >>> 32)
571 <    private static final int  UAC_SHIFT  = AC_SHIFT - 32;
572 <    private static final int  UTC_SHIFT  = TC_SHIFT - 32;
573 <    private static final int  UAC_MASK   = SMASK << UAC_SHIFT;
574 <    private static final int  UTC_MASK   = SMASK << UTC_SHIFT;
575 <    private static final int  UAC_UNIT   = 1 << UAC_SHIFT;
576 <    private static final int  UTC_UNIT   = 1 << UTC_SHIFT;
577 <
578 <    // masks and units for dealing with e = (int)ctl
579 <    private static final int E_MASK      = 0x7fffffff; // no STOP_BIT
580 <    private static final int E_SEQ       = 1 << EC_SHIFT;
581 <
582 <    // runState bits
583 <    private static final int SHUTDOWN    = 1 << 31;
584 <    private static final int RS_SEQ      = 1 << 16;
585 <    private static final int RS_SEQ_MASK = 0x7fff0000;
586 <
587 <    // access mode for WorkQueue
588 <    static final int LIFO_QUEUE          =  0;
589 <    static final int FIFO_QUEUE          =  1;
590 <    static final int SHARED_QUEUE        = -1;
591 <
592 <    /**
593 <     * The wakeup interval (in nanoseconds) for a worker waiting for a
594 <     * task when the pool is quiescent to instead try to shrink the
595 <     * number of workers.  The exact value does not matter too
596 <     * much. It must be short enough to release resources during
597 <     * sustained periods of idleness, but not so short that threads
598 <     * are continually re-created.
599 <     */
600 <    private static final long SHRINK_RATE =
601 <        4L * 1000L * 1000L * 1000L; // 4 seconds
602 <
603 <    /**
604 <     * The timeout value for attempted shrinkage, includes
605 <     * some slop to cope with system timer imprecision.
606 <     */
607 <    private static final long SHRINK_TIMEOUT = SHRINK_RATE - (SHRINK_RATE / 10);
608 <
609 <    /**
610 <     * The maximum stolen->joining link depth allowed in tryHelpStealer.
611 <     * Depths for legitimate chains are unbounded, but we use a fixed
612 <     * constant to avoid (otherwise unchecked) cycles and to bound
613 <     * staleness of traversal parameters at the expense of sometimes
614 <     * blocking when we could be helping.
615 <     */
616 <    private static final int MAX_HELP_DEPTH = 16;
617 <
618 <    /*
619 <     * Field layout order in this class tends to matter more than one
620 <     * would like. Runtime layout order is only loosely related to
621 <     * declaration order and may differ across JVMs, but the following
622 <     * empirically works OK on current JVMs.
530 >     * Class for artificial tasks that are used to replace the target
531 >     * of local joins if they are removed from an interior queue slot
532 >     * in WorkQueue.tryRemoveAndExec. We don't need the proxy to
533 >     * actually do anything beyond having a unique identity.
534       */
535 <
536 <    volatile long ctl;                       // main pool control
537 <    final int parallelism;                   // parallelism level
538 <    final int localMode;                     // per-worker scheduling mode
539 <    int nextPoolIndex;                       // hint used in registerWorker
540 <    volatile int runState;                   // shutdown status, seq, and mask
630 <    WorkQueue[] workQueues;                  // main registry
631 <    final ReentrantLock lock;                // for registration
632 <    final Condition termination;             // for awaitTermination
633 <    final ForkJoinWorkerThreadFactory factory; // factory for new workers
634 <    final Thread.UncaughtExceptionHandler ueh; // per-worker UEH
635 <    final AtomicLong stealCount;             // collect counts when terminated
636 <    final AtomicInteger nextWorkerNumber;    // to create worker name string
637 <    final String workerNamePrefix;           // Prefix for assigning worker names
535 >    static final class EmptyTask extends ForkJoinTask<Void> {
536 >        EmptyTask() { status = ForkJoinTask.NORMAL; } // force done
537 >        public final Void getRawResult() { return null; }
538 >        public final void setRawResult(Void x) {}
539 >        public final boolean exec() { return true; }
540 >    }
541  
542      /**
543       * Queues supporting work-stealing as well as external task
# Line 685 | Line 588 | public class ForkJoinPool extends Abstra
588       * avoiding really bad worst-case access. (Until better JVM
589       * support is in place, this padding is dependent on transient
590       * properties of JVM field layout rules.)  We also take care in
591 <     * allocating and sizing and resizing the array. Non-shared queue
591 >     * allocating, sizing and resizing the array. Non-shared queue
592       * arrays are initialized (via method growArray) by workers before
593       * use. Others are allocated on first use.
594       */
595      static final class WorkQueue {
596          /**
597           * Capacity of work-stealing queue array upon initialization.
598 <         * Must be a power of two; at least 4, but set larger to
599 <         * reduce cacheline sharing among queues.
598 >         * Must be a power of two; at least 4, but should be larger to
599 >         * reduce or eliminate cacheline sharing among queues.
600 >         * Currently, it is much larger, as a partial workaround for
601 >         * the fact that JVMs often place arrays in locations that
602 >         * share GC bookkeeping (especially cardmarks) such that
603 >         * per-write accesses encounter serious memory contention.
604           */
605 <        static final int INITIAL_QUEUE_CAPACITY = 1 << 8;
605 >        static final int INITIAL_QUEUE_CAPACITY = 1 << 13;
606  
607          /**
608           * Maximum size for queue arrays. Must be a power of two less
# Line 719 | Line 626 | public class ForkJoinPool extends Abstra
626          volatile int base;         // index of next slot for poll
627          int top;                   // index of next slot for push
628          ForkJoinTask<?>[] array;   // the elements (initially unallocated)
629 +        final ForkJoinPool pool;   // the containing pool (may be null)
630          final ForkJoinWorkerThread owner; // owning thread or null if shared
631          volatile Thread parker;    // == owner during call to park; else null
632          ForkJoinTask<?> currentJoin;  // task being joined in awaitJoin
633          ForkJoinTask<?> currentSteal; // current non-local task being executed
634          // Heuristic padding to ameliorate unfortunate memory placements
635 <        Object p00, p01, p02, p03, p04, p05, p06, p07, p08, p09, p0a;
635 >        Object p00, p01, p02, p03, p04, p05, p06, p07;
636 >        Object p08, p09, p0a, p0b, p0c, p0d, p0e;
637  
638 <        WorkQueue(ForkJoinWorkerThread owner, int mode) {
730 <            this.owner = owner;
638 >        WorkQueue(ForkJoinPool pool, ForkJoinWorkerThread owner, int mode) {
639              this.mode = mode;
640 +            this.pool = pool;
641 +            this.owner = owner;
642              // Place indices in the center of array (that is not yet allocated)
643              base = top = INITIAL_QUEUE_CAPACITY >>> 1;
644          }
645  
646          /**
647 <         * Returns number of tasks in the queue.
647 >         * Returns the approximate number of tasks in the queue.
648           */
649          final int queueSize() {
650 <            int n = base - top; // non-owner callers must read base first
651 <            return (n >= 0) ? 0 : -n;
650 >            int n = base - top;       // non-owner callers must read base first
651 >            return (n >= 0) ? 0 : -n; // ignore transient negative
652 >        }
653 >
654 >        /**
655 >         * Provides a more accurate estimate of whether this queue has
656 >         * any tasks than does queueSize, by checking whether a
657 >         * near-empty queue has at least one unclaimed task.
658 >         */
659 >        final boolean isEmpty() {
660 >            ForkJoinTask<?>[] a; int m, s;
661 >            int n = base - (s = top);
662 >            return (n >= 0 ||
663 >                    (n == -1 &&
664 >                     ((a = array) == null ||
665 >                      (m = a.length - 1) < 0 ||
666 >                      U.getObjectVolatile
667 >                      (a, ((m & (s - 1)) << ASHIFT) + ABASE) == null)));
668          }
669  
670          /**
671           * Pushes a task. Call only by owner in unshared queues.
672           *
673           * @param task the task. Caller must ensure non-null.
748         * @param p if non-null, pool to signal if necessary
674           * @throw RejectedExecutionException if array cannot be resized
675           */
676 <        final void push(ForkJoinTask<?> task, ForkJoinPool p) {
677 <            ForkJoinTask<?>[] a;
676 >        final void push(ForkJoinTask<?> task) {
677 >            ForkJoinTask<?>[] a; ForkJoinPool p;
678              int s = top, m, n;
679              if ((a = array) != null) {    // ignore if queue removed
680                  U.putOrderedObject
681                      (a, (((m = a.length - 1) & s) << ASHIFT) + ABASE, task);
682                  if ((n = (top = s + 1) - base) <= 2) {
683 <                    if (p != null)
683 >                    if ((p = pool) != null)
684                          p.signalWork();
685                  }
686                  else if (n >= m)
# Line 774 | Line 699 | public class ForkJoinPool extends Abstra
699              boolean submitted = false;
700              if (runState == 0 && U.compareAndSwapInt(this, RUNSTATE, 0, 1)) {
701                  ForkJoinTask<?>[] a = array;
702 <                int s = top, n = s - base;
702 >                int s = top;
703                  try {
704 <                    if ((a != null && n < a.length - 1) ||
704 >                    if ((a != null && a.length > s + 1 - base) ||
705                          (a = growArray(false)) != null) { // must presize
706                          int j = (((a.length - 1) & s) << ASHIFT) + ABASE;
707                          U.putObject(a, (long)j, task);    // don't need "ordered"
# Line 791 | Line 716 | public class ForkJoinPool extends Abstra
716          }
717  
718          /**
719 <         * Takes next task, if one exists, in FIFO order.
720 <         */
721 <        final ForkJoinTask<?> poll() {
797 <            ForkJoinTask<?>[] a; int b, i;
798 <            while ((b = base) - top < 0 && (a = array) != null &&
799 <                   (i = (a.length - 1) & b) >= 0) {
800 <                int j = (i << ASHIFT) + ABASE;
801 <                ForkJoinTask<?> t = (ForkJoinTask<?>)U.getObjectVolatile(a, j);
802 <                if (t != null && base == b &&
803 <                    U.compareAndSwapObject(a, j, t, null)) {
804 <                    base = b + 1;
805 <                    return t;
806 <                }
807 <            }
808 <            return null;
809 <        }
810 <
811 <        /**
812 <         * Takes next task, if one exists, in LIFO order.
813 <         * Call only by owner in unshared queues.
719 >         * Takes next task, if one exists, in LIFO order.  Call only
720 >         * by owner in unshared queues. (We do not have a shared
721 >         * version of this method because it is never needed.)
722           */
723          final ForkJoinTask<?> pop() {
724              ForkJoinTask<?> t; int m;
# Line 830 | Line 738 | public class ForkJoinPool extends Abstra
738          }
739  
740          /**
741 +         * Takes a task in FIFO order if b is base of queue and a task
742 +         * can be claimed without contention. Specialized versions
743 +         * appear in ForkJoinPool methods scan and tryHelpStealer.
744 +         */
745 +        final ForkJoinTask<?> pollAt(int b) {
746 +            ForkJoinTask<?> t; ForkJoinTask<?>[] a;
747 +            if ((a = array) != null) {
748 +                int j = (((a.length - 1) & b) << ASHIFT) + ABASE;
749 +                if ((t = (ForkJoinTask<?>)U.getObjectVolatile(a, j)) != null &&
750 +                    base == b &&
751 +                    U.compareAndSwapObject(a, j, t, null)) {
752 +                    base = b + 1;
753 +                    return t;
754 +                }
755 +            }
756 +            return null;
757 +        }
758 +
759 +        /**
760 +         * Takes next task, if one exists, in FIFO order.
761 +         */
762 +        final ForkJoinTask<?> poll() {
763 +            ForkJoinTask<?>[] a; int b; ForkJoinTask<?> t;
764 +            while ((b = base) - top < 0 && (a = array) != null) {
765 +                int j = (((a.length - 1) & b) << ASHIFT) + ABASE;
766 +                t = (ForkJoinTask<?>)U.getObjectVolatile(a, j);
767 +                if (t != null) {
768 +                    if (base == b &&
769 +                        U.compareAndSwapObject(a, j, t, null)) {
770 +                        base = b + 1;
771 +                        return t;
772 +                    }
773 +                }
774 +                else if (base == b) {
775 +                    if (b + 1 == top)
776 +                        break;
777 +                    Thread.yield(); // wait for lagging update
778 +                }
779 +            }
780 +            return null;
781 +        }
782 +
783 +        /**
784           * Takes next task, if one exists, in order specified by mode.
785           */
786          final ForkJoinTask<?> nextLocalTask() {
# Line 849 | Line 800 | public class ForkJoinPool extends Abstra
800          }
801  
802          /**
852         * Returns task at index b if b is current base of queue.
853         */
854        final ForkJoinTask<?> pollAt(int b) {
855            ForkJoinTask<?>[] a; int i;
856            ForkJoinTask<?> task = null;
857            if ((a = array) != null && (i = ((a.length - 1) & b)) >= 0) {
858                int j = (i << ASHIFT) + ABASE;
859                ForkJoinTask<?> t = (ForkJoinTask<?>)U.getObjectVolatile(a, j);
860                if (t != null && base == b &&
861                    U.compareAndSwapObject(a, j, t, null)) {
862                    base = b + 1;
863                    task = t;
864                }
865            }
866            return task;
867        }
868
869        /**
803           * Pops the given task only if it is at the current top.
804           */
805          final boolean tryUnpush(ForkJoinTask<?> t) {
# Line 884 | Line 817 | public class ForkJoinPool extends Abstra
817           * Polls the given task only if it is at the current base.
818           */
819          final boolean pollFor(ForkJoinTask<?> task) {
820 <            ForkJoinTask<?>[] a; int b, i;
821 <            if ((b = base) - top < 0 && (a = array) != null &&
822 <                (i = (a.length - 1) & b) >= 0) {
890 <                int j = (i << ASHIFT) + ABASE;
820 >            ForkJoinTask<?>[] a; int b;
821 >            if ((b = base) - top < 0 && (a = array) != null) {
822 >                int j = (((a.length - 1) & b) << ASHIFT) + ABASE;
823                  if (U.getObjectVolatile(a, j) == task && base == b &&
824                      U.compareAndSwapObject(a, j, task, null)) {
825                      base = b + 1;
# Line 990 | Line 922 | public class ForkJoinPool extends Abstra
922                  ForkJoinTask.cancelIgnoringExceptions(t);
923          }
924  
925 +        /**
926 +         * Computes next value for random probes.  Scans don't require
927 +         * a very high quality generator, but also not a crummy one.
928 +         * Marsaglia xor-shift is cheap and works well enough.  Note:
929 +         * This is manually inlined in its usages in ForkJoinPool to
930 +         * avoid writes inside busy scan loops.
931 +         */
932 +        final int nextSeed() {
933 +            int r = seed;
934 +            r ^= r << 13;
935 +            r ^= r >>> 17;
936 +            return seed = r ^= r << 5;
937 +        }
938 +
939          // Execution methods
940  
941          /**
942           * Removes and runs tasks until empty, using local mode
943 <         * ordering.
943 >         * ordering. Normally called only after checking for apparent
944 >         * non-emptiness.
945           */
946          final void runLocalTasks() {
947 <            if (base - top < 0) {
948 <                for (ForkJoinTask<?> t; (t = nextLocalTask()) != null; )
949 <                    t.doExec();
947 >            // hoist checks from repeated pop/poll
948 >            ForkJoinTask<?>[] a; int m;
949 >            if ((a = array) != null && (m = a.length - 1) >= 0) {
950 >                if (mode == 0) {
951 >                    for (int s; (s = top - 1) - base >= 0;) {
952 >                        int j = ((m & s) << ASHIFT) + ABASE;
953 >                        ForkJoinTask<?> t =
954 >                            (ForkJoinTask<?>)U.getObjectVolatile(a, j);
955 >                        if (t != null) {
956 >                            if (U.compareAndSwapObject(a, j, t, null)) {
957 >                                top = s;
958 >                                t.doExec();
959 >                            }
960 >                        }
961 >                        else
962 >                            break;
963 >                    }
964 >                }
965 >                else {
966 >                    for (int b; (b = base) - top < 0;) {
967 >                        int j = ((m & b) << ASHIFT) + ABASE;
968 >                        ForkJoinTask<?> t =
969 >                            (ForkJoinTask<?>)U.getObjectVolatile(a, j);
970 >                        if (t != null) {
971 >                            if (base == b &&
972 >                                U.compareAndSwapObject(a, j, t, null)) {
973 >                                base = b + 1;
974 >                                t.doExec();
975 >                            }
976 >                        } else if (base == b) {
977 >                            if (b + 1 == top)
978 >                                break;
979 >                            Thread.yield(); // wait for lagging update
980 >                        }
981 >                    }
982 >                }
983              }
984          }
985  
# Line 1014 | Line 994 | public class ForkJoinPool extends Abstra
994              if (t != null) {
995                  currentSteal = t;
996                  t.doExec();
997 <                runLocalTasks();
997 >                if (top != base)        // conservative guard
998 >                    runLocalTasks();
999                  ++nsteals;
1000                  currentSteal = null;
1001              }
1002 <            else if (runState < 0)            // terminating
1002 >            else if (runState < 0)      // terminating
1003                  alive = false;
1004              return alive;
1005          }
# Line 1036 | Line 1017 | public class ForkJoinPool extends Abstra
1017          }
1018  
1019          /**
1020 <         * Computes next value for random probes.  Scans don't require
1040 <         * a very high quality generator, but also not a crummy one.
1041 <         * Marsaglia xor-shift is cheap and works well enough.  Note:
1042 <         * This is manually inlined in several usages in ForkJoinPool
1043 <         * to avoid writes inside busy scan loops.
1020 >         * Returns true if owned and not known to be blocked.
1021           */
1022 <        final int nextSeed() {
1023 <            int r = seed;
1024 <            r ^= r << 13;
1025 <            r ^= r >>> 17;
1026 <            r ^= r << 5;
1027 <            return seed = r;
1022 >        final boolean isApparentlyUnblocked() {
1023 >            Thread wt; Thread.State s;
1024 >            return (eventCount >= 0 &&
1025 >                    (wt = owner) != null &&
1026 >                    (s = wt.getState()) != Thread.State.BLOCKED &&
1027 >                    s != Thread.State.WAITING &&
1028 >                    s != Thread.State.TIMED_WAITING);
1029 >        }
1030 >
1031 >        /**
1032 >         * If this owned and is not already interrupted, try to
1033 >         * interrupt and/or unpark, ignoring exceptions.
1034 >         */
1035 >        final void interruptOwner() {
1036 >            Thread wt, p;
1037 >            if ((wt = owner) != null && !wt.isInterrupted()) {
1038 >                try {
1039 >                    wt.interrupt();
1040 >                } catch (SecurityException ignore) {
1041 >                }
1042 >            }
1043 >            if ((p = parker) != null)
1044 >                U.unpark(p);
1045          }
1046  
1047          // Unsafe mechanics
# Line 1075 | Line 1069 | public class ForkJoinPool extends Abstra
1069      }
1070  
1071      /**
1072 <     * Class for artificial tasks that are used to replace the target
1073 <     * of local joins if they are removed from an interior queue slot
1074 <     * in WorkQueue.tryRemoveAndExec. We don't need the proxy to
1075 <     * actually do anything beyond having a unique identity.
1076 <     */
1077 <    static final class EmptyTask extends ForkJoinTask<Void> {
1078 <        EmptyTask() { status = ForkJoinTask.NORMAL; } // force done
1079 <        public Void getRawResult() { return null; }
1080 <        public void setRawResult(Void x) {}
1081 <        public boolean exec() { return true; }
1082 <    }
1083 <
1084 <    /**
1085 <     * Per-thread records for (typically non-FJ) threads that submit
1092 <     * to pools. Cureently holds only psuedo-random seed / index that
1093 <     * is used to choose submission queues in method doSubmit. In the
1094 <     * future, this may incorporate a means to implement different
1095 <     * task rejection and resubmission policies.
1072 >     * Per-thread records for threads that submit to pools. Currently
1073 >     * holds only pseudo-random seed / index that is used to choose
1074 >     * submission queues in method doSubmit. In the future, this may
1075 >     * also incorporate a means to implement different task rejection
1076 >     * and resubmission policies.
1077 >     *
1078 >     * Seeds for submitters and workers/workQueues work in basically
1079 >     * the same way but are initialized and updated using slightly
1080 >     * different mechanics. Both are initialized using the same
1081 >     * approach as in class ThreadLocal, where successive values are
1082 >     * unlikely to collide with previous values. This is done during
1083 >     * registration for workers, but requires a separate AtomicInteger
1084 >     * for submitters. Seeds are then randomly modified upon
1085 >     * collisions using xorshifts, which requires a non-zero seed.
1086       */
1087      static final class Submitter {
1088 <        int seed; // seed for random submission queue selection
1099 <
1100 <        // Heuristic padding to ameliorate unfortunate memory placements
1101 <        int p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, pa, pb, pc, pd, pe;
1102 <
1088 >        int seed;
1089          Submitter() {
1090 <            // Use identityHashCode, forced negative, for seed
1091 <            seed = System.identityHashCode(Thread.currentThread()) | (1 << 31);
1106 <        }
1107 <
1108 <        /**
1109 <         * Computes next value for random probes.  Like method
1110 <         * WorkQueue.nextSeed, this is manually inlined in several
1111 <         * usages to avoid writes inside busy loops.
1112 <         */
1113 <        final int nextSeed() {
1114 <            int r = seed;
1115 <            r ^= r << 13;
1116 <            r ^= r >>> 17;
1117 <            return seed = r ^= r << 5;
1090 >            int s = nextSubmitterSeed.getAndAdd(SEED_INCREMENT);
1091 >            seed = (s == 0) ? 1 : s; // ensure non-zero
1092          }
1093      }
1094  
# Line 1123 | Line 1097 | public class ForkJoinPool extends Abstra
1097          public Submitter initialValue() { return new Submitter(); }
1098      }
1099  
1100 +    // static fields (initialized in static initializer below)
1101 +
1102 +    /**
1103 +     * Creates a new ForkJoinWorkerThread. This factory is used unless
1104 +     * overridden in ForkJoinPool constructors.
1105 +     */
1106 +    public static final ForkJoinWorkerThreadFactory
1107 +        defaultForkJoinWorkerThreadFactory;
1108 +
1109 +    /**
1110 +     * Generator for assigning sequence numbers as pool names.
1111 +     */
1112 +    private static final AtomicInteger poolNumberGenerator;
1113 +
1114 +    /**
1115 +     * Generator for initial hashes/seeds for submitters. Accessed by
1116 +     * Submitter class constructor.
1117 +     */
1118 +    static final AtomicInteger nextSubmitterSeed;
1119 +
1120 +    /**
1121 +     * Permission required for callers of methods that may start or
1122 +     * kill threads.
1123 +     */
1124 +    private static final RuntimePermission modifyThreadPermission;
1125 +
1126      /**
1127       * Per-thread submission bookeeping. Shared across all pools
1128       * to reduce ThreadLocal pollution and because random motion
1129       * to avoid contention in one pool is likely to hold for others.
1130       */
1131 <    static final ThreadSubmitter submitters = new ThreadSubmitter();
1131 >    private static final ThreadSubmitter submitters;
1132 >
1133 >    // static constants
1134  
1135      /**
1136 <     * Top-level runloop for workers
1136 >     * The wakeup interval (in nanoseconds) for a worker waiting for a
1137 >     * task when the pool is quiescent to instead try to shrink the
1138 >     * number of workers.  The exact value does not matter too
1139 >     * much. It must be short enough to release resources during
1140 >     * sustained periods of idleness, but not so short that threads
1141 >     * are continually re-created.
1142       */
1143 <    final void runWorker(ForkJoinWorkerThread wt) {
1144 <        // Initialize queue array and seed in this thread
1138 <        WorkQueue w = wt.workQueue;
1139 <        w.growArray(false);
1140 <        // Same initial hash as Submitters
1141 <        w.seed = System.identityHashCode(Thread.currentThread()) | (1 << 31);
1143 >    private static final long SHRINK_RATE =
1144 >        4L * 1000L * 1000L * 1000L; // 4 seconds
1145  
1146 <        do {} while (w.runTask(scan(w)));
1147 <    }
1146 >    /**
1147 >     * The timeout value for attempted shrinkage, includes
1148 >     * some slop to cope with system timer imprecision.
1149 >     */
1150 >    private static final long SHRINK_TIMEOUT = SHRINK_RATE - (SHRINK_RATE / 10);
1151 >
1152 >    /**
1153 >     * The maximum stolen->joining link depth allowed in method
1154 >     * tryHelpStealer.  Must be a power of two. This value also
1155 >     * controls the maximum number of times to try to help join a task
1156 >     * without any apparent progress or change in pool state before
1157 >     * giving up and blocking (see awaitJoin).  Depths for legitimate
1158 >     * chains are unbounded, but we use a fixed constant to avoid
1159 >     * (otherwise unchecked) cycles and to bound staleness of
1160 >     * traversal parameters at the expense of sometimes blocking when
1161 >     * we could be helping.
1162 >     */
1163 >    private static final int MAX_HELP = 32;
1164 >
1165 >    /**
1166 >     * Secondary time-based bound (in nanosecs) for helping attempts
1167 >     * before trying compensated blocking in awaitJoin. Used in
1168 >     * conjunction with MAX_HELP to reduce variance due to different
1169 >     * polling rates associated with different helping options. The
1170 >     * value should roughly approximate the time required to create
1171 >     * and/or activate a worker thread.
1172 >     */
1173 >    private static final long COMPENSATION_DELAY = 100L * 1000L; // 0.1 millisec
1174 >
1175 >    /**
1176 >     * Increment for seed generators. See class ThreadLocal for
1177 >     * explanation.
1178 >     */
1179 >    private static final int SEED_INCREMENT = 0x61c88647;
1180 >
1181 >    /**
1182 >     * Bits and masks for control variables
1183 >     *
1184 >     * Field ctl is a long packed with:
1185 >     * AC: Number of active running workers minus target parallelism (16 bits)
1186 >     * TC: Number of total workers minus target parallelism (16 bits)
1187 >     * ST: true if pool is terminating (1 bit)
1188 >     * EC: the wait count of top waiting thread (15 bits)
1189 >     * ID: poolIndex of top of Treiber stack of waiters (16 bits)
1190 >     *
1191 >     * When convenient, we can extract the upper 32 bits of counts and
1192 >     * the lower 32 bits of queue state, u = (int)(ctl >>> 32) and e =
1193 >     * (int)ctl.  The ec field is never accessed alone, but always
1194 >     * together with id and st. The offsets of counts by the target
1195 >     * parallelism and the positionings of fields makes it possible to
1196 >     * perform the most common checks via sign tests of fields: When
1197 >     * ac is negative, there are not enough active workers, when tc is
1198 >     * negative, there are not enough total workers, and when e is
1199 >     * negative, the pool is terminating.  To deal with these possibly
1200 >     * negative fields, we use casts in and out of "short" and/or
1201 >     * signed shifts to maintain signedness.
1202 >     *
1203 >     * When a thread is queued (inactivated), its eventCount field is
1204 >     * set negative, which is the only way to tell if a worker is
1205 >     * prevented from executing tasks, even though it must continue to
1206 >     * scan for them to avoid queuing races. Note however that
1207 >     * eventCount updates lag releases so usage requires care.
1208 >     *
1209 >     * Field runState is an int packed with:
1210 >     * SHUTDOWN: true if shutdown is enabled (1 bit)
1211 >     * SEQ:  a sequence number updated upon (de)registering workers (30 bits)
1212 >     * INIT: set true after workQueues array construction (1 bit)
1213 >     *
1214 >     * The sequence number enables simple consistency checks:
1215 >     * Staleness of read-only operations on the workQueues array can
1216 >     * be checked by comparing runState before vs after the reads.
1217 >     */
1218 >
1219 >    // bit positions/shifts for fields
1220 >    private static final int  AC_SHIFT   = 48;
1221 >    private static final int  TC_SHIFT   = 32;
1222 >    private static final int  ST_SHIFT   = 31;
1223 >    private static final int  EC_SHIFT   = 16;
1224 >
1225 >    // bounds
1226 >    private static final int  SMASK      = 0xffff;  // short bits
1227 >    private static final int  MAX_CAP    = 0x7fff;  // max #workers - 1
1228 >    private static final int  SQMASK     = 0xfffe;  // even short bits
1229 >    private static final int  SHORT_SIGN = 1 << 15;
1230 >    private static final int  INT_SIGN   = 1 << 31;
1231 >
1232 >    // masks
1233 >    private static final long STOP_BIT   = 0x0001L << ST_SHIFT;
1234 >    private static final long AC_MASK    = ((long)SMASK) << AC_SHIFT;
1235 >    private static final long TC_MASK    = ((long)SMASK) << TC_SHIFT;
1236 >
1237 >    // units for incrementing and decrementing
1238 >    private static final long TC_UNIT    = 1L << TC_SHIFT;
1239 >    private static final long AC_UNIT    = 1L << AC_SHIFT;
1240 >
1241 >    // masks and units for dealing with u = (int)(ctl >>> 32)
1242 >    private static final int  UAC_SHIFT  = AC_SHIFT - 32;
1243 >    private static final int  UTC_SHIFT  = TC_SHIFT - 32;
1244 >    private static final int  UAC_MASK   = SMASK << UAC_SHIFT;
1245 >    private static final int  UTC_MASK   = SMASK << UTC_SHIFT;
1246 >    private static final int  UAC_UNIT   = 1 << UAC_SHIFT;
1247 >    private static final int  UTC_UNIT   = 1 << UTC_SHIFT;
1248 >
1249 >    // masks and units for dealing with e = (int)ctl
1250 >    private static final int E_MASK      = 0x7fffffff; // no STOP_BIT
1251 >    private static final int E_SEQ       = 1 << EC_SHIFT;
1252 >
1253 >    // runState bits
1254 >    private static final int SHUTDOWN    = 1 << 31;
1255 >
1256 >    // access mode for WorkQueue
1257 >    static final int LIFO_QUEUE          =  0;
1258 >    static final int FIFO_QUEUE          =  1;
1259 >    static final int SHARED_QUEUE        = -1;
1260 >
1261 >    // Instance fields
1262 >
1263 >    /*
1264 >     * Field layout order in this class tends to matter more than one
1265 >     * would like. Runtime layout order is only loosely related to
1266 >     * declaration order and may differ across JVMs, but the following
1267 >     * empirically works OK on current JVMs.
1268 >     */
1269  
1270 <    // Creating, registering and deregistering workers
1270 >    volatile long ctl;                         // main pool control
1271 >    final int parallelism;                     // parallelism level
1272 >    final int localMode;                       // per-worker scheduling mode
1273 >    final int submitMask;                      // submit queue index bound
1274 >    int nextSeed;                              // for initializing worker seeds
1275 >    volatile int runState;                     // shutdown status and seq
1276 >    WorkQueue[] workQueues;                    // main registry
1277 >    final Mutex lock;                          // for registration
1278 >    final Condition termination;               // for awaitTermination
1279 >    final ForkJoinWorkerThreadFactory factory; // factory for new workers
1280 >    final Thread.UncaughtExceptionHandler ueh; // per-worker UEH
1281 >    final AtomicLong stealCount;               // collect counts when terminated
1282 >    final AtomicInteger nextWorkerNumber;      // to create worker name string
1283 >    final String workerNamePrefix;             // to create worker name string
1284 >
1285 >    //  Creating, registering, and deregistering workers
1286  
1287      /**
1288       * Tries to create and start a worker
1289       */
1290      private void addWorker() {
1291          Throwable ex = null;
1292 <        ForkJoinWorkerThread w = null;
1292 >        ForkJoinWorkerThread wt = null;
1293          try {
1294 <            if ((w = factory.newThread(this)) != null) {
1295 <                w.start();
1294 >            if ((wt = factory.newThread(this)) != null) {
1295 >                wt.start();
1296                  return;
1297              }
1298          } catch (Throwable e) {
1299              ex = e;
1300          }
1301 <        deregisterWorker(w, ex);
1301 >        deregisterWorker(wt, ex); // adjust counts etc on failure
1302      }
1303  
1304      /**
# Line 1174 | Line 1313 | public class ForkJoinPool extends Abstra
1313      }
1314  
1315      /**
1316 <     * Callback from ForkJoinWorkerThread constructor to establish and
1317 <     * record its WorkQueue.
1316 >     * Callback from ForkJoinWorkerThread constructor to establish its
1317 >     * poolIndex and record its WorkQueue. To avoid scanning bias due
1318 >     * to packing entries in front of the workQueues array, we treat
1319 >     * the array as a simple power-of-two hash table using per-thread
1320 >     * seed as hash, expanding as needed.
1321       *
1322 <     * @param wt the worker thread
1322 >     * @param w the worker's queue
1323       */
1324 <    final void registerWorker(ForkJoinWorkerThread wt) {
1325 <        WorkQueue w = wt.workQueue;
1184 <        ReentrantLock lock = this.lock;
1324 >    final void registerWorker(WorkQueue w) {
1325 >        Mutex lock = this.lock;
1326          lock.lock();
1327          try {
1187            int k = nextPoolIndex;
1328              WorkQueue[] ws = workQueues;
1329 <            if (ws != null) {                       // ignore on shutdown
1330 <                int n = ws.length;
1331 <                if (k < 0 || (k & 1) == 0 || k >= n || ws[k] != null) {
1332 <                    for (k = 1; k < n && ws[k] != null; k += 2)
1333 <                        ;                           // workers are at odd indices
1334 <                    if (k >= n)                     // resize
1335 <                        workQueues = ws = Arrays.copyOf(ws, n << 1);
1336 <                }
1337 <                w.poolIndex = k;
1338 <                w.eventCount = ~(k >>> 1) & SMASK;  // Set up wait count
1339 <                ws[k] = w;                          // record worker
1340 <                nextPoolIndex = k + 2;
1341 <                int rs = runState;
1342 <                int m = rs & SMASK;                 // recalculate runState mask
1203 <                if (k > m)
1204 <                    m = (m << 1) + 1;
1205 <                runState = (rs & SHUTDOWN) | ((rs + RS_SEQ) & RS_SEQ_MASK) | m;
1329 >            if (w != null && ws != null) {          // skip on shutdown/failure
1330 >                int rs, n;
1331 >                while ((n = ws.length) <            // ensure can hold total
1332 >                       (parallelism + (short)(ctl >>> TC_SHIFT) << 1))
1333 >                    workQueues = ws = Arrays.copyOf(ws, n << 1);
1334 >                int m = n - 1;
1335 >                int s = nextSeed += SEED_INCREMENT; // rarely-colliding sequence
1336 >                w.seed = (s == 0) ? 1 : s;          // ensure non-zero seed
1337 >                int r = (s << 1) | 1;               // use odd-numbered indices
1338 >                while (ws[r &= m] != null)          // step by approx half size
1339 >                    r += ((n >>> 1) & SQMASK) + 2;
1340 >                w.eventCount = w.poolIndex = r;     // establish before recording
1341 >                ws[r] = w;                          // also update seq
1342 >                runState = ((rs = runState) & SHUTDOWN) | ((rs + 2) & ~SHUTDOWN);
1343              }
1344          } finally {
1345              lock.unlock();
# Line 1210 | Line 1347 | public class ForkJoinPool extends Abstra
1347      }
1348  
1349      /**
1350 <     * Final callback from terminating worker, as well as failure to
1351 <     * construct or start a worker in addWorker.  Removes record of
1350 >     * Final callback from terminating worker, as well as upon failure
1351 >     * to construct or start a worker in addWorker.  Removes record of
1352       * worker from array, and adjusts counts. If pool is shutting
1353       * down, tries to complete termination.
1354       *
# Line 1219 | Line 1356 | public class ForkJoinPool extends Abstra
1356       * @param ex the exception causing failure, or null if none
1357       */
1358      final void deregisterWorker(ForkJoinWorkerThread wt, Throwable ex) {
1359 +        Mutex lock = this.lock;
1360          WorkQueue w = null;
1361          if (wt != null && (w = wt.workQueue) != null) {
1362              w.runState = -1;                // ensure runState is set
1363              stealCount.getAndAdd(w.totalSteals + w.nsteals);
1364              int idx = w.poolIndex;
1227            ReentrantLock lock = this.lock;
1365              lock.lock();
1366              try {                           // remove record from array
1367                  WorkQueue[] ws = workQueues;
1368                  if (ws != null && idx >= 0 && idx < ws.length && ws[idx] == w)
1369 <                    ws[nextPoolIndex = idx] = null;
1369 >                    ws[idx] = null;
1370              } finally {
1371                  lock.unlock();
1372              }
# Line 1241 | Line 1378 | public class ForkJoinPool extends Abstra
1378                                             ((c - TC_UNIT) & TC_MASK) |
1379                                             (c & ~(AC_MASK|TC_MASK)))));
1380  
1381 <        if (!tryTerminate(false) && w != null) {
1381 >        if (!tryTerminate(false, false) && w != null) {
1382              w.cancelAll();                  // cancel remaining tasks
1383              if (w.array != null)            // suppress signal if never ran
1384                  signalWork();               // wake up or create replacement
1385 +            if (ex == null)                 // help clean refs on way out
1386 +                ForkJoinTask.helpExpungeStaleExceptions();
1387          }
1388  
1389          if (ex != null)                     // rethrow
1390              U.throwException(ex);
1391      }
1392  
1393 +
1394 +    // Submissions
1395 +
1396      /**
1397 <     * Tries to add and register a new queue at the given index.
1397 >     * Unless shutting down, adds the given task to a submission queue
1398 >     * at submitter's current queue index (modulo submission
1399 >     * range). If no queue exists at the index, one is created.  If
1400 >     * the queue is busy, another index is randomly chosen. The
1401 >     * submitMask bounds the effective number of queues to the
1402 >     * (nearest poswer of two for) parallelism level.
1403       *
1404 <     * @param idx the workQueues array index to register the queue
1405 <     * @return the queue, or null if could not add because could
1406 <     * not acquire lock or idx is unusable
1407 <     */
1408 <    private WorkQueue tryAddSharedQueue(int idx) {
1409 <        WorkQueue q = null;
1410 <        ReentrantLock lock = this.lock;
1411 <        if (idx >= 0 && (idx & 1) == 0 && !lock.isLocked()) {
1412 <            // create queue outside of lock but only if apparently free
1413 <            WorkQueue nq = new WorkQueue(null, SHARED_QUEUE);
1414 <            if (lock.tryLock()) {
1415 <                try {
1416 <                    WorkQueue[] ws = workQueues;
1417 <                    if (ws != null && idx < ws.length) {
1418 <                        if ((q = ws[idx]) == null) {
1419 <                            int rs;         // update runState seq
1420 <                            ws[idx] = q = nq;
1421 <                            runState = (((rs = runState) & SHUTDOWN) |
1275 <                                        ((rs + RS_SEQ) & ~SHUTDOWN));
1276 <                        }
1404 >     * @param task the task. Caller must ensure non-null.
1405 >     */
1406 >    private void doSubmit(ForkJoinTask<?> task) {
1407 >        Submitter s = submitters.get();
1408 >        for (int r = s.seed, m = submitMask;;) {
1409 >            WorkQueue[] ws; WorkQueue q;
1410 >            int k = r & m & SQMASK;          // use only even indices
1411 >            if (runState < 0 || (ws = workQueues) == null || ws.length <= k)
1412 >                throw new RejectedExecutionException(); // shutting down
1413 >            else if ((q = ws[k]) == null) {  // create new queue
1414 >                WorkQueue nq = new WorkQueue(this, null, SHARED_QUEUE);
1415 >                Mutex lock = this.lock;      // construct outside lock
1416 >                lock.lock();
1417 >                try {                        // recheck under lock
1418 >                    int rs = runState;       // to update seq
1419 >                    if (ws == workQueues && ws[k] == null) {
1420 >                        ws[k] = nq;
1421 >                        runState = ((rs & SHUTDOWN) | ((rs + 2) & ~SHUTDOWN));
1422                      }
1423                  } finally {
1424                      lock.unlock();
1425                  }
1426              }
1427 +            else if (q.trySharedPush(task)) {
1428 +                signalWork();
1429 +                return;
1430 +            }
1431 +            else if (m > 1) {                // move to a different index
1432 +                r ^= r << 13;                // same xorshift as WorkQueues
1433 +                r ^= r >>> 17;
1434 +                s.seed = r ^= r << 5;
1435 +            }
1436 +            else
1437 +                Thread.yield();              // yield if no alternatives
1438          }
1283        return q;
1439      }
1440  
1441      // Maintaining ctl counts
# Line 1294 | Line 1449 | public class ForkJoinPool extends Abstra
1449      }
1450  
1451      /**
1452 <     * Activates or creates a worker.
1452 >     * Tries to activate or create a worker if too few are active.
1453       */
1454      final void signalWork() {
1455 <        /*
1456 <         * The while condition is true if: (there is are too few total
1457 <         * workers OR there is at least one waiter) AND (there are too
1458 <         * few active workers OR the pool is terminating).  The value
1459 <         * of e distinguishes the remaining cases: zero (no waiters)
1460 <         * for create, negative if terminating (in which case do
1461 <         * nothing), else release a waiter. The secondary checks for
1462 <         * release (non-null array etc) can fail if the pool begins
1463 <         * terminating after the test, and don't impose any added cost
1464 <         * because JVMs must perform null and bounds checks anyway.
1465 <         */
1466 <        long c; int e, u;
1467 <        while ((((e = (int)(c = ctl)) | (u = (int)(c >>> 32))) &
1468 <                (INT_SIGN|SHORT_SIGN)) == (INT_SIGN|SHORT_SIGN)) {
1314 <            WorkQueue[] ws = workQueues; int i; WorkQueue w; Thread p;
1315 <            if (e == 0) {                    // add a new worker
1316 <                if (U.compareAndSwapLong
1317 <                    (this, CTL, c, (long)(((u + UTC_UNIT) & UTC_MASK) |
1318 <                                          ((u + UAC_UNIT) & UAC_MASK)) << 32)) {
1319 <                    addWorker();
1320 <                    break;
1455 >        long c; int u;
1456 >        while ((u = (int)((c = ctl) >>> 32)) < 0) {     // too few active
1457 >            WorkQueue[] ws = workQueues; int e, i; WorkQueue w; Thread p;
1458 >            if ((e = (int)c) > 0) {                     // at least one waiting
1459 >                if (ws != null && (i = e & SMASK) < ws.length &&
1460 >                    (w = ws[i]) != null && w.eventCount == (e | INT_SIGN)) {
1461 >                    long nc = (((long)(w.nextWait & E_MASK)) |
1462 >                               ((long)(u + UAC_UNIT) << 32));
1463 >                    if (U.compareAndSwapLong(this, CTL, c, nc)) {
1464 >                        w.eventCount = (e + E_SEQ) & E_MASK;
1465 >                        if ((p = w.parker) != null)
1466 >                            U.unpark(p);                // activate and release
1467 >                        break;
1468 >                    }
1469                  }
1470 +                else
1471 +                    break;
1472              }
1473 <            else if (e > 0 && ws != null &&
1474 <                     (i = ((~e << 1) | 1) & SMASK) < ws.length &&
1475 <                     (w = ws[i]) != null &&
1476 <                     w.eventCount == (e | INT_SIGN)) {
1477 <                if (U.compareAndSwapLong
1328 <                    (this, CTL, c, (((long)(w.nextWait & E_MASK)) |
1329 <                                    ((long)(u + UAC_UNIT) << 32)))) {
1330 <                    w.eventCount = (e + E_SEQ) & E_MASK;
1331 <                    if ((p = w.parker) != null)
1332 <                        U.unpark(p);         // release a waiting worker
1473 >            else if (e == 0 && (u & SHORT_SIGN) != 0) { // too few total
1474 >                long nc = (long)(((u + UTC_UNIT) & UTC_MASK) |
1475 >                                 ((u + UAC_UNIT) & UAC_MASK)) << 32;
1476 >                if (U.compareAndSwapLong(this, CTL, c, nc)) {
1477 >                    addWorker();
1478                      break;
1479                  }
1480              }
# Line 1338 | Line 1483 | public class ForkJoinPool extends Abstra
1483          }
1484      }
1485  
1341    /**
1342     * Tries to decrement active count (sometimes implicitly) and
1343     * possibly release or create a compensating worker in preparation
1344     * for blocking. Fails on contention or termination.
1345     *
1346     * @return true if the caller can block, else should recheck and retry
1347     */
1348    final boolean tryCompensate() {
1349        WorkQueue[] ws; WorkQueue w; Thread p;
1350        int pc = parallelism, e, u, ac, tc, i;
1351        long c = ctl;
1352
1353        if ((e = (int)c) >= 0) {
1354            if ((ac = ((u = (int)(c >>> 32)) >> UAC_SHIFT)) <= 0 &&
1355                e != 0 && (ws = workQueues) != null &&
1356                (i = ((~e << 1) | 1) & SMASK) < ws.length &&
1357                (w = ws[i]) != null) {
1358                if (w.eventCount == (e | INT_SIGN) &&
1359                    U.compareAndSwapLong
1360                    (this, CTL, c, ((long)(w.nextWait & E_MASK) |
1361                                    (c & (AC_MASK|TC_MASK))))) {
1362                    w.eventCount = (e + E_SEQ) & E_MASK;
1363                    if ((p = w.parker) != null)
1364                        U.unpark(p);
1365                    return true;             // release an idle worker
1366                }
1367            }
1368            else if ((tc = (short)(u >>> UTC_SHIFT)) >= 0 && ac + pc > 1) {
1369                long nc = ((c - AC_UNIT) & AC_MASK) | (c & ~AC_MASK);
1370                if (U.compareAndSwapLong(this, CTL, c, nc))
1371                    return true;             // no compensation needed
1372            }
1373            else if (tc + pc < MAX_ID) {
1374                long nc = ((c + TC_UNIT) & TC_MASK) | (c & ~TC_MASK);
1375                if (U.compareAndSwapLong(this, CTL, c, nc)) {
1376                    addWorker();
1377                    return true;             // create replacement
1378                }
1379            }
1380        }
1381        return false;
1382    }
1486  
1487 <    // Submissions
1487 >    // Scanning for tasks
1488  
1489      /**
1490 <     * Unless shutting down, adds the given task to a submission queue
1388 <     * at submitter's current queue index. If no queue exists at the
1389 <     * index, one is created unless pool lock is busy.  If the queue
1390 <     * and/or lock are busy, another index is randomly chosen.
1490 >     * Top-level runloop for workers, called by ForkJoinWorkerThread.run.
1491       */
1492 <    private void doSubmit(ForkJoinTask<?> task) {
1493 <        if (task == null)
1494 <            throw new NullPointerException();
1395 <        Submitter s = submitters.get();
1396 <        for (int r = s.seed;;) {
1397 <            WorkQueue q; int k;
1398 <            int rs = runState, m = rs & SMASK;
1399 <            WorkQueue[] ws = workQueues;
1400 <            if (rs < 0 || ws == null)   // shutting down
1401 <                throw new RejectedExecutionException();
1402 <            if (ws.length > m &&        // k must be at index
1403 <                ((q = ws[k = (r << 1) & m]) != null ||
1404 <                 (q = tryAddSharedQueue(k)) != null) &&
1405 <                q.trySharedPush(task)) {
1406 <                signalWork();
1407 <                return;
1408 <            }
1409 <            r ^= r << 13;               // xorshift seed to new position
1410 <            r ^= r >>> 17;
1411 <            if (((s.seed = r ^= r << 5) & m) == 0)
1412 <                Thread.yield();         // occasionally yield if busy
1413 <        }
1492 >    final void runWorker(WorkQueue w) {
1493 >        w.growArray(false);         // initialize queue array in this thread
1494 >        do {} while (w.runTask(scan(w)));
1495      }
1496  
1416
1417    // Scanning for tasks
1418
1497      /**
1498       * Scans for and, if found, returns one task, else possibly
1499       * inactivates the worker. This method operates on single reads of
1500 <     * volatile state and is designed to be re-invoked continuously in
1501 <     * part because it returns upon detecting inconsistencies,
1500 >     * volatile state and is designed to be re-invoked continuously,
1501 >     * in part because it returns upon detecting inconsistencies,
1502       * contention, or state changes that indicate possible success on
1503       * re-invocation.
1504       *
1505 <     * The scan searches for tasks across queues, randomly selecting
1506 <     * the first #queues probes, favoring steals 2:1 over submissions
1507 <     * (by exploiting even/odd indexing), and then performing a
1508 <     * circular sweep of all queues.  The scan terminates upon either
1509 <     * finding a non-empty queue, or completing a full sweep. If the
1510 <     * worker is not inactivated, it takes and returns a task from
1511 <     * this queue.  On failure to find a task, we take one of the
1512 <     * following actions, after which the caller will retry calling
1513 <     * this method unless terminated.
1505 >     * The scan searches for tasks across a random permutation of
1506 >     * queues (starting at a random index and stepping by a random
1507 >     * relative prime, checking each at least once).  The scan
1508 >     * terminates upon either finding a non-empty queue, or completing
1509 >     * the sweep. If the worker is not inactivated, it takes and
1510 >     * returns a task from this queue.  On failure to find a task, we
1511 >     * take one of the following actions, after which the caller will
1512 >     * retry calling this method unless terminated.
1513 >     *
1514 >     * * If pool is terminating, terminate the worker.
1515       *
1516       * * If not a complete sweep, try to release a waiting worker.  If
1517       * the scan terminated because the worker is inactivated, then the
# Line 1441 | Line 1520 | public class ForkJoinPool extends Abstra
1520       * another worker, but with same net effect. Releasing in other
1521       * cases as well ensures that we have enough workers running.
1522       *
1444     * * If the caller has run a task since the the last empty scan,
1445     * return (to allow rescan) if other workers are not also yet
1446     * enqueued.  Field WorkQueue.rescans counts down on each scan to
1447     * ensure eventual inactivation, and occasional calls to
1448     * Thread.yield to help avoid interference with more useful
1449     * activities on the system.
1450     *
1451     * * If pool is terminating, terminate the worker.
1452     *
1523       * * If not already enqueued, try to inactivate and enqueue the
1524 <     * worker on wait queue.
1524 >     * worker on wait queue. Or, if inactivating has caused the pool
1525 >     * to be quiescent, relay to idleAwaitWork to check for
1526 >     * termination and possibly shrink pool.
1527 >     *
1528 >     * * If already inactive, and the caller has run a task since the
1529 >     * last empty scan, return (to allow rescan) unless others are
1530 >     * also inactivated.  Field WorkQueue.rescans counts down on each
1531 >     * scan to ensure eventual inactivation and blocking.
1532       *
1533 <     * * If already enqueued and none of the above apply, either park
1534 <     * awaiting signal, or if this is the most recent waiter and pool
1458 <     * is quiescent, relay to idleAwaitWork to check for termination
1459 <     * and possibly shrink pool.
1533 >     * * If already enqueued and none of the above apply, park
1534 >     * awaiting signal,
1535       *
1536       * @param w the worker (via its WorkQueue)
1537       * @return a task or null of none found
1538       */
1539      private final ForkJoinTask<?> scan(WorkQueue w) {
1540 <        boolean swept = false;                 // true after full empty scan
1541 <        WorkQueue[] ws;                        // volatile read order matters
1542 <        int r = w.seed, ec = w.eventCount;     // ec is negative if inactive
1543 <        int rs = runState, m = rs & SMASK;
1544 <        if ((ws = workQueues) != null && ws.length > m) {
1545 <            ForkJoinTask<?> task = null;
1546 <            for (int k = 0, j = -2 - m; ; ++j) {
1547 <                WorkQueue q; int b;
1548 <                if (j < 0) {                   // random probes while j negative
1549 <                    r ^= r << 13; r ^= r >>> 17; k = (r ^= r << 5) | (j & 1);
1550 <                }                              // worker (not submit) for odd j
1551 <                else                           // cyclic scan when j >= 0
1552 <                    k += (m >>> 1) | 1;        // step by half to reduce bias
1553 <
1554 <                if ((q = ws[k & m]) != null && (b = q.base) - q.top < 0) {
1555 <                    if (ec >= 0)
1556 <                        task = q.pollAt(b);    // steal
1557 <                    break;
1540 >        WorkQueue[] ws;                       // first update random seed
1541 >        int r = w.seed; r ^= r << 13; r ^= r >>> 17; w.seed = r ^= r << 5;
1542 >        int rs = runState, m;                 // volatile read order matters
1543 >        if ((ws = workQueues) != null && (m = ws.length - 1) > 0) {
1544 >            int ec = w.eventCount;            // ec is negative if inactive
1545 >            int step = (r >>> 16) | 1;        // relative prime
1546 >            for (int j = (m + 1) << 2; ; r += step) {
1547 >                WorkQueue q; ForkJoinTask<?> t; ForkJoinTask<?>[] a; int b;
1548 >                if ((q = ws[r & m]) != null && (b = q.base) - q.top < 0 &&
1549 >                    (a = q.array) != null) {  // probably nonempty
1550 >                    int i = (((a.length - 1) & b) << ASHIFT) + ABASE;
1551 >                    t = (ForkJoinTask<?>)U.getObjectVolatile(a, i);
1552 >                    if (q.base == b && ec >= 0 && t != null &&
1553 >                        U.compareAndSwapObject(a, i, t, null)) {
1554 >                        q.base = b + 1;       // specialization of pollAt
1555 >                        return t;
1556 >                    }
1557 >                    else if ((t != null || b + 1 != q.top) &&
1558 >                             (ec < 0 || j <= m)) {
1559 >                        rs = 0;               // mark scan as imcomplete
1560 >                        break;                // caller can retry after release
1561 >                    }
1562                  }
1563 <                else if (j > m) {
1485 <                    if (rs == runState)        // staleness check
1486 <                        swept = true;
1563 >                if (--j < 0)
1564                      break;
1565 +            }
1566 +            long c = ctl; int e = (int)c, a = (int)(c >> AC_SHIFT), nr, ns;
1567 +            if (e < 0)                        // decode ctl on empty scan
1568 +                w.runState = -1;              // pool is terminating
1569 +            else if (rs == 0 || rs != runState) { // incomplete scan
1570 +                WorkQueue v; Thread p;        // try to release a waiter
1571 +                if (e > 0 && a < 0 && w.eventCount == ec &&
1572 +                    (v = ws[e & m]) != null && v.eventCount == (e | INT_SIGN)) {
1573 +                    long nc = ((long)(v.nextWait & E_MASK) |
1574 +                               ((c + AC_UNIT) & (AC_MASK|TC_MASK)));
1575 +                    if (ctl == c && U.compareAndSwapLong(this, CTL, c, nc)) {
1576 +                        v.eventCount = (e + E_SEQ) & E_MASK;
1577 +                        if ((p = v.parker) != null)
1578 +                            U.unpark(p);
1579 +                    }
1580                  }
1581              }
1582 <            w.seed = r;                        // save seed for next scan
1583 <            if (task != null)
1584 <                return task;
1585 <        }
1586 <
1587 <        // Decode ctl on empty scan
1588 <        long c = ctl; int e = (int)c, a = (int)(c >> AC_SHIFT), nr, ns;
1589 <        if (!swept) {                          // try to release a waiter
1590 <            WorkQueue v; Thread p;
1591 <            if (e > 0 && a < 0 && ws != null &&
1592 <                (v = ws[((~e << 1) | 1) & m]) != null &&
1593 <                v.eventCount == (e | INT_SIGN) && U.compareAndSwapLong
1594 <                (this, CTL, c, ((long)(v.nextWait & E_MASK) |
1595 <                                ((c + AC_UNIT) & (AC_MASK|TC_MASK))))) {
1596 <                v.eventCount = (e + E_SEQ) & E_MASK;
1597 <                if ((p = v.parker) != null)
1598 <                    U.unpark(p);
1599 <            }
1600 <        }
1601 <        else if ((nr = w.rescans) > 0) {       // continue rescanning
1602 <            int ac = a + parallelism;
1603 <            if ((w.rescans = (ac < nr) ? ac : nr - 1) > 0 && w.seed < 0 &&
1604 <                w.eventCount == ec)
1605 <                Thread.yield();                // 1 bit randomness for yield call
1606 <        }
1607 <        else if (e < 0)                        // pool is terminating
1608 <            w.runState = -1;
1609 <        else if (ec >= 0) {                    // try to enqueue
1610 <            long nc = (long)ec | ((c - AC_UNIT) & (AC_MASK|TC_MASK));
1611 <            w.nextWait = e;
1612 <            w.eventCount = ec | INT_SIGN;      // mark as inactive
1613 <            if (!U.compareAndSwapLong(this, CTL, c, nc))
1522 <                w.eventCount = ec;             // back out on CAS failure
1523 <            else if ((ns = w.nsteals) != 0) {  // set rescans if ran task
1524 <                if (a <= 0)                    // ... unless too many active
1525 <                    w.rescans = a + parallelism;
1526 <                w.nsteals = 0;
1527 <                w.totalSteals += ns;
1528 <            }
1529 <        }
1530 <        else{                                  // already queued
1531 <            if (parallelism == -a)
1532 <                idleAwaitWork(w);              // quiescent
1533 <            if (w.eventCount == ec) {
1534 <                Thread.interrupted();          // clear status
1535 <                ForkJoinWorkerThread wt = w.owner;
1536 <                U.putObject(wt, PARKBLOCKER, this);
1537 <                w.parker = wt;                 // emulate LockSupport.park
1538 <                if (w.eventCount == ec)        // recheck
1539 <                    U.park(false, 0L);         // block
1540 <                w.parker = null;
1541 <                U.putObject(wt, PARKBLOCKER, null);
1582 >            else if (ec >= 0) {               // try to enqueue/inactivate
1583 >                long nc = (long)ec | ((c - AC_UNIT) & (AC_MASK|TC_MASK));
1584 >                w.nextWait = e;
1585 >                w.eventCount = ec | INT_SIGN; // mark as inactive
1586 >                if (ctl != c || !U.compareAndSwapLong(this, CTL, c, nc))
1587 >                    w.eventCount = ec;        // unmark on CAS failure
1588 >                else {
1589 >                    if ((ns = w.nsteals) != 0) {
1590 >                        w.nsteals = 0;        // set rescans if ran task
1591 >                        w.rescans = (a > 0)? 0 : a + parallelism;
1592 >                        w.totalSteals += ns;
1593 >                    }
1594 >                    if (a == 1 - parallelism) // quiescent
1595 >                        idleAwaitWork(w, nc, c);
1596 >                }
1597 >            }
1598 >            else if (w.eventCount < 0) {      // already queued
1599 >                if ((nr = w.rescans) > 0) {   // continue rescanning
1600 >                    int ac = a + parallelism;
1601 >                    if (((w.rescans = (ac < nr) ? ac : nr - 1) & 3) == 0)
1602 >                        Thread.yield();       // yield before block
1603 >                }
1604 >                else {
1605 >                    Thread.interrupted();     // clear status
1606 >                    Thread wt = Thread.currentThread();
1607 >                    U.putObject(wt, PARKBLOCKER, this);
1608 >                    w.parker = wt;            // emulate LockSupport.park
1609 >                    if (w.eventCount < 0)     // recheck
1610 >                        U.park(false, 0L);
1611 >                    w.parker = null;
1612 >                    U.putObject(wt, PARKBLOCKER, null);
1613 >                }
1614              }
1615          }
1616          return null;
1617      }
1618  
1619      /**
1620 <     * If inactivating worker w has caused pool to become quiescent,
1621 <     * checks for pool termination, and, so long as this is not the
1622 <     * only worker, waits for event for up to SHRINK_RATE nanosecs.
1623 <     * On timeout, if ctl has not changed, terminates the worker,
1624 <     * which will in turn wake up another worker to possibly repeat
1625 <     * this process.
1620 >     * If inactivating worker w has caused the pool to become
1621 >     * quiescent, checks for pool termination, and, so long as this is
1622 >     * not the only worker, waits for event for up to SHRINK_RATE
1623 >     * nanosecs.  On timeout, if ctl has not changed, terminates the
1624 >     * worker, which will in turn wake up another worker to possibly
1625 >     * repeat this process.
1626       *
1627       * @param w the calling worker
1628 +     * @param currentCtl the ctl value triggering possible quiescence
1629 +     * @param prevCtl the ctl value to restore if thread is terminated
1630       */
1631 <    private void idleAwaitWork(WorkQueue w) {
1632 <        long c; int nw, ec;
1633 <        if (!tryTerminate(false) &&
1634 <            (int)((c = ctl) >> AC_SHIFT) + parallelism == 0 &&
1635 <            (ec = w.eventCount) == ((int)c | INT_SIGN) &&
1636 <            (nw = w.nextWait) != 0) {
1563 <            long nc = ((long)(nw & E_MASK) | // ctl to restore on timeout
1564 <                       ((c + AC_UNIT) & AC_MASK) | (c & TC_MASK));
1565 <            ForkJoinTask.helpExpungeStaleExceptions(); // help clean
1566 <            ForkJoinWorkerThread wt = w.owner;
1567 <            while (ctl == c) {
1631 >    private void idleAwaitWork(WorkQueue w, long currentCtl, long prevCtl) {
1632 >        if (w.eventCount < 0 && !tryTerminate(false, false) &&
1633 >            (int)prevCtl != 0 && ctl == currentCtl) {
1634 >            Thread wt = Thread.currentThread();
1635 >            Thread.yield();            // yield before block
1636 >            while (ctl == currentCtl) {
1637                  long startTime = System.nanoTime();
1638                  Thread.interrupted();  // timed variant of version in scan()
1639                  U.putObject(wt, PARKBLOCKER, this);
1640                  w.parker = wt;
1641 <                if (ctl == c)
1641 >                if (ctl == currentCtl)
1642                      U.park(false, SHRINK_RATE);
1643                  w.parker = null;
1644                  U.putObject(wt, PARKBLOCKER, null);
1645 <                if (ctl != c)
1645 >                if (ctl != currentCtl)
1646                      break;
1647                  if (System.nanoTime() - startTime >= SHRINK_TIMEOUT &&
1648 <                    U.compareAndSwapLong(this, CTL, c, nc)) {
1649 <                    w.runState = -1;          // shrink
1650 <                    w.eventCount = (ec + E_SEQ) | E_MASK;
1648 >                    U.compareAndSwapLong(this, CTL, currentCtl, prevCtl)) {
1649 >                    w.eventCount = (w.eventCount + E_SEQ) | E_MASK;
1650 >                    w.runState = -1;   // shrink
1651                      break;
1652                  }
1653              }
# Line 1596 | Line 1665 | public class ForkJoinPool extends Abstra
1665       * leaves hints in workers to speed up subsequent calls. The
1666       * implementation is very branchy to cope with potential
1667       * inconsistencies or loops encountering chains that are stale,
1668 <     * unknown, or of length greater than MAX_HELP_DEPTH links.  All
1669 <     * of these cases are dealt with by just retrying by caller.
1668 >     * unknown, or so long that they are likely cyclic.  All of these
1669 >     * cases are dealt with by just retrying by caller.
1670       *
1671       * @param joiner the joining worker
1672       * @param task the task to join
1673       * @return true if found or ran a task (and so is immediately retryable)
1674       */
1675 <    final boolean tryHelpStealer(WorkQueue joiner, ForkJoinTask<?> task) {
1676 <        ForkJoinTask<?> subtask;    // current target
1675 >    private boolean tryHelpStealer(WorkQueue joiner, ForkJoinTask<?> task) {
1676 >        WorkQueue[] ws;
1677 >        int m, depth = MAX_HELP;                // remaining chain depth
1678          boolean progress = false;
1679 <        int depth = 0;              // current chain depth
1680 <        int m = runState & SMASK;
1681 <        WorkQueue[] ws = workQueues;
1682 <
1683 <        if (ws != null && ws.length > m && (subtask = task).status >= 0) {
1684 <            outer:for (WorkQueue j = joiner;;) {
1615 <                // Try to find the stealer of subtask, by first using hint
1616 <                WorkQueue stealer = null;
1617 <                WorkQueue v = ws[j.stealHint & m];
1679 >        if ((ws = workQueues) != null && (m = ws.length - 1) > 0 &&
1680 >            task.status >= 0) {
1681 >            ForkJoinTask<?> subtask = task;     // current target
1682 >            outer: for (WorkQueue j = joiner;;) {
1683 >                WorkQueue stealer = null;       // find stealer of subtask
1684 >                WorkQueue v = ws[j.stealHint & m]; // try hint
1685                  if (v != null && v.currentSteal == subtask)
1686                      stealer = v;
1687 <                else {
1687 >                else {                          // scan
1688                      for (int i = 1; i <= m; i += 2) {
1689 <                        if ((v = ws[i]) != null && v.currentSteal == subtask) {
1689 >                        if ((v = ws[i]) != null && v.currentSteal == subtask &&
1690 >                            v != joiner) {
1691                              stealer = v;
1692 <                            j.stealHint = i; // save hint
1692 >                            j.stealHint = i;    // save hint
1693                              break;
1694                          }
1695                      }
# Line 1629 | Line 1697 | public class ForkJoinPool extends Abstra
1697                          break;
1698                  }
1699  
1700 <                for (WorkQueue q = stealer;;) { // Try to help stealer
1701 <                    ForkJoinTask<?> t; int b;
1700 >                for (WorkQueue q = stealer;;) { // try to help stealer
1701 >                    ForkJoinTask[] a; ForkJoinTask<?> t; int b;
1702                      if (task.status < 0)
1703                          break outer;
1704 <                    if ((b = q.base) - q.top < 0) {
1704 >                    if ((b = q.base) - q.top < 0 && (a = q.array) != null) {
1705                          progress = true;
1706 <                        if (subtask.status < 0)
1707 <                            break outer;               // stale
1708 <                        if ((t = q.pollAt(b)) != null) {
1709 <                            stealer.stealHint = joiner.poolIndex;
1706 >                        int i = (((a.length - 1) & b) << ASHIFT) + ABASE;
1707 >                        t = (ForkJoinTask<?>)U.getObjectVolatile(a, i);
1708 >                        if (subtask.status < 0) // must recheck before taking
1709 >                            break outer;
1710 >                        if (t != null &&
1711 >                            q.base == b &&
1712 >                            U.compareAndSwapObject(a, i, t, null)) {
1713 >                            q.base = b + 1;
1714                              joiner.runSubtask(t);
1715                          }
1716 +                        else if (q.base == b)
1717 +                            break outer;        // possibly stalled
1718                      }
1719 <                    else { // empty - try to descend to find stealer's stealer
1719 >                    else {                      // descend
1720                          ForkJoinTask<?> next = stealer.currentJoin;
1721 <                        if (++depth == MAX_HELP_DEPTH || subtask.status < 0 ||
1721 >                        if (--depth <= 0 || subtask.status < 0 ||
1722                              next == null || next == subtask)
1723 <                            break outer;  // max depth, stale, dead-end, cyclic
1723 >                            break outer;        // stale, dead-end, or cyclic
1724                          subtask = next;
1725                          j = stealer;
1726                          break;
# Line 1663 | Line 1737 | public class ForkJoinPool extends Abstra
1737       * @param joiner the joining worker
1738       * @param task the task
1739       */
1740 <    final void tryPollForAndExec(WorkQueue joiner, ForkJoinTask<?> task) {
1740 >    private void tryPollForAndExec(WorkQueue joiner, ForkJoinTask<?> task) {
1741          WorkQueue[] ws;
1742 <        int m = runState & SMASK;
1743 <        if ((ws = workQueues) != null && ws.length > m) {
1670 <            for (int j = 1; j <= m && task.status >= 0; j += 2) {
1742 >        if ((ws = workQueues) != null) {
1743 >            for (int j = 1; j < ws.length && task.status >= 0; j += 2) {
1744                  WorkQueue q = ws[j];
1745                  if (q != null && q.pollFor(task)) {
1746                      joiner.runSubtask(task);
# Line 1678 | Line 1751 | public class ForkJoinPool extends Abstra
1751      }
1752  
1753      /**
1754 <     * Returns a non-empty steal queue, if one is found during a random,
1755 <     * then cyclic scan, else null.  This method must be retried by
1756 <     * caller if, by the time it tries to use the queue, it is empty.
1754 >     * Tries to decrement active count (sometimes implicitly) and
1755 >     * possibly release or create a compensating worker in preparation
1756 >     * for blocking. Fails on contention or termination. Otherwise,
1757 >     * adds a new thread if no idle workers are available and either
1758 >     * pool would become completely starved or: (at least half
1759 >     * starved, and fewer than 50% spares exist, and there is at least
1760 >     * one task apparently available). Even though the availablity
1761 >     * check requires a full scan, it is worthwhile in reducing false
1762 >     * alarms.
1763 >     *
1764 >     * @param task if nonnull, a task being waited for
1765 >     * @param blocker if nonnull, a blocker being waited for
1766 >     * @return true if the caller can block, else should recheck and retry
1767 >     */
1768 >    final boolean tryCompensate(ForkJoinTask<?> task, ManagedBlocker blocker) {
1769 >        int pc = parallelism, e;
1770 >        long c = ctl;
1771 >        WorkQueue[] ws = workQueues;
1772 >        if ((e = (int)c) >= 0 && ws != null) {
1773 >            int u, a, ac, hc;
1774 >            int tc = (short)((u = (int)(c >>> 32)) >>> UTC_SHIFT) + pc;
1775 >            boolean replace = false;
1776 >            if ((a = u >> UAC_SHIFT) <= 0) {
1777 >                if ((ac = a + pc) <= 1)
1778 >                    replace = true;
1779 >                else if ((e > 0 || (task != null &&
1780 >                                    ac <= (hc = pc >>> 1) && tc < pc + hc))) {
1781 >                    WorkQueue w;
1782 >                    for (int j = 0; j < ws.length; ++j) {
1783 >                        if ((w = ws[j]) != null && !w.isEmpty()) {
1784 >                            replace = true;
1785 >                            break;   // in compensation range and tasks available
1786 >                        }
1787 >                    }
1788 >                }
1789 >            }
1790 >            if ((task == null || task.status >= 0) && // recheck need to block
1791 >                (blocker == null || !blocker.isReleasable()) && ctl == c) {
1792 >                if (!replace) {          // no compensation
1793 >                    long nc = ((c - AC_UNIT) & AC_MASK) | (c & ~AC_MASK);
1794 >                    if (U.compareAndSwapLong(this, CTL, c, nc))
1795 >                        return true;
1796 >                }
1797 >                else if (e != 0) {       // release an idle worker
1798 >                    WorkQueue w; Thread p; int i;
1799 >                    if ((i = e & SMASK) < ws.length && (w = ws[i]) != null) {
1800 >                        long nc = ((long)(w.nextWait & E_MASK) |
1801 >                                   (c & (AC_MASK|TC_MASK)));
1802 >                        if (w.eventCount == (e | INT_SIGN) &&
1803 >                            U.compareAndSwapLong(this, CTL, c, nc)) {
1804 >                            w.eventCount = (e + E_SEQ) & E_MASK;
1805 >                            if ((p = w.parker) != null)
1806 >                                U.unpark(p);
1807 >                            return true;
1808 >                        }
1809 >                    }
1810 >                }
1811 >                else if (tc < MAX_CAP) { // create replacement
1812 >                    long nc = ((c + TC_UNIT) & TC_MASK) | (c & ~TC_MASK);
1813 >                    if (U.compareAndSwapLong(this, CTL, c, nc)) {
1814 >                        addWorker();
1815 >                        return true;
1816 >                    }
1817 >                }
1818 >            }
1819 >        }
1820 >        return false;
1821 >    }
1822 >
1823 >    /**
1824 >     * Helps and/or blocks until the given task is done
1825 >     *
1826 >     * @param joiner the joining worker
1827 >     * @param task the task
1828 >     * @return task status on exit
1829 >     */
1830 >    final int awaitJoin(WorkQueue joiner, ForkJoinTask<?> task) {
1831 >        ForkJoinTask<?> prevJoin = joiner.currentJoin;
1832 >        joiner.currentJoin = task;
1833 >        long startTime = 0L;
1834 >        for (int k = 0, s; ; ++k) {
1835 >            if ((joiner.isEmpty() ?                  // try to help
1836 >                 !tryHelpStealer(joiner, task) :
1837 >                 !joiner.tryRemoveAndExec(task))) {
1838 >                if (k == 0) {
1839 >                    startTime = System.nanoTime();
1840 >                    tryPollForAndExec(joiner, task); // check uncommon case
1841 >                }
1842 >                else if ((k & (MAX_HELP - 1)) == 0 &&
1843 >                         System.nanoTime() - startTime >= COMPENSATION_DELAY &&
1844 >                         tryCompensate(task, null)) {
1845 >                    if (task.trySetSignal() && task.status >= 0) {
1846 >                        synchronized (task) {
1847 >                            if (task.status >= 0) {
1848 >                                try {                // see ForkJoinTask
1849 >                                    task.wait();     //  for explanation
1850 >                                } catch (InterruptedException ie) {
1851 >                                }
1852 >                            }
1853 >                            else
1854 >                                task.notifyAll();
1855 >                        }
1856 >                    }
1857 >                    long c;                          // re-activate
1858 >                    do {} while (!U.compareAndSwapLong
1859 >                                 (this, CTL, c = ctl, c + AC_UNIT));
1860 >                }
1861 >            }
1862 >            if ((s = task.status) < 0) {
1863 >                joiner.currentJoin = prevJoin;
1864 >                return s;
1865 >            }
1866 >            else if ((k & (MAX_HELP - 1)) == MAX_HELP >>> 1)
1867 >                Thread.yield();                     // for politeness
1868 >        }
1869 >    }
1870 >
1871 >    /**
1872 >     * Stripped-down variant of awaitJoin used by timed joins. Tries
1873 >     * to help join only while there is continuous progress. (Caller
1874 >     * will then enter a timed wait.)
1875 >     *
1876 >     * @param joiner the joining worker
1877 >     * @param task the task
1878 >     * @return task status on exit
1879 >     */
1880 >    final int helpJoinOnce(WorkQueue joiner, ForkJoinTask<?> task) {
1881 >        int s;
1882 >        while ((s = task.status) >= 0 &&
1883 >               (joiner.isEmpty() ?
1884 >                tryHelpStealer(joiner, task) :
1885 >                joiner.tryRemoveAndExec(task)))
1886 >            ;
1887 >        return s;
1888 >    }
1889 >
1890 >    /**
1891 >     * Returns a (probably) non-empty steal queue, if one is found
1892 >     * during a random, then cyclic scan, else null.  This method must
1893 >     * be retried by caller if, by the time it tries to use the queue,
1894 >     * it is empty.
1895       */
1896      private WorkQueue findNonEmptyStealQueue(WorkQueue w) {
1897 <        int r = w.seed;    // Same idea as scan(), but ignoring submissions
1897 >        // Similar to loop in scan(), but ignoring submissions
1898 >        int r = w.seed; r ^= r << 13; r ^= r >>> 17; w.seed = r ^= r << 5;
1899 >        int step = (r >>> 16) | 1;
1900          for (WorkQueue[] ws;;) {
1901 <            int m = runState & SMASK;
1902 <            if ((ws = workQueues) == null)
1901 >            int rs = runState, m;
1902 >            if ((ws = workQueues) == null || (m = ws.length - 1) < 1)
1903                  return null;
1904 <            if (ws.length > m) {
1905 <                WorkQueue q;
1906 <                for (int n = m << 2, k = r, j = -n;;) {
1907 <                    r ^= r << 13; r ^= r >>> 17; r ^= r << 5;
1908 <                    if ((q = ws[(k | 1) & m]) != null && q.base - q.top < 0) {
1909 <                        w.seed = r;
1697 <                        return q;
1698 <                    }
1699 <                    else if (j > n)
1904 >            for (int j = (m + 1) << 2; ; r += step) {
1905 >                WorkQueue q = ws[((r << 1) | 1) & m];
1906 >                if (q != null && !q.isEmpty())
1907 >                    return q;
1908 >                else if (--j < 0) {
1909 >                    if (runState == rs)
1910                          return null;
1911 <                    else
1702 <                        k = (j++ < 0) ? r : k + ((m >>> 1) | 1);
1703 <
1911 >                    break;
1912                  }
1913              }
1914          }
# Line 1714 | Line 1922 | public class ForkJoinPool extends Abstra
1922       */
1923      final void helpQuiescePool(WorkQueue w) {
1924          for (boolean active = true;;) {
1925 <            w.runLocalTasks();      // exhaust local queue
1925 >            if (w.base - w.top < 0)
1926 >                w.runLocalTasks();  // exhaust local queue
1927              WorkQueue q = findNonEmptyStealQueue(w);
1928              if (q != null) {
1929 <                ForkJoinTask<?> t;
1929 >                ForkJoinTask<?> t; int b;
1930                  if (!active) {      // re-establish active count
1931                      long c;
1932                      active = true;
1933                      do {} while (!U.compareAndSwapLong
1934                                   (this, CTL, c = ctl, c + AC_UNIT));
1935                  }
1936 <                if ((t = q.poll()) != null)
1936 >                if ((b = q.base) - q.top < 0 && (t = q.pollAt(b)) != null)
1937                      w.runSubtask(t);
1938              }
1939              else {
# Line 1752 | Line 1961 | public class ForkJoinPool extends Abstra
1961       */
1962      final ForkJoinTask<?> nextTaskFor(WorkQueue w) {
1963          for (ForkJoinTask<?> t;;) {
1964 <            WorkQueue q;
1964 >            WorkQueue q; int b;
1965              if ((t = w.nextLocalTask()) != null)
1966                  return t;
1967              if ((q = findNonEmptyStealQueue(w)) == null)
1968                  return null;
1969 <            if ((t = q.poll()) != null)
1969 >            if ((b = q.base) - q.top < 0 && (t = q.pollAt(b)) != null)
1970                  return t;
1971          }
1972      }
# Line 1778 | Line 1987 | public class ForkJoinPool extends Abstra
1987                  8);
1988      }
1989  
1990 <    // Termination
1990 >    //  Termination
1991  
1992      /**
1993 <     * Sets SHUTDOWN bit of runState under lock
1994 <     */
1995 <    private void enableShutdown() {
1996 <        ReentrantLock lock = this.lock;
1997 <        if (runState >= 0) {
1998 <            lock.lock();                       // don't need try/finally
1999 <            runState |= SHUTDOWN;
1791 <            lock.unlock();
1792 <        }
1793 <    }
1794 <
1795 <    /**
1796 <     * Possibly initiates and/or completes termination.  Upon
1797 <     * termination, cancels all queued tasks and then
1993 >     * Possibly initiates and/or completes termination.  The caller
1994 >     * triggering termination runs three passes through workQueues:
1995 >     * (0) Setting termination status, followed by wakeups of queued
1996 >     * workers; (1) cancelling all tasks; (2) interrupting lagging
1997 >     * threads (likely in external tasks, but possibly also blocked in
1998 >     * joins).  Each pass repeats previous steps because of potential
1999 >     * lagging thread creation.
2000       *
2001       * @param now if true, unconditionally terminate, else only
2002       * if no work and no active workers
2003 +     * @param enable if true, enable shutdown when next possible
2004       * @return true if now terminating or terminated
2005       */
2006 <    private boolean tryTerminate(boolean now) {
2006 >    private boolean tryTerminate(boolean now, boolean enable) {
2007 >        Mutex lock = this.lock;
2008          for (long c;;) {
2009              if (((c = ctl) & STOP_BIT) != 0) {      // already terminating
2010                  if ((short)(c >>> TC_SHIFT) == -parallelism) {
1807                    ReentrantLock lock = this.lock; // signal when no workers
2011                      lock.lock();                    // don't need try/finally
2012                      termination.signalAll();        // signal when 0 workers
2013                      lock.unlock();
2014                  }
2015                  return true;
2016              }
2017 <            if (!now) {
2018 <                if ((int)(c >> AC_SHIFT) != -parallelism || runState >= 0 ||
2017 >            if (runState >= 0) {                    // not yet enabled
2018 >                if (!enable)
2019 >                    return false;
2020 >                lock.lock();
2021 >                runState |= SHUTDOWN;
2022 >                lock.unlock();
2023 >            }
2024 >            if (!now) {                             // check if idle & no tasks
2025 >                if ((int)(c >> AC_SHIFT) != -parallelism ||
2026                      hasQueuedSubmissions())
2027                      return false;
2028                  // Check for unqueued inactive workers. One pass suffices.
2029                  WorkQueue[] ws = workQueues; WorkQueue w;
2030                  if (ws != null) {
2031 <                    int n = ws.length;
1822 <                    for (int i = 1; i < n; i += 2) {
2031 >                    for (int i = 1; i < ws.length; i += 2) {
2032                          if ((w = ws[i]) != null && w.eventCount >= 0)
2033                              return false;
2034                      }
2035                  }
2036              }
2037 <            if (U.compareAndSwapLong(this, CTL, c, c | STOP_BIT))
2038 <                startTerminating();
2039 <        }
2040 <    }
2041 <
2042 <    /**
2043 <     * Initiates termination: Runs three passes through workQueues:
2044 <     * (0) Setting termination status, followed by wakeups of queued
2045 <     * workers; (1) cancelling all tasks; (2) interrupting lagging
2046 <     * threads (likely in external tasks, but possibly also blocked in
2047 <     * joins).  Each pass repeats previous steps because of potential
2048 <     * lagging thread creation.
2049 <     */
1841 <    private void startTerminating() {
1842 <        for (int pass = 0; pass < 3; ++pass) {
1843 <            WorkQueue[] ws = workQueues;
1844 <            if (ws != null) {
1845 <                WorkQueue w; Thread wt;
1846 <                int n = ws.length;
1847 <                for (int j = 0; j < n; ++j) {
1848 <                    if ((w = ws[j]) != null) {
1849 <                        w.runState = -1;
1850 <                        if (pass > 0) {
1851 <                            w.cancelAll();
1852 <                            if (pass > 1 && (wt = w.owner) != null &&
1853 <                                !wt.isInterrupted()) {
1854 <                                try {
1855 <                                    wt.interrupt();
1856 <                                } catch (SecurityException ignore) {
2037 >            if (U.compareAndSwapLong(this, CTL, c, c | STOP_BIT)) {
2038 >                for (int pass = 0; pass < 3; ++pass) {
2039 >                    WorkQueue[] ws = workQueues;
2040 >                    if (ws != null) {
2041 >                        WorkQueue w;
2042 >                        int n = ws.length;
2043 >                        for (int i = 0; i < n; ++i) {
2044 >                            if ((w = ws[i]) != null) {
2045 >                                w.runState = -1;
2046 >                                if (pass > 0) {
2047 >                                    w.cancelAll();
2048 >                                    if (pass > 1)
2049 >                                        w.interruptOwner();
2050                                  }
2051                              }
2052                          }
2053 <                    }
2054 <                }
2055 <                // Wake up workers parked on event queue
2056 <                int i, e; long c; Thread p;
2057 <                while ((i = ((~(e = (int)(c = ctl)) << 1) | 1) & SMASK) < n &&
2058 <                       (w = ws[i]) != null &&
2059 <                       w.eventCount == (e | INT_SIGN)) {
2060 <                    long nc = ((long)(w.nextWait & E_MASK) |
2061 <                               ((c + AC_UNIT) & AC_MASK) |
2062 <                               (c & (TC_MASK|STOP_BIT)));
2063 <                    if (U.compareAndSwapLong(this, CTL, c, nc)) {
2064 <                        w.eventCount = (e + E_SEQ) & E_MASK;
2065 <                        if ((p = w.parker) != null)
2066 <                            U.unpark(p);
2053 >                        // Wake up workers parked on event queue
2054 >                        int i, e; long cc; Thread p;
2055 >                        while ((e = (int)(cc = ctl) & E_MASK) != 0 &&
2056 >                               (i = e & SMASK) < n &&
2057 >                               (w = ws[i]) != null) {
2058 >                            long nc = ((long)(w.nextWait & E_MASK) |
2059 >                                       ((cc + AC_UNIT) & AC_MASK) |
2060 >                                       (cc & (TC_MASK|STOP_BIT)));
2061 >                            if (w.eventCount == (e | INT_SIGN) &&
2062 >                                U.compareAndSwapLong(this, CTL, cc, nc)) {
2063 >                                w.eventCount = (e + E_SEQ) & E_MASK;
2064 >                                w.runState = -1;
2065 >                                if ((p = w.parker) != null)
2066 >                                    U.unpark(p);
2067 >                            }
2068 >                        }
2069                      }
2070                  }
2071              }
# Line 1946 | Line 2141 | public class ForkJoinPool extends Abstra
2141          checkPermission();
2142          if (factory == null)
2143              throw new NullPointerException();
2144 <        if (parallelism <= 0 || parallelism > MAX_ID)
2144 >        if (parallelism <= 0 || parallelism > MAX_CAP)
2145              throw new IllegalArgumentException();
2146          this.parallelism = parallelism;
2147          this.factory = factory;
2148          this.ueh = handler;
2149          this.localMode = asyncMode ? FIFO_QUEUE : LIFO_QUEUE;
1955        this.nextPoolIndex = 1;
2150          long np = (long)(-parallelism); // offset ctl counts
2151          this.ctl = ((np << AC_SHIFT) & AC_MASK) | ((np << TC_SHIFT) & TC_MASK);
2152 <        // initialize workQueues array with room for 2*parallelism if possible
2153 <        int n = parallelism << 1;
2154 <        if (n >= MAX_ID)
2155 <            n = MAX_ID;
2156 <        else { // See Hackers Delight, sec 3.2, where n < (1 << 16)
2157 <            n |= n >>> 1; n |= n >>> 2; n |= n >>> 4; n |= n >>> 8;
2158 <        }
1965 <        this.workQueues = new WorkQueue[(n + 1) << 1];
1966 <        ReentrantLock lck = this.lock = new ReentrantLock();
1967 <        this.termination = lck.newCondition();
2152 >        // Use nearest power 2 for workQueues size. See Hackers Delight sec 3.2.
2153 >        int n = parallelism - 1;
2154 >        n |= n >>> 1; n |= n >>> 2; n |= n >>> 4; n |= n >>> 8; n |= n >>> 16;
2155 >        int size = (n + 1) << 1;        // #slots = 2*#workers
2156 >        this.submitMask = size - 1;     // room for max # of submit queues
2157 >        this.workQueues = new WorkQueue[size];
2158 >        this.termination = (this.lock = new Mutex()).newCondition();
2159          this.stealCount = new AtomicLong();
2160          this.nextWorkerNumber = new AtomicInteger();
2161 +        int pn = poolNumberGenerator.incrementAndGet();
2162          StringBuilder sb = new StringBuilder("ForkJoinPool-");
2163 <        sb.append(poolNumberGenerator.incrementAndGet());
2163 >        sb.append(Integer.toString(pn));
2164          sb.append("-worker-");
2165          this.workerNamePrefix = sb.toString();
2166 <        // Create initial submission queue
2167 <        WorkQueue sq = tryAddSharedQueue(0);
2168 <        if (sq != null)
1977 <            sq.growArray(false);
2166 >        lock.lock();
2167 >        this.runState = 1;              // set init flag
2168 >        lock.unlock();
2169      }
2170  
2171      // Execution methods
# Line 1996 | Line 2187 | public class ForkJoinPool extends Abstra
2187       *         scheduled for execution
2188       */
2189      public <T> T invoke(ForkJoinTask<T> task) {
2190 +        if (task == null)
2191 +            throw new NullPointerException();
2192          doSubmit(task);
2193          return task.join();
2194      }
# Line 2009 | Line 2202 | public class ForkJoinPool extends Abstra
2202       *         scheduled for execution
2203       */
2204      public void execute(ForkJoinTask<?> task) {
2205 +        if (task == null)
2206 +            throw new NullPointerException();
2207          doSubmit(task);
2208      }
2209  
# Line 2026 | Line 2221 | public class ForkJoinPool extends Abstra
2221          if (task instanceof ForkJoinTask<?>) // avoid re-wrap
2222              job = (ForkJoinTask<?>) task;
2223          else
2224 <            job = ForkJoinTask.adapt(task, null);
2224 >            job = new ForkJoinTask.AdaptedRunnableAction(task);
2225          doSubmit(job);
2226      }
2227  
# Line 2040 | Line 2235 | public class ForkJoinPool extends Abstra
2235       *         scheduled for execution
2236       */
2237      public <T> ForkJoinTask<T> submit(ForkJoinTask<T> task) {
2238 +        if (task == null)
2239 +            throw new NullPointerException();
2240          doSubmit(task);
2241          return task;
2242      }
# Line 2050 | Line 2247 | public class ForkJoinPool extends Abstra
2247       *         scheduled for execution
2248       */
2249      public <T> ForkJoinTask<T> submit(Callable<T> task) {
2250 <        if (task == null)
2054 <            throw new NullPointerException();
2055 <        ForkJoinTask<T> job = ForkJoinTask.adapt(task);
2250 >        ForkJoinTask<T> job = new ForkJoinTask.AdaptedCallable<T>(task);
2251          doSubmit(job);
2252          return job;
2253      }
# Line 2063 | Line 2258 | public class ForkJoinPool extends Abstra
2258       *         scheduled for execution
2259       */
2260      public <T> ForkJoinTask<T> submit(Runnable task, T result) {
2261 <        if (task == null)
2067 <            throw new NullPointerException();
2068 <        ForkJoinTask<T> job = ForkJoinTask.adapt(task, result);
2261 >        ForkJoinTask<T> job = new ForkJoinTask.AdaptedRunnable<T>(task, result);
2262          doSubmit(job);
2263          return job;
2264      }
# Line 2082 | Line 2275 | public class ForkJoinPool extends Abstra
2275          if (task instanceof ForkJoinTask<?>) // avoid re-wrap
2276              job = (ForkJoinTask<?>) task;
2277          else
2278 <            job = ForkJoinTask.adapt(task, null);
2278 >            job = new ForkJoinTask.AdaptedRunnableAction(task);
2279          doSubmit(job);
2280          return job;
2281      }
# Line 2092 | Line 2285 | public class ForkJoinPool extends Abstra
2285       * @throws RejectedExecutionException {@inheritDoc}
2286       */
2287      public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) {
2288 <        ArrayList<ForkJoinTask<T>> forkJoinTasks =
2289 <            new ArrayList<ForkJoinTask<T>>(tasks.size());
2290 <        for (Callable<T> task : tasks)
2291 <            forkJoinTasks.add(ForkJoinTask.adapt(task));
2292 <        invoke(new InvokeAll<T>(forkJoinTasks));
2293 <
2288 >        // In previous versions of this class, this method constructed
2289 >        // a task to run ForkJoinTask.invokeAll, but now external
2290 >        // invocation of multiple tasks is at least as efficient.
2291 >        List<ForkJoinTask<T>> fs = new ArrayList<ForkJoinTask<T>>(tasks.size());
2292 >        // Workaround needed because method wasn't declared with
2293 >        // wildcards in return type but should have been.
2294          @SuppressWarnings({"unchecked", "rawtypes"})
2295 <            List<Future<T>> futures = (List<Future<T>>) (List) forkJoinTasks;
2103 <        return futures;
2104 <    }
2295 >            List<Future<T>> futures = (List<Future<T>>) (List) fs;
2296  
2297 <    static final class InvokeAll<T> extends RecursiveAction {
2298 <        final ArrayList<ForkJoinTask<T>> tasks;
2299 <        InvokeAll(ArrayList<ForkJoinTask<T>> tasks) { this.tasks = tasks; }
2300 <        public void compute() {
2301 <            try { invokeAll(tasks); }
2302 <            catch (Exception ignore) {}
2297 >        boolean done = false;
2298 >        try {
2299 >            for (Callable<T> t : tasks) {
2300 >                ForkJoinTask<T> f = new ForkJoinTask.AdaptedCallable<T>(t);
2301 >                doSubmit(f);
2302 >                fs.add(f);
2303 >            }
2304 >            for (ForkJoinTask<T> f : fs)
2305 >                f.quietlyJoin();
2306 >            done = true;
2307 >            return futures;
2308 >        } finally {
2309 >            if (!done)
2310 >                for (ForkJoinTask<T> f : fs)
2311 >                    f.cancel(false);
2312          }
2113        private static final long serialVersionUID = -7914297376763021607L;
2313      }
2314  
2315      /**
# Line 2175 | Line 2374 | public class ForkJoinPool extends Abstra
2374          int rc = 0;
2375          WorkQueue[] ws; WorkQueue w;
2376          if ((ws = workQueues) != null) {
2377 <            int n = ws.length;
2378 <            for (int i = 1; i < n; i += 2) {
2180 <                Thread.State s; ForkJoinWorkerThread wt;
2181 <                if ((w = ws[i]) != null && (wt = w.owner) != null &&
2182 <                    w.eventCount >= 0 &&
2183 <                    (s = wt.getState()) != Thread.State.BLOCKED &&
2184 <                    s != Thread.State.WAITING &&
2185 <                    s != Thread.State.TIMED_WAITING)
2377 >            for (int i = 1; i < ws.length; i += 2) {
2378 >                if ((w = ws[i]) != null && w.isApparentlyUnblocked())
2379                      ++rc;
2380              }
2381          }
# Line 2231 | Line 2424 | public class ForkJoinPool extends Abstra
2424          long count = stealCount.get();
2425          WorkQueue[] ws; WorkQueue w;
2426          if ((ws = workQueues) != null) {
2427 <            int n = ws.length;
2235 <            for (int i = 1; i < n; i += 2) {
2427 >            for (int i = 1; i < ws.length; i += 2) {
2428                  if ((w = ws[i]) != null)
2429                      count += w.totalSteals;
2430              }
# Line 2254 | Line 2446 | public class ForkJoinPool extends Abstra
2446          long count = 0;
2447          WorkQueue[] ws; WorkQueue w;
2448          if ((ws = workQueues) != null) {
2449 <            int n = ws.length;
2258 <            for (int i = 1; i < n; i += 2) {
2449 >            for (int i = 1; i < ws.length; i += 2) {
2450                  if ((w = ws[i]) != null)
2451                      count += w.queueSize();
2452              }
# Line 2274 | Line 2465 | public class ForkJoinPool extends Abstra
2465          int count = 0;
2466          WorkQueue[] ws; WorkQueue w;
2467          if ((ws = workQueues) != null) {
2468 <            int n = ws.length;
2278 <            for (int i = 0; i < n; i += 2) {
2468 >            for (int i = 0; i < ws.length; i += 2) {
2469                  if ((w = ws[i]) != null)
2470                      count += w.queueSize();
2471              }
# Line 2292 | Line 2482 | public class ForkJoinPool extends Abstra
2482      public boolean hasQueuedSubmissions() {
2483          WorkQueue[] ws; WorkQueue w;
2484          if ((ws = workQueues) != null) {
2485 <            int n = ws.length;
2486 <            for (int i = 0; i < n; i += 2) {
2297 <                if ((w = ws[i]) != null && w.queueSize() != 0)
2485 >            for (int i = 0; i < ws.length; i += 2) {
2486 >                if ((w = ws[i]) != null && !w.isEmpty())
2487                      return true;
2488              }
2489          }
# Line 2311 | Line 2500 | public class ForkJoinPool extends Abstra
2500      protected ForkJoinTask<?> pollSubmission() {
2501          WorkQueue[] ws; WorkQueue w; ForkJoinTask<?> t;
2502          if ((ws = workQueues) != null) {
2503 <            int n = ws.length;
2315 <            for (int i = 0; i < n; i += 2) {
2503 >            for (int i = 0; i < ws.length; i += 2) {
2504                  if ((w = ws[i]) != null && (t = w.poll()) != null)
2505                      return t;
2506              }
# Line 2341 | Line 2529 | public class ForkJoinPool extends Abstra
2529          int count = 0;
2530          WorkQueue[] ws; WorkQueue w; ForkJoinTask<?> t;
2531          if ((ws = workQueues) != null) {
2532 <            int n = ws.length;
2345 <            for (int i = 0; i < n; ++i) {
2532 >            for (int i = 0; i < ws.length; ++i) {
2533                  if ((w = ws[i]) != null) {
2534                      while ((t = w.poll()) != null) {
2535                          c.add(t);
# Line 2362 | Line 2549 | public class ForkJoinPool extends Abstra
2549       * @return a string identifying this pool, as well as its state
2550       */
2551      public String toString() {
2552 <        long st = getStealCount();
2553 <        long qt = getQueuedTaskCount();
2554 <        long qs = getQueuedSubmissionCount();
2368 <        int rc = getRunningThreadCount();
2369 <        int pc = parallelism;
2552 >        // Use a single pass through workQueues to collect counts
2553 >        long qt = 0L, qs = 0L; int rc = 0;
2554 >        long st = stealCount.get();
2555          long c = ctl;
2556 +        WorkQueue[] ws; WorkQueue w;
2557 +        if ((ws = workQueues) != null) {
2558 +            for (int i = 0; i < ws.length; ++i) {
2559 +                if ((w = ws[i]) != null) {
2560 +                    int size = w.queueSize();
2561 +                    if ((i & 1) == 0)
2562 +                        qs += size;
2563 +                    else {
2564 +                        qt += size;
2565 +                        st += w.totalSteals;
2566 +                        if (w.isApparentlyUnblocked())
2567 +                            ++rc;
2568 +                    }
2569 +                }
2570 +            }
2571 +        }
2572 +        int pc = parallelism;
2573          int tc = pc + (short)(c >>> TC_SHIFT);
2574          int ac = pc + (int)(c >> AC_SHIFT);
2575          if (ac < 0) // ignore transient negative
# Line 2403 | Line 2605 | public class ForkJoinPool extends Abstra
2605       */
2606      public void shutdown() {
2607          checkPermission();
2608 <        enableShutdown();
2407 <        tryTerminate(false);
2608 >        tryTerminate(false, true);
2609      }
2610  
2611      /**
# Line 2425 | Line 2626 | public class ForkJoinPool extends Abstra
2626       */
2627      public List<Runnable> shutdownNow() {
2628          checkPermission();
2629 <        enableShutdown();
2429 <        tryTerminate(true);
2629 >        tryTerminate(true, true);
2630          return Collections.emptyList();
2631      }
2632  
# Line 2483 | Line 2683 | public class ForkJoinPool extends Abstra
2683      public boolean awaitTermination(long timeout, TimeUnit unit)
2684          throws InterruptedException {
2685          long nanos = unit.toNanos(timeout);
2686 <        final ReentrantLock lock = this.lock;
2686 >        final Mutex lock = this.lock;
2687          lock.lock();
2688          try {
2689              for (;;) {
# Line 2597 | Line 2797 | public class ForkJoinPool extends Abstra
2797          ForkJoinPool p = ((t instanceof ForkJoinWorkerThread) ?
2798                            ((ForkJoinWorkerThread)t).pool : null);
2799          while (!blocker.isReleasable()) {
2800 <            if (p == null || p.tryCompensate()) {
2800 >            if (p == null || p.tryCompensate(null, blocker)) {
2801                  try {
2802                      do {} while (!blocker.isReleasable() && !blocker.block());
2803                  } finally {
# Line 2614 | Line 2814 | public class ForkJoinPool extends Abstra
2814      // implement RunnableFuture.
2815  
2816      protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
2817 <        return (RunnableFuture<T>) ForkJoinTask.adapt(runnable, value);
2817 >        return new ForkJoinTask.AdaptedRunnable<T>(runnable, value);
2818      }
2819  
2820      protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
2821 <        return (RunnableFuture<T>) ForkJoinTask.adapt(callable);
2821 >        return new ForkJoinTask.AdaptedCallable<T>(callable);
2822      }
2823  
2824      // Unsafe mechanics
2825      private static final sun.misc.Unsafe U;
2826      private static final long CTL;
2627    private static final long RUNSTATE;
2827      private static final long PARKBLOCKER;
2828 +    private static final int ABASE;
2829 +    private static final int ASHIFT;
2830  
2831      static {
2832          poolNumberGenerator = new AtomicInteger();
2833 +        nextSubmitterSeed = new AtomicInteger(0x55555555);
2834          modifyThreadPermission = new RuntimePermission("modifyThread");
2835          defaultForkJoinWorkerThreadFactory =
2836              new DefaultForkJoinWorkerThreadFactory();
2837 +        submitters = new ThreadSubmitter();
2838          int s;
2839          try {
2840              U = getUnsafe();
2841              Class<?> k = ForkJoinPool.class;
2842 <            Class<?> tk = Thread.class;
2842 >            Class<?> ak = ForkJoinTask[].class;
2843              CTL = U.objectFieldOffset
2844                  (k.getDeclaredField("ctl"));
2845 <            RUNSTATE = U.objectFieldOffset
2643 <                (k.getDeclaredField("runState"));
2845 >            Class<?> tk = Thread.class;
2846              PARKBLOCKER = U.objectFieldOffset
2847                  (tk.getDeclaredField("parkBlocker"));
2848 +            ABASE = U.arrayBaseOffset(ak);
2849 +            s = U.arrayIndexScale(ak);
2850          } catch (Exception e) {
2851              throw new Error(e);
2852          }
2853 +        if ((s & (s-1)) != 0)
2854 +            throw new Error("data type scale not a power of two");
2855 +        ASHIFT = 31 - Integer.numberOfLeadingZeros(s);
2856      }
2857  
2858      /**

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines