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.118 by jsr166, Sat Jan 28 04:34:54 2012 UTC vs.
Revision 1.136 by dl, Mon Oct 29 17:23:34 2012 UTC

# Line 21 | Line 21 | import java.util.concurrent.RunnableFutu
21   import java.util.concurrent.TimeUnit;
22   import java.util.concurrent.atomic.AtomicInteger;
23   import java.util.concurrent.atomic.AtomicLong;
24 < import java.util.concurrent.locks.ReentrantLock;
24 > import java.util.concurrent.locks.AbstractQueuedSynchronizer;
25   import java.util.concurrent.locks.Condition;
26  
27   /**
# Line 42 | Line 42 | import java.util.concurrent.locks.Condit
42   * ForkJoinPool}s may also be appropriate for use with event-style
43   * tasks that are never joined.
44   *
45 < * <p>A {@code ForkJoinPool} is constructed with a given target
46 < * parallelism level; by default, equal to the number of available
47 < * processors. The pool attempts to maintain enough active (or
48 < * available) threads by dynamically adding, suspending, or resuming
49 < * internal worker threads, even if some tasks are stalled waiting to
50 < * join others. However, no such adjustments are guaranteed in the
51 < * face of blocked IO or other unmanaged synchronization. The nested
52 < * {@link ManagedBlocker} interface enables extension of the kinds of
45 > * <p>A static {@link #commonPool} is available and appropriate for
46 > * most applications. The common pool is used by any ForkJoinTask that
47 > * is not explicitly submitted to a specified pool. Using the common
48 > * pool normally reduces resource usage (its threads are slowly
49 > * reclaimed during periods of non-use, and reinstated upon subsequent
50 > * use).  The common pool is by default constructed with default
51 > * parameters, but these may be controlled by setting any or all of
52 > * the three properties {@code
53 > * java.util.concurrent.ForkJoinPool.common.{parallelism,
54 > * threadFactory, exceptionHandler}}.
55 > *
56 > * <p>For applications that require separate or custom pools, a {@code
57 > * ForkJoinPool} may be constructed with a given target parallelism
58 > * level; by default, equal to the number of available processors. The
59 > * pool attempts to maintain enough active (or available) threads by
60 > * dynamically adding, suspending, or resuming internal worker
61 > * threads, even if some tasks are stalled waiting to join
62 > * others. However, no such adjustments are guaranteed in the face of
63 > * blocked IO or other unmanaged synchronization. The nested {@link
64 > * ManagedBlocker} interface enables extension of the kinds of
65   * synchronization accommodated.
66   *
67   * <p>In addition to execution and lifecycle control methods, this
# Line 94 | Line 106 | import java.util.concurrent.locks.Condit
106   *  </tr>
107   * </table>
108   *
97 * <p><b>Sample Usage.</b> Normally a single {@code ForkJoinPool} is
98 * used for all parallel task execution in a program or subsystem.
99 * Otherwise, use would not usually outweigh the construction and
100 * bookkeeping overhead of creating a large set of threads. For
101 * example, a common pool could be used for the {@code SortTasks}
102 * illustrated in {@link RecursiveAction}. Because {@code
103 * ForkJoinPool} uses threads in {@linkplain java.lang.Thread#isDaemon
104 * daemon} mode, there is typically no need to explicitly {@link
105 * #shutdown} such a pool upon program exit.
106 *
107 *  <pre> {@code
108 * static final ForkJoinPool mainPool = new ForkJoinPool();
109 * ...
110 * public void sort(long[] array) {
111 *   mainPool.invoke(new SortTask(array, 0, array.length));
112 * }}</pre>
113 *
109   * <p><b>Implementation notes</b>: This implementation restricts the
110   * maximum number of running threads to 32767. Attempts to create
111   * pools with greater than the maximum number result in
# Line 177 | Line 172 | public class ForkJoinPool extends Abstra
172       * If an attempted steal fails, a thief always chooses a different
173       * random victim target to try next. So, in order for one thief to
174       * progress, it suffices for any in-progress poll or new push on
175 <     * any empty queue to complete.
175 >     * any empty queue to complete. (This is why we normally use
176 >     * method pollAt and its variants that try once at the apparent
177 >     * base index, else consider alternative actions, rather than
178 >     * method poll.)
179       *
180       * This approach also enables support of a user mode in which local
181       * task processing is in FIFO, not LIFO order, simply by using
# Line 203 | Line 201 | public class ForkJoinPool extends Abstra
201       * take tasks, and they are multiplexed on to a finite number of
202       * shared work queues. However, classes are set up so that future
203       * extensions could allow submitters to optionally help perform
204 <     * tasks as well. Pool submissions from internal workers are also
205 <     * allowed, but use randomized rather than thread-hashed queue
206 <     * indices to avoid imbalance.  Insertion of tasks in shared mode
207 <     * requires a lock (mainly to protect in the case of resizing) but
208 <     * we use only a simple spinlock (using bits in field runState),
209 <     * because submitters encountering a busy queue try or create
212 <     * others so never block.
204 >     * tasks as well. Insertion of tasks in shared mode requires a
205 >     * lock (mainly to protect in the case of resizing) but we use
206 >     * only a simple spinlock (using bits in field runState), because
207 >     * submitters encountering a busy queue move on to try or create
208 >     * other queues -- they block only when creating and registering
209 >     * new queues.
210       *
211       * Management
212       * ==========
# Line 238 | Line 235 | public class ForkJoinPool extends Abstra
235       * when locked remains available to check consistency.
236       *
237       * Recording WorkQueues.  WorkQueues are recorded in the
238 <     * "workQueues" array that is created upon pool construction and
239 <     * expanded if necessary.  Updates to the array while recording
240 <     * new workers and unrecording terminated ones are protected from
241 <     * each other by a lock but the array is otherwise concurrently
242 <     * readable, and accessed directly.  To simplify index-based
243 <     * operations, the array size is always a power of two, and all
244 <     * readers must tolerate null slots. Shared (submission) queues
245 <     * are at even indices, worker queues at odd indices. Grouping
246 <     * them together in this way simplifies and speeds up task
247 <     * scanning. To avoid flailing during start-up, the array is
248 <     * presized to hold twice #parallelism workers (which is unlikely
249 <     * to need further resizing during execution). But to avoid
253 <     * 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
238 >     * "workQueues" array that is created upon first use and expanded
239 >     * if necessary.  Updates to the array while recording new workers
240 >     * and unrecording terminated ones are protected from each other
241 >     * by a lock but the array is otherwise concurrently readable, and
242 >     * accessed directly.  To simplify index-based operations, the
243 >     * array size is always a power of two, and all readers must
244 >     * tolerate null slots. Shared (submission) queues are at even
245 >     * indices, worker queues at odd indices. Grouping them together
246 >     * in this way simplifies and speeds up task scanning.
247 >     *
248 >     * All worker thread creation is on-demand, triggered by task
249 >     * submissions, replacement of terminated workers, and/or
250       * compensation for blocked workers. However, all other support
251       * code is set up to work with other policies.  To ensure that we
252       * do not hold on to worker references that would prevent GC, ALL
# Line 266 | Line 259 | public class ForkJoinPool extends Abstra
259       * both index-check and null-check the IDs. All such accesses
260       * ignore bad IDs by returning out early from what they are doing,
261       * since this can only be associated with termination, in which
262 <     * case it is OK to give up.
263 <     *
264 <     * All uses of the workQueues array check that it is non-null
265 <     * (even if previously non-null). This allows nulling during
266 <     * termination, which is currently not necessary, but remains an
267 <     * option for resource-revocation-based shutdown schemes. It also
275 <     * helps reduce JIT issuance of uncommon-trap code, which tends to
262 >     * case it is OK to give up.  All uses of the workQueues array
263 >     * also check that it is non-null (even if previously
264 >     * non-null). This allows nulling during termination, which is
265 >     * currently not necessary, but remains an option for
266 >     * resource-revocation-based shutdown schemes. It also helps
267 >     * reduce JIT issuance of uncommon-trap code, which tends to
268       * unnecessarily complicate control flow in some methods.
269       *
270       * Event Queuing. Unlike HPC work-stealing frameworks, we cannot
# Line 323 | Line 315 | public class ForkJoinPool extends Abstra
315       *
316       * Trimming workers. To release resources after periods of lack of
317       * use, a worker starting to wait when the pool is quiescent will
318 <     * time out and terminate if the pool has remained quiescent for
319 <     * SHRINK_RATE nanosecs. This will slowly propagate, eventually
320 <     * terminating all workers after long periods of non-use.
318 >     * time out and terminate if the pool has remained quiescent for a
319 >     * given period -- a short period if there are more threads than
320 >     * parallelism, longer as the number of threads decreases. This
321 >     * will slowly propagate, eventually terminating all workers after
322 >     * periods of non-use.
323       *
324       * Shutdown and Termination. A call to shutdownNow atomically sets
325       * a runState bit and then (non-atomically) sets each worker's
# Line 383 | Line 377 | public class ForkJoinPool extends Abstra
377       * (http://portal.acm.org/citation.cfm?id=155354). It differs in
378       * that: (1) We only maintain dependency links across workers upon
379       * steals, rather than use per-task bookkeeping.  This sometimes
380 <     * requires a linear scan of workers array to locate stealers, but
381 <     * often doesn't because stealers leave hints (that may become
380 >     * requires a linear scan of workQueues array to locate stealers,
381 >     * but often doesn't because stealers leave hints (that may become
382       * stale/wrong) of where to locate them.  A stealHint is only a
383       * hint because a worker might have had multiple steals and the
384       * hint records only one of them (usually the most current).
# Line 395 | Line 389 | public class ForkJoinPool extends Abstra
389       * which means that we miss links in the chain during long-lived
390       * tasks, GC stalls etc (which is OK since blocking in such cases
391       * is usually a good idea).  (4) We bound the number of attempts
392 <     * to find work (see MAX_HELP_DEPTH) and fall back to suspending
393 <     * the worker and if necessary replacing it with another.
392 >     * to find work (see MAX_HELP) and fall back to suspending the
393 >     * worker and if necessary replacing it with another.
394       *
395       * It is impossible to keep exactly the target parallelism number
396       * of threads running at any given time.  Determining the
397       * existence of conservatively safe helping targets, the
398       * availability of already-created spares, and the apparent need
399       * to create new spares are all racy, so we rely on multiple
400 <     * retries of each.  Currently, in keeping with on-demand
401 <     * signalling policy, we compensate only if blocking would leave
402 <     * less than one active (non-waiting, non-blocked) worker.
403 <     * Additionally, to avoid some false alarms due to GC, lagging
404 <     * counters, system activity, etc, compensated blocking for joins
405 <     * is only attempted after rechecks stabilize in
406 <     * ForkJoinTask.awaitJoin. (Retries are interspersed with
407 <     * Thread.yield, for good citizenship.)
400 >     * retries of each.  Compensation in the apparent absence of
401 >     * helping opportunities is challenging to control on JVMs, where
402 >     * GC and other activities can stall progress of tasks that in
403 >     * turn stall out many other dependent tasks, without us being
404 >     * able to determine whether they will ever require compensation.
405 >     * Even though work-stealing otherwise encounters little
406 >     * degradation in the presence of more threads than cores,
407 >     * aggressively adding new threads in such cases entails risk of
408 >     * unwanted positive feedback control loops in which more threads
409 >     * cause more dependent stalls (as well as delayed progress of
410 >     * unblocked threads to the point that we know they are available)
411 >     * leading to more situations requiring more threads, and so
412 >     * on. This aspect of control can be seen as an (analytically
413 >     * intractable) game with an opponent that may choose the worst
414 >     * (for us) active thread to stall at any time.  We take several
415 >     * precautions to bound losses (and thus bound gains), mainly in
416 >     * methods tryCompensate and awaitJoin: (1) We only try
417 >     * compensation after attempting enough helping steps (measured
418 >     * via counting and timing) that we have already consumed the
419 >     * estimated cost of creating and activating a new thread.  (2) We
420 >     * allow up to 50% of threads to be blocked before initially
421 >     * adding any others, and unless completely saturated, check that
422 >     * some work is available for a new worker before adding. Also, we
423 >     * create up to only 50% more threads until entering a mode that
424 >     * only adds a thread if all others are possibly blocked.  All
425 >     * together, this means that we might be half as fast to react,
426 >     * and create half as many threads as possible in the ideal case,
427 >     * but present vastly fewer anomalies in all other cases compared
428 >     * to both more aggressive and more conservative alternatives.
429       *
430       * Style notes: There is a lot of representation-level coupling
431       * among classes ForkJoinPool, ForkJoinWorkerThread, and
# Line 418 | Line 433 | public class ForkJoinPool extends Abstra
433       * managed by ForkJoinPool, so are directly accessed.  There is
434       * little point trying to reduce this, since any associated future
435       * changes in representations will need to be accompanied by
436 <     * algorithmic changes anyway. All together, these low-level
437 <     * implementation choices produce as much as a factor of 4
438 <     * performance improvement compared to naive implementations, and
439 <     * enable the processing of billions of tasks per second, at the
440 <     * expense of some ugliness.
441 <     *
442 <     * Methods signalWork() and scan() are the main bottlenecks, so are
443 <     * especially heavily micro-optimized/mangled.  There are lots of
444 <     * inline assignments (of form "while ((local = field) != 0)")
445 <     * which are usually the simplest way to ensure the required read
446 <     * orderings (which are sometimes critical). This leads to a
447 <     * "C"-like style of listing declarations of these locals at the
448 <     * heads of methods or blocks.  There are several occurrences of
449 <     * 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).
436 >     * algorithmic changes anyway. Several methods intrinsically
437 >     * sprawl because they must accumulate sets of consistent reads of
438 >     * volatiles held in local variables.  Methods signalWork() and
439 >     * scan() are the main bottlenecks, so are especially heavily
440 >     * micro-optimized/mangled.  There are lots of inline assignments
441 >     * (of form "while ((local = field) != 0)") which are usually the
442 >     * simplest way to ensure the required read orderings (which are
443 >     * sometimes critical). This leads to a "C"-like style of listing
444 >     * declarations of these locals at the heads of methods or blocks.
445 >     * There are several occurrences of the unusual "do {} while
446 >     * (!cas...)"  which is the simplest way to force an update of a
447 >     * CAS'ed variable. There are also other coding oddities that help
448 >     * some methods perform reasonably even when interpreted (not
449 >     * compiled).
450       *
451       * The order of declarations in this file is:
452 <     * (1) statics
453 <     * (2) fields (along with constants used when unpacking some of
454 <     *     them), listed in an order that tends to reduce contention
455 <     *     among them a bit under most JVMs;
456 <     * (3) nested classes
457 <     * (4) internal control methods
458 <     * (5) callbacks and other support for ForkJoinTask methods
459 <     * (6) exported methods (plus a few little helpers)
448 <     * (7) static block initializing all statics in a minimally
449 <     *     dependent order.
452 >     * (1) Static utility functions
453 >     * (2) Nested (static) classes
454 >     * (3) Static fields
455 >     * (4) Fields, along with constants used when unpacking some of them
456 >     * (5) Internal control methods
457 >     * (6) Callbacks and other support for ForkJoinTask methods
458 >     * (7) Exported methods
459 >     * (8) Static block initializing statics in minimally dependent order
460       */
461  
462 +    // Static utilities
463 +
464 +    /**
465 +     * If there is a security manager, makes sure caller has
466 +     * permission to modify threads.
467 +     */
468 +    private static void checkPermission() {
469 +        SecurityManager security = System.getSecurityManager();
470 +        if (security != null)
471 +            security.checkPermission(modifyThreadPermission);
472 +    }
473 +
474 +    // Nested classes
475 +
476      /**
477       * Factory for creating new {@link ForkJoinWorkerThread}s.
478       * A {@code ForkJoinWorkerThreadFactory} must be defined and used
# Line 477 | Line 501 | public class ForkJoinPool extends Abstra
501      }
502  
503      /**
504 <     * Creates a new ForkJoinWorkerThread. This factory is used unless
505 <     * overridden in ForkJoinPool constructors.
506 <     */
507 <    public static final ForkJoinWorkerThreadFactory
484 <        defaultForkJoinWorkerThreadFactory;
485 <
486 <    /**
487 <     * Permission required for callers of methods that may start or
488 <     * kill threads.
489 <     */
490 <    private static final RuntimePermission modifyThreadPermission;
491 <
492 <    /**
493 <     * If there is a security manager, makes sure caller has
494 <     * permission to modify threads.
504 >     * Class for artificial tasks that are used to replace the target
505 >     * of local joins if they are removed from an interior queue slot
506 >     * in WorkQueue.tryRemoveAndExec. We don't need the proxy to
507 >     * actually do anything beyond having a unique identity.
508       */
509 <    private static void checkPermission() {
510 <        SecurityManager security = System.getSecurityManager();
511 <        if (security != null)
512 <            security.checkPermission(modifyThreadPermission);
509 >    static final class EmptyTask extends ForkJoinTask<Void> {
510 >        EmptyTask() { status = ForkJoinTask.NORMAL; } // force done
511 >        public final Void getRawResult() { return null; }
512 >        public final void setRawResult(Void x) {}
513 >        public final boolean exec() { return true; }
514      }
515  
516      /**
503     * Generator for assigning sequence numbers as pool names.
504     */
505    private static final AtomicInteger poolNumberGenerator;
506
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.
623     */
624
625    volatile long ctl;                       // main pool control
626    final int parallelism;                   // parallelism level
627    final int localMode;                     // per-worker scheduling mode
628    int nextPoolIndex;                       // hint used in registerWorker
629    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
638
639    /**
517       * Queues supporting work-stealing as well as external task
518       * submission. See above for main rationale and algorithms.
519       * Implementation relies heavily on "Unsafe" intrinsics
# Line 685 | Line 562 | public class ForkJoinPool extends Abstra
562       * avoiding really bad worst-case access. (Until better JVM
563       * support is in place, this padding is dependent on transient
564       * properties of JVM field layout rules.)  We also take care in
565 <     * allocating and sizing and resizing the array. Non-shared queue
565 >     * allocating, sizing and resizing the array. Non-shared queue
566       * arrays are initialized (via method growArray) by workers before
567       * use. Others are allocated on first use.
568       */
569      static final class WorkQueue {
570          /**
571           * Capacity of work-stealing queue array upon initialization.
572 <         * Must be a power of two; at least 4, but set larger to
573 <         * reduce cacheline sharing among queues.
572 >         * Must be a power of two; at least 4, but should be larger to
573 >         * reduce or eliminate cacheline sharing among queues.
574 >         * Currently, it is much larger, as a partial workaround for
575 >         * the fact that JVMs often place arrays in locations that
576 >         * share GC bookkeeping (especially cardmarks) such that
577 >         * per-write accesses encounter serious memory contention.
578           */
579 <        static final int INITIAL_QUEUE_CAPACITY = 1 << 8;
579 >        static final int INITIAL_QUEUE_CAPACITY = 1 << 13;
580  
581          /**
582           * Maximum size for queue arrays. Must be a power of two less
# Line 719 | Line 600 | public class ForkJoinPool extends Abstra
600          volatile int base;         // index of next slot for poll
601          int top;                   // index of next slot for push
602          ForkJoinTask<?>[] array;   // the elements (initially unallocated)
603 +        final ForkJoinPool pool;   // the containing pool (may be null)
604          final ForkJoinWorkerThread owner; // owning thread or null if shared
605          volatile Thread parker;    // == owner during call to park; else null
606 <        ForkJoinTask<?> currentJoin;  // task being joined in awaitJoin
606 >        volatile ForkJoinTask<?> currentJoin;  // task being joined in awaitJoin
607          ForkJoinTask<?> currentSteal; // current non-local task being executed
608          // Heuristic padding to ameliorate unfortunate memory placements
609 <        Object p00, p01, p02, p03, p04, p05, p06, p07, p08, p09, p0a;
609 >        Object p00, p01, p02, p03, p04, p05, p06, p07;
610 >        Object p08, p09, p0a, p0b, p0c, p0d, p0e;
611  
612 <        WorkQueue(ForkJoinWorkerThread owner, int mode) {
730 <            this.owner = owner;
612 >        WorkQueue(ForkJoinPool pool, ForkJoinWorkerThread owner, int mode) {
613              this.mode = mode;
614 +            this.pool = pool;
615 +            this.owner = owner;
616              // Place indices in the center of array (that is not yet allocated)
617              base = top = INITIAL_QUEUE_CAPACITY >>> 1;
618          }
619  
620          /**
621 <         * Returns number of tasks in the queue.
621 >         * Returns the approximate number of tasks in the queue.
622           */
623          final int queueSize() {
624 <            int n = base - top; // non-owner callers must read base first
625 <            return (n >= 0) ? 0 : -n;
624 >            int n = base - top;       // non-owner callers must read base first
625 >            return (n >= 0) ? 0 : -n; // ignore transient negative
626 >        }
627 >
628 >        /**
629 >         * Provides a more accurate estimate of whether this queue has
630 >         * any tasks than does queueSize, by checking whether a
631 >         * near-empty queue has at least one unclaimed task.
632 >         */
633 >        final boolean isEmpty() {
634 >            ForkJoinTask<?>[] a; int m, s;
635 >            int n = base - (s = top);
636 >            return (n >= 0 ||
637 >                    (n == -1 &&
638 >                     ((a = array) == null ||
639 >                      (m = a.length - 1) < 0 ||
640 >                      U.getObjectVolatile
641 >                      (a, ((m & (s - 1)) << ASHIFT) + ABASE) == null)));
642          }
643  
644          /**
645           * Pushes a task. Call only by owner in unshared queues.
646           *
647           * @param task the task. Caller must ensure non-null.
748         * @param p if non-null, pool to signal if necessary
648           * @throw RejectedExecutionException if array cannot be resized
649           */
650 <        final void push(ForkJoinTask<?> task, ForkJoinPool p) {
651 <            ForkJoinTask<?>[] a;
650 >        final void push(ForkJoinTask<?> task) {
651 >            ForkJoinTask<?>[] a; ForkJoinPool p;
652              int s = top, m, n;
653              if ((a = array) != null) {    // ignore if queue removed
654                  U.putOrderedObject
655                      (a, (((m = a.length - 1) & s) << ASHIFT) + ABASE, task);
656                  if ((n = (top = s + 1) - base) <= 2) {
657 <                    if (p != null)
657 >                    if ((p = pool) != null)
658                          p.signalWork();
659                  }
660                  else if (n >= m)
# Line 774 | Line 673 | public class ForkJoinPool extends Abstra
673              boolean submitted = false;
674              if (runState == 0 && U.compareAndSwapInt(this, RUNSTATE, 0, 1)) {
675                  ForkJoinTask<?>[] a = array;
676 <                int s = top, n = s - base;
676 >                int s = top;
677                  try {
678 <                    if ((a != null && n < a.length - 1) ||
678 >                    if ((a != null && a.length > s + 1 - base) ||
679                          (a = growArray(false)) != null) { // must presize
680                          int j = (((a.length - 1) & s) << ASHIFT) + ABASE;
681                          U.putObject(a, (long)j, task);    // don't need "ordered"
# Line 791 | Line 690 | public class ForkJoinPool extends Abstra
690          }
691  
692          /**
693 <         * Takes next task, if one exists, in FIFO order.
693 >         * Takes next task, if one exists, in LIFO order.  Call only
694 >         * by owner in unshared queues. (We do not have a shared
695 >         * version of this method because it is never needed.)
696           */
697 <        final ForkJoinTask<?> poll() {
698 <            ForkJoinTask<?>[] a; int b, i;
699 <            while ((b = base) - top < 0 && (a = array) != null &&
700 <                   (i = (a.length - 1) & b) >= 0) {
701 <                int j = (i << ASHIFT) + ABASE;
702 <                ForkJoinTask<?> t = (ForkJoinTask<?>)U.getObjectVolatile(a, j);
703 <                if (t != null && base == b &&
697 >        final ForkJoinTask<?> pop() {
698 >            ForkJoinTask<?>[] a; ForkJoinTask<?> t; int m;
699 >            if ((a = array) != null && (m = a.length - 1) >= 0) {
700 >                for (int s; (s = top - 1) - base >= 0;) {
701 >                    long j = ((m & s) << ASHIFT) + ABASE;
702 >                    if ((t = (ForkJoinTask<?>)U.getObject(a, j)) == null)
703 >                        break;
704 >                    if (U.compareAndSwapObject(a, j, t, null)) {
705 >                        top = s;
706 >                        return t;
707 >                    }
708 >                }
709 >            }
710 >            return null;
711 >        }
712 >
713 >        /**
714 >         * Takes a task in FIFO order if b is base of queue and a task
715 >         * can be claimed without contention. Specialized versions
716 >         * appear in ForkJoinPool methods scan and tryHelpStealer.
717 >         */
718 >        final ForkJoinTask<?> pollAt(int b) {
719 >            ForkJoinTask<?> t; ForkJoinTask<?>[] a;
720 >            if ((a = array) != null) {
721 >                int j = (((a.length - 1) & b) << ASHIFT) + ABASE;
722 >                if ((t = (ForkJoinTask<?>)U.getObjectVolatile(a, j)) != null &&
723 >                    base == b &&
724                      U.compareAndSwapObject(a, j, t, null)) {
725                      base = b + 1;
726                      return t;
# Line 809 | Line 730 | public class ForkJoinPool extends Abstra
730          }
731  
732          /**
733 <         * Takes next task, if one exists, in LIFO order.
813 <         * Call only by owner in unshared queues.
733 >         * Takes next task, if one exists, in FIFO order.
734           */
735 <        final ForkJoinTask<?> pop() {
736 <            ForkJoinTask<?> t; int m;
737 <            ForkJoinTask<?>[] a = array;
738 <            if (a != null && (m = a.length - 1) >= 0) {
739 <                for (int s; (s = top - 1) - base >= 0;) {
740 <                    int j = ((m & s) << ASHIFT) + ABASE;
741 <                    if ((t = (ForkJoinTask<?>)U.getObjectVolatile(a, j)) == null)
742 <                        break;
743 <                    if (U.compareAndSwapObject(a, j, t, null)) {
824 <                        top = s;
735 >        final ForkJoinTask<?> poll() {
736 >            ForkJoinTask<?>[] a; int b; ForkJoinTask<?> t;
737 >            while ((b = base) - top < 0 && (a = array) != null) {
738 >                int j = (((a.length - 1) & b) << ASHIFT) + ABASE;
739 >                t = (ForkJoinTask<?>)U.getObjectVolatile(a, j);
740 >                if (t != null) {
741 >                    if (base == b &&
742 >                        U.compareAndSwapObject(a, j, t, null)) {
743 >                        base = b + 1;
744                          return t;
745                      }
746                  }
747 +                else if (base == b) {
748 +                    if (b + 1 == top)
749 +                        break;
750 +                    Thread.yield(); // wait for lagging update
751 +                }
752              }
753              return null;
754          }
# Line 849 | Line 773 | public class ForkJoinPool extends Abstra
773          }
774  
775          /**
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        /**
776           * Pops the given task only if it is at the current top.
777           */
778          final boolean tryUnpush(ForkJoinTask<?> t) {
# Line 881 | Line 787 | public class ForkJoinPool extends Abstra
787          }
788  
789          /**
790 +         * Version of tryUnpush for shared queues; called by non-FJ
791 +         * submitters after prechecking that task probably exists.
792 +         */
793 +        final boolean trySharedUnpush(ForkJoinTask<?> t) {
794 +            boolean success = false;
795 +            if (runState == 0 && U.compareAndSwapInt(this, RUNSTATE, 0, 1)) {
796 +                try {
797 +                    ForkJoinTask<?>[] a; int s;
798 +                    if ((a = array) != null && (s = top) != base &&
799 +                        U.compareAndSwapObject
800 +                        (a, (((a.length - 1) & --s) << ASHIFT) + ABASE, t, null)) {
801 +                        top = s;
802 +                        success = true;
803 +                    }
804 +                } finally {
805 +                    runState = 0;                         // unlock
806 +                }
807 +            }
808 +            return success;
809 +        }
810 +
811 +        /**
812           * Polls the given task only if it is at the current base.
813           */
814          final boolean pollFor(ForkJoinTask<?> task) {
815 <            ForkJoinTask<?>[] a; int b, i;
816 <            if ((b = base) - top < 0 && (a = array) != null &&
817 <                (i = (a.length - 1) & b) >= 0) {
890 <                int j = (i << ASHIFT) + ABASE;
815 >            ForkJoinTask<?>[] a; int b;
816 >            if ((b = base) - top < 0 && (a = array) != null) {
817 >                int j = (((a.length - 1) & b) << ASHIFT) + ABASE;
818                  if (U.getObjectVolatile(a, j) == task && base == b &&
819                      U.compareAndSwapObject(a, j, task, null)) {
820                      base = b + 1;
# Line 898 | Line 825 | public class ForkJoinPool extends Abstra
825          }
826  
827          /**
901         * If present, removes from queue and executes the given task, or
902         * any other cancelled task. Returns (true) immediately on any CAS
903         * or consistency check failure so caller can retry.
904         *
905         * @return false if no progress can be made
906         */
907        final boolean tryRemoveAndExec(ForkJoinTask<?> task) {
908            boolean removed = false, empty = true, progress = true;
909            ForkJoinTask<?>[] a; int m, s, b, n;
910            if ((a = array) != null && (m = a.length - 1) >= 0 &&
911                (n = (s = top) - (b = base)) > 0) {
912                for (ForkJoinTask<?> t;;) {           // traverse from s to b
913                    int j = ((--s & m) << ASHIFT) + ABASE;
914                    t = (ForkJoinTask<?>)U.getObjectVolatile(a, j);
915                    if (t == null)                    // inconsistent length
916                        break;
917                    else if (t == task) {
918                        if (s + 1 == top) {           // pop
919                            if (!U.compareAndSwapObject(a, j, task, null))
920                                break;
921                            top = s;
922                            removed = true;
923                        }
924                        else if (base == b)           // replace with proxy
925                            removed = U.compareAndSwapObject(a, j, task,
926                                                             new EmptyTask());
927                        break;
928                    }
929                    else if (t.status >= 0)
930                        empty = false;
931                    else if (s + 1 == top) {          // pop and throw away
932                        if (U.compareAndSwapObject(a, j, t, null))
933                            top = s;
934                        break;
935                    }
936                    if (--n == 0) {
937                        if (!empty && base == b)
938                            progress = false;
939                        break;
940                    }
941                }
942            }
943            if (removed)
944                task.doExec();
945            return progress;
946        }
947
948        /**
828           * Initializes or doubles the capacity of array. Call either
829           * by owner or with lock held -- it is OK for base, but not
830           * top, to move while resizings are in progress.
# Line 990 | Line 869 | public class ForkJoinPool extends Abstra
869                  ForkJoinTask.cancelIgnoringExceptions(t);
870          }
871  
872 +        /**
873 +         * Computes next value for random probes.  Scans don't require
874 +         * a very high quality generator, but also not a crummy one.
875 +         * Marsaglia xor-shift is cheap and works well enough.  Note:
876 +         * This is manually inlined in its usages in ForkJoinPool to
877 +         * avoid writes inside busy scan loops.
878 +         */
879 +        final int nextSeed() {
880 +            int r = seed;
881 +            r ^= r << 13;
882 +            r ^= r >>> 17;
883 +            return seed = r ^= r << 5;
884 +        }
885 +
886          // Execution methods
887  
888          /**
889 <         * Removes and runs tasks until empty, using local mode
997 <         * ordering.
889 >         * Pops and runs tasks until empty.
890           */
891 <        final void runLocalTasks() {
892 <            if (base - top < 0) {
893 <                for (ForkJoinTask<?> t; (t = nextLocalTask()) != null; )
891 >        private void popAndExecAll() {
892 >            // A bit faster than repeated pop calls
893 >            ForkJoinTask<?>[] a; int m, s; long j; ForkJoinTask<?> t;
894 >            while ((a = array) != null && (m = a.length - 1) >= 0 &&
895 >                   (s = top - 1) - base >= 0 &&
896 >                   (t = ((ForkJoinTask<?>)
897 >                         U.getObject(a, j = ((m & s) << ASHIFT) + ABASE)))
898 >                   != null) {
899 >                if (U.compareAndSwapObject(a, j, t, null)) {
900 >                    top = s;
901                      t.doExec();
902 +                }
903              }
904          }
905  
906          /**
907 +         * Polls and runs tasks until empty.
908 +         */
909 +        private void pollAndExecAll() {
910 +            for (ForkJoinTask<?> t; (t = poll()) != null;)
911 +                t.doExec();
912 +        }
913 +
914 +        /**
915 +         * If present, removes from queue and executes the given task, or
916 +         * any other cancelled task. Returns (true) immediately on any CAS
917 +         * or consistency check failure so caller can retry.
918 +         *
919 +         * @return 0 if no progress can be made, else positive
920 +         * (this unusual convention simplifies use with tryHelpStealer.)
921 +         */
922 +        final int tryRemoveAndExec(ForkJoinTask<?> task) {
923 +            int stat = 1;
924 +            boolean removed = false, empty = true;
925 +            ForkJoinTask<?>[] a; int m, s, b, n;
926 +            if ((a = array) != null && (m = a.length - 1) >= 0 &&
927 +                (n = (s = top) - (b = base)) > 0) {
928 +                for (ForkJoinTask<?> t;;) {           // traverse from s to b
929 +                    int j = ((--s & m) << ASHIFT) + ABASE;
930 +                    t = (ForkJoinTask<?>)U.getObjectVolatile(a, j);
931 +                    if (t == null)                    // inconsistent length
932 +                        break;
933 +                    else if (t == task) {
934 +                        if (s + 1 == top) {           // pop
935 +                            if (!U.compareAndSwapObject(a, j, task, null))
936 +                                break;
937 +                            top = s;
938 +                            removed = true;
939 +                        }
940 +                        else if (base == b)           // replace with proxy
941 +                            removed = U.compareAndSwapObject(a, j, task,
942 +                                                             new EmptyTask());
943 +                        break;
944 +                    }
945 +                    else if (t.status >= 0)
946 +                        empty = false;
947 +                    else if (s + 1 == top) {          // pop and throw away
948 +                        if (U.compareAndSwapObject(a, j, t, null))
949 +                            top = s;
950 +                        break;
951 +                    }
952 +                    if (--n == 0) {
953 +                        if (!empty && base == b)
954 +                            stat = 0;
955 +                        break;
956 +                    }
957 +                }
958 +            }
959 +            if (removed)
960 +                task.doExec();
961 +            return stat;
962 +        }
963 +
964 +        /**
965           * Executes a top-level task and any local tasks remaining
966           * after execution.
1009         *
1010         * @return true unless terminating
967           */
968 <        final boolean runTask(ForkJoinTask<?> t) {
1013 <            boolean alive = true;
968 >        final void runTask(ForkJoinTask<?> t) {
969              if (t != null) {
970                  currentSteal = t;
971                  t.doExec();
972 <                runLocalTasks();
972 >                if (top != base) {       // process remaining local tasks
973 >                    if (mode == 0)
974 >                        popAndExecAll();
975 >                    else
976 >                        pollAndExecAll();
977 >                }
978                  ++nsteals;
979                  currentSteal = null;
980              }
1021            else if (runState < 0)            // terminating
1022                alive = false;
1023            return alive;
981          }
982  
983          /**
# Line 1036 | Line 993 | public class ForkJoinPool extends Abstra
993          }
994  
995          /**
996 <         * 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.
996 >         * Returns true if owned and not known to be blocked.
997           */
998 <        final int nextSeed() {
999 <            int r = seed;
1000 <            r ^= r << 13;
1001 <            r ^= r >>> 17;
1002 <            r ^= r << 5;
1003 <            return seed = r;
998 >        final boolean isApparentlyUnblocked() {
999 >            Thread wt; Thread.State s;
1000 >            return (eventCount >= 0 &&
1001 >                    (wt = owner) != null &&
1002 >                    (s = wt.getState()) != Thread.State.BLOCKED &&
1003 >                    s != Thread.State.WAITING &&
1004 >                    s != Thread.State.TIMED_WAITING);
1005 >        }
1006 >
1007 >        /**
1008 >         * If this owned and is not already interrupted, try to
1009 >         * interrupt and/or unpark, ignoring exceptions.
1010 >         */
1011 >        final void interruptOwner() {
1012 >            Thread wt, p;
1013 >            if ((wt = owner) != null && !wt.isInterrupted()) {
1014 >                try {
1015 >                    wt.interrupt();
1016 >                } catch (SecurityException ignore) {
1017 >                }
1018 >            }
1019 >            if ((p = parker) != null)
1020 >                U.unpark(p);
1021          }
1022  
1023          // Unsafe mechanics
# Line 1075 | Line 1045 | public class ForkJoinPool extends Abstra
1045      }
1046  
1047      /**
1048 <     * Class for artificial tasks that are used to replace the target
1049 <     * of local joins if they are removed from an interior queue slot
1050 <     * in WorkQueue.tryRemoveAndExec. We don't need the proxy to
1051 <     * actually do anything beyond having a unique identity.
1052 <     */
1053 <    static final class EmptyTask extends ForkJoinTask<Void> {
1054 <        EmptyTask() { status = ForkJoinTask.NORMAL; } // force done
1055 <        public Void getRawResult() { return null; }
1056 <        public void setRawResult(Void x) {}
1057 <        public boolean exec() { return true; }
1058 <    }
1059 <
1060 <    /**
1061 <     * 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.
1048 >     * Per-thread records for threads that submit to pools. Currently
1049 >     * holds only pseudo-random seed / index that is used to choose
1050 >     * submission queues in method doSubmit. In the future, this may
1051 >     * also incorporate a means to implement different task rejection
1052 >     * and resubmission policies.
1053 >     *
1054 >     * Seeds for submitters and workers/workQueues work in basically
1055 >     * the same way but are initialized and updated using slightly
1056 >     * different mechanics. Both are initialized using the same
1057 >     * approach as in class ThreadLocal, where successive values are
1058 >     * unlikely to collide with previous values. This is done during
1059 >     * registration for workers, but requires a separate AtomicInteger
1060 >     * for submitters. Seeds are then randomly modified upon
1061 >     * collisions using xorshifts, which requires a non-zero seed.
1062       */
1063      static final class Submitter {
1064 <        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 <
1064 >        int seed;
1065          Submitter() {
1066 <            // Use identityHashCode, forced negative, for seed
1067 <            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;
1066 >            int s = nextSubmitterSeed.getAndAdd(SEED_INCREMENT);
1067 >            seed = (s == 0) ? 1 : s; // ensure non-zero
1068          }
1069      }
1070  
# Line 1123 | Line 1073 | public class ForkJoinPool extends Abstra
1073          public Submitter initialValue() { return new Submitter(); }
1074      }
1075  
1076 +    // static fields (initialized in static initializer below)
1077 +
1078      /**
1079 <     * Per-thread submission bookeeping. Shared across all pools
1079 >     * Creates a new ForkJoinWorkerThread. This factory is used unless
1080 >     * overridden in ForkJoinPool constructors.
1081 >     */
1082 >    public static final ForkJoinWorkerThreadFactory
1083 >        defaultForkJoinWorkerThreadFactory;
1084 >
1085 >
1086 >    /** Property prefix for constructing common pool */
1087 >    private static final String propPrefix =
1088 >        "java.util.concurrent.ForkJoinPool.common.";
1089 >
1090 >    /**
1091 >     * Common (static) pool. Non-null for public use unless a static
1092 >     * construction exception, but internal usages must null-check on
1093 >     * use.
1094 >     */
1095 >    static final ForkJoinPool commonPool;
1096 >
1097 >    /**
1098 >     * Common pool parallelism. Must equal commonPool.parallelism.
1099 >     */
1100 >    static final int commonPoolParallelism;
1101 >
1102 >    /**
1103 >     * Generator for assigning sequence numbers as pool names.
1104 >     */
1105 >    private static final AtomicInteger poolNumberGenerator;
1106 >
1107 >    /**
1108 >     * Generator for initial hashes/seeds for submitters. Accessed by
1109 >     * Submitter class constructor.
1110 >     */
1111 >    static final AtomicInteger nextSubmitterSeed;
1112 >
1113 >    /**
1114 >     * Permission required for callers of methods that may start or
1115 >     * kill threads.
1116 >     */
1117 >    private static final RuntimePermission modifyThreadPermission;
1118 >
1119 >    /**
1120 >     * Per-thread submission bookkeeping. Shared across all pools
1121       * to reduce ThreadLocal pollution and because random motion
1122       * to avoid contention in one pool is likely to hold for others.
1123       */
1124 <    static final ThreadSubmitter submitters = new ThreadSubmitter();
1124 >    private static final ThreadSubmitter submitters;
1125 >
1126 >    // static constants
1127  
1128      /**
1129 <     * Top-level runloop for workers
1129 >     * Initial timeout value (in nanoseconds) for the thread triggering
1130 >     * quiescence to park waiting for new work. On timeout, the thread
1131 >     * will instead try to shrink the number of workers.
1132       */
1133 <    final void runWorker(ForkJoinWorkerThread wt) {
1137 <        // 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);
1133 >    private static final long IDLE_TIMEOUT      = 1000L * 1000L * 1000L; // 1sec
1134  
1135 <        do {} while (w.runTask(scan(w)));
1135 >    /**
1136 >     * Timeout value when there are more threads than parallelism level
1137 >     */
1138 >    private static final long FAST_IDLE_TIMEOUT =  100L * 1000L * 1000L;
1139 >
1140 >    /**
1141 >     * The maximum stolen->joining link depth allowed in method
1142 >     * tryHelpStealer.  Must be a power of two. This value also
1143 >     * controls the maximum number of times to try to help join a task
1144 >     * without any apparent progress or change in pool state before
1145 >     * giving up and blocking (see awaitJoin).  Depths for legitimate
1146 >     * chains are unbounded, but we use a fixed constant to avoid
1147 >     * (otherwise unchecked) cycles and to bound staleness of
1148 >     * traversal parameters at the expense of sometimes blocking when
1149 >     * we could be helping.
1150 >     */
1151 >    private static final int MAX_HELP = 64;
1152 >
1153 >    /**
1154 >     * Secondary time-based bound (in nanosecs) for helping attempts
1155 >     * before trying compensated blocking in awaitJoin. Used in
1156 >     * conjunction with MAX_HELP to reduce variance due to different
1157 >     * polling rates associated with different helping options. The
1158 >     * value should roughly approximate the time required to create
1159 >     * and/or activate a worker thread.
1160 >     */
1161 >    private static final long COMPENSATION_DELAY = 1L << 18; // ~0.25 millisec
1162 >
1163 >    /**
1164 >     * Increment for seed generators. See class ThreadLocal for
1165 >     * explanation.
1166 >     */
1167 >    private static final int SEED_INCREMENT = 0x61c88647;
1168 >
1169 >    /**
1170 >     * Bits and masks for control variables
1171 >     *
1172 >     * Field ctl is a long packed with:
1173 >     * AC: Number of active running workers minus target parallelism (16 bits)
1174 >     * TC: Number of total workers minus target parallelism (16 bits)
1175 >     * ST: true if pool is terminating (1 bit)
1176 >     * EC: the wait count of top waiting thread (15 bits)
1177 >     * ID: poolIndex of top of Treiber stack of waiters (16 bits)
1178 >     *
1179 >     * When convenient, we can extract the upper 32 bits of counts and
1180 >     * the lower 32 bits of queue state, u = (int)(ctl >>> 32) and e =
1181 >     * (int)ctl.  The ec field is never accessed alone, but always
1182 >     * together with id and st. The offsets of counts by the target
1183 >     * parallelism and the positionings of fields makes it possible to
1184 >     * perform the most common checks via sign tests of fields: When
1185 >     * ac is negative, there are not enough active workers, when tc is
1186 >     * negative, there are not enough total workers, and when e is
1187 >     * negative, the pool is terminating.  To deal with these possibly
1188 >     * negative fields, we use casts in and out of "short" and/or
1189 >     * signed shifts to maintain signedness.
1190 >     *
1191 >     * When a thread is queued (inactivated), its eventCount field is
1192 >     * set negative, which is the only way to tell if a worker is
1193 >     * prevented from executing tasks, even though it must continue to
1194 >     * scan for them to avoid queuing races. Note however that
1195 >     * eventCount updates lag releases so usage requires care.
1196 >     *
1197 >     * Field runState is an int packed with:
1198 >     * SHUTDOWN: true if shutdown is enabled (1 bit)
1199 >     * SEQ:  a sequence number updated upon (de)registering workers (30 bits)
1200 >     * INIT: set true after workQueues array construction (1 bit)
1201 >     *
1202 >     * The sequence number enables simple consistency checks:
1203 >     * Staleness of read-only operations on the workQueues array can
1204 >     * be checked by comparing runState before vs after the reads.
1205 >     */
1206 >
1207 >    // bit positions/shifts for fields
1208 >    private static final int  AC_SHIFT   = 48;
1209 >    private static final int  TC_SHIFT   = 32;
1210 >    private static final int  ST_SHIFT   = 31;
1211 >    private static final int  EC_SHIFT   = 16;
1212 >
1213 >    // bounds
1214 >    private static final int  SMASK      = 0xffff;  // short bits
1215 >    private static final int  MAX_CAP    = 0x7fff;  // max #workers - 1
1216 >    private static final int  SQMASK     = 0xfffe;  // even short bits
1217 >    private static final int  SHORT_SIGN = 1 << 15;
1218 >    private static final int  INT_SIGN   = 1 << 31;
1219 >
1220 >    // masks
1221 >    private static final long STOP_BIT   = 0x0001L << ST_SHIFT;
1222 >    private static final long AC_MASK    = ((long)SMASK) << AC_SHIFT;
1223 >    private static final long TC_MASK    = ((long)SMASK) << TC_SHIFT;
1224 >
1225 >    // units for incrementing and decrementing
1226 >    private static final long TC_UNIT    = 1L << TC_SHIFT;
1227 >    private static final long AC_UNIT    = 1L << AC_SHIFT;
1228 >
1229 >    // masks and units for dealing with u = (int)(ctl >>> 32)
1230 >    private static final int  UAC_SHIFT  = AC_SHIFT - 32;
1231 >    private static final int  UTC_SHIFT  = TC_SHIFT - 32;
1232 >    private static final int  UAC_MASK   = SMASK << UAC_SHIFT;
1233 >    private static final int  UTC_MASK   = SMASK << UTC_SHIFT;
1234 >    private static final int  UAC_UNIT   = 1 << UAC_SHIFT;
1235 >    private static final int  UTC_UNIT   = 1 << UTC_SHIFT;
1236 >
1237 >    // masks and units for dealing with e = (int)ctl
1238 >    private static final int E_MASK      = 0x7fffffff; // no STOP_BIT
1239 >    private static final int E_SEQ       = 1 << EC_SHIFT;
1240 >
1241 >    // runState bits
1242 >    private static final int SHUTDOWN    = 1 << 31;
1243 >
1244 >    // access mode for WorkQueue
1245 >    static final int LIFO_QUEUE          =  0;
1246 >    static final int FIFO_QUEUE          =  1;
1247 >    static final int SHARED_QUEUE        = -1;
1248 >
1249 >    // Instance fields
1250 >
1251 >    /*
1252 >     * Field layout order in this class tends to matter more than one
1253 >     * would like. Runtime layout order is only loosely related to
1254 >     * declaration order and may differ across JVMs, but the following
1255 >     * empirically works OK on current JVMs.
1256 >     */
1257 >
1258 >    volatile long stealCount;                  // collects worker counts
1259 >    volatile long ctl;                         // main pool control
1260 >    final int parallelism;                     // parallelism level
1261 >    final int localMode;                       // per-worker scheduling mode
1262 >    volatile int nextWorkerNumber;             // to create worker name string
1263 >    final int submitMask;                      // submit queue index bound
1264 >    int nextSeed;                              // for initializing worker seeds
1265 >    volatile int mainLock;                     // spinlock for array updates
1266 >    volatile int runState;                     // shutdown status and seq
1267 >    WorkQueue[] workQueues;                    // main registry
1268 >    final ForkJoinWorkerThreadFactory factory; // factory for new workers
1269 >    final Thread.UncaughtExceptionHandler ueh; // per-worker UEH
1270 >    final String workerNamePrefix;             // to create worker name string
1271 >
1272 >    /*
1273 >     * Mechanics for main lock protecting worker array updates.  Uses
1274 >     * the same strategy as ConcurrentHashMap bins -- a spinLock for
1275 >     * normal cases, but falling back to builtin lock when (rarely)
1276 >     * needed.  See internal ConcurrentHashMap documentation for
1277 >     * explanation.
1278 >     */
1279 >
1280 >    static final int LOCK_WAITING = 2; // bit to indicate need for signal
1281 >    static final int MAX_LOCK_SPINS = 1 << 8;
1282 >
1283 >    private void tryAwaitMainLock() {
1284 >        int spins = MAX_LOCK_SPINS, r = 0, h;
1285 >        while (((h = mainLock) & 1) != 0) {
1286 >            if (r == 0)
1287 >                r = ThreadLocalRandom.current().nextInt(); // randomize spins
1288 >            else if (spins >= 0) {
1289 >                r ^= r << 1; r ^= r >>> 3; r ^= r << 10; // xorshift
1290 >                if (r >= 0)
1291 >                    --spins;
1292 >            }
1293 >            else if (U.compareAndSwapInt(this, MAINLOCK, h, h | LOCK_WAITING)) {
1294 >                synchronized (this) {
1295 >                    if ((mainLock & LOCK_WAITING) != 0) {
1296 >                        try {
1297 >                            wait();
1298 >                        } catch (InterruptedException ie) {
1299 >                            Thread.currentThread().interrupt();
1300 >                        }
1301 >                    }
1302 >                    else
1303 >                        notifyAll(); // possibly won race vs signaller
1304 >                }
1305 >                break;
1306 >            }
1307 >        }
1308      }
1309  
1310 <    // Creating, registering and deregistering workers
1310 >    //  Creating, registering, and deregistering workers
1311  
1312      /**
1313       * Tries to create and start a worker
1314       */
1315      private void addWorker() {
1316          Throwable ex = null;
1317 <        ForkJoinWorkerThread w = null;
1317 >        ForkJoinWorkerThread wt = null;
1318          try {
1319 <            if ((w = factory.newThread(this)) != null) {
1320 <                w.start();
1319 >            if ((wt = factory.newThread(this)) != null) {
1320 >                wt.start();
1321                  return;
1322              }
1323          } catch (Throwable e) {
1324              ex = e;
1325          }
1326 <        deregisterWorker(w, ex);
1326 >        deregisterWorker(wt, ex); // adjust counts etc on failure
1327      }
1328  
1329      /**
# Line 1169 | Line 1333 | public class ForkJoinPool extends Abstra
1333       * ForkJoinWorkerThread.
1334       */
1335      final String nextWorkerName() {
1336 <        return workerNamePrefix.concat
1337 <            (Integer.toString(nextWorkerNumber.addAndGet(1)));
1336 >        int n;
1337 >        do {} while(!U.compareAndSwapInt(this, NEXTWORKERNUMBER,
1338 >                                         n = nextWorkerNumber, ++n));
1339 >        return workerNamePrefix.concat(Integer.toString(n));
1340      }
1341  
1342      /**
1343 <     * Callback from ForkJoinWorkerThread constructor to establish and
1344 <     * record its WorkQueue.
1343 >     * Callback from ForkJoinWorkerThread constructor to establish its
1344 >     * poolIndex and record its WorkQueue. To avoid scanning bias due
1345 >     * to packing entries in front of the workQueues array, we treat
1346 >     * the array as a simple power-of-two hash table using per-thread
1347 >     * seed as hash, expanding as needed.
1348       *
1349 <     * @param wt the worker thread
1349 >     * @param w the worker's queue
1350       */
1351 <    final void registerWorker(ForkJoinWorkerThread wt) {
1352 <        WorkQueue w = wt.workQueue;
1353 <        ReentrantLock lock = this.lock;
1185 <        lock.lock();
1351 >    final void registerWorker(WorkQueue w) {
1352 >        while (!U.compareAndSwapInt(this, MAINLOCK, 0, 1))
1353 >            tryAwaitMainLock();
1354          try {
1355 <            int k = nextPoolIndex;
1356 <            WorkQueue[] ws = workQueues;
1357 <            if (ws != null) {                       // ignore on shutdown
1358 <                int n = ws.length;
1359 <                if (k < 0 || (k & 1) == 0 || k >= n || ws[k] != null) {
1360 <                    for (k = 1; k < n && ws[k] != null; k += 2)
1361 <                        ;                           // workers are at odd indices
1362 <                    if (k >= n)                     // resize
1363 <                        workQueues = ws = Arrays.copyOf(ws, n << 1);
1364 <                }
1365 <                w.poolIndex = k;
1366 <                w.eventCount = ~(k >>> 1) & SMASK;  // Set up wait count
1367 <                ws[k] = w;                          // record worker
1368 <                nextPoolIndex = k + 2;
1369 <                int rs = runState;
1370 <                int m = rs & SMASK;                 // recalculate runState mask
1371 <                if (k > m)
1372 <                    m = (m << 1) + 1;
1373 <                runState = (rs & SHUTDOWN) | ((rs + RS_SEQ) & RS_SEQ_MASK) | m;
1355 >            WorkQueue[] ws;
1356 >            if ((ws = workQueues) == null)
1357 >                ws = workQueues = new WorkQueue[submitMask + 1];
1358 >            if (w != null) {
1359 >                int rs, n =  ws.length, m = n - 1;
1360 >                int s = nextSeed += SEED_INCREMENT; // rarely-colliding sequence
1361 >                w.seed = (s == 0) ? 1 : s;          // ensure non-zero seed
1362 >                int r = (s << 1) | 1;               // use odd-numbered indices
1363 >                if (ws[r &= m] != null) {           // collision
1364 >                    int probes = 0;                 // step by approx half size
1365 >                    int step = (n <= 4) ? 2 : ((n >>> 1) & SQMASK) + 2;
1366 >                    while (ws[r = (r + step) & m] != null) {
1367 >                        if (++probes >= n) {
1368 >                            workQueues = ws = Arrays.copyOf(ws, n <<= 1);
1369 >                            m = n - 1;
1370 >                            probes = 0;
1371 >                        }
1372 >                    }
1373 >                }
1374 >                w.eventCount = w.poolIndex = r;     // establish before recording
1375 >                ws[r] = w;                          // also update seq
1376 >                runState = ((rs = runState) & SHUTDOWN) | ((rs + 2) & ~SHUTDOWN);
1377              }
1378          } finally {
1379 <            lock.unlock();
1379 >            if (!U.compareAndSwapInt(this, MAINLOCK, 1, 0)) {
1380 >                mainLock = 0;
1381 >                synchronized (this) { notifyAll(); };
1382 >            }
1383          }
1384 +
1385      }
1386  
1387      /**
1388 <     * Final callback from terminating worker, as well as failure to
1389 <     * construct or start a worker in addWorker.  Removes record of
1388 >     * Final callback from terminating worker, as well as upon failure
1389 >     * to construct or start a worker in addWorker.  Removes record of
1390       * worker from array, and adjusts counts. If pool is shutting
1391       * down, tries to complete termination.
1392       *
# Line 1222 | Line 1397 | public class ForkJoinPool extends Abstra
1397          WorkQueue w = null;
1398          if (wt != null && (w = wt.workQueue) != null) {
1399              w.runState = -1;                // ensure runState is set
1400 <            stealCount.getAndAdd(w.totalSteals + w.nsteals);
1400 >            long steals = w.totalSteals + w.nsteals, sc;
1401 >            do {} while(!U.compareAndSwapLong(this, STEALCOUNT,
1402 >                                              sc = stealCount, sc + steals));
1403              int idx = w.poolIndex;
1404 <            ReentrantLock lock = this.lock;
1405 <            lock.lock();
1406 <            try {                           // remove record from array
1404 >            while (!U.compareAndSwapInt(this, MAINLOCK, 0, 1))
1405 >                tryAwaitMainLock();
1406 >            try {
1407                  WorkQueue[] ws = workQueues;
1408                  if (ws != null && idx >= 0 && idx < ws.length && ws[idx] == w)
1409 <                    ws[nextPoolIndex = idx] = null;
1409 >                    ws[idx] = null;
1410              } finally {
1411 <                lock.unlock();
1411 >                if (!U.compareAndSwapInt(this, MAINLOCK, 1, 0)) {
1412 >                    mainLock = 0;
1413 >                    synchronized (this) { notifyAll(); };
1414 >                }
1415              }
1416          }
1417  
# Line 1241 | Line 1421 | public class ForkJoinPool extends Abstra
1421                                             ((c - TC_UNIT) & TC_MASK) |
1422                                             (c & ~(AC_MASK|TC_MASK)))));
1423  
1424 <        if (!tryTerminate(false) && w != null) {
1424 >        if (!tryTerminate(false, false) && w != null) {
1425              w.cancelAll();                  // cancel remaining tasks
1426              if (w.array != null)            // suppress signal if never ran
1427                  signalWork();               // wake up or create replacement
1428 +            if (ex == null)                 // help clean refs on way out
1429 +                ForkJoinTask.helpExpungeStaleExceptions();
1430          }
1431  
1432          if (ex != null)                     // rethrow
1433              U.throwException(ex);
1434      }
1435  
1436 +    // Submissions
1437 +
1438      /**
1439 <     * Tries to add and register a new queue at the given index.
1439 >     * Unless shutting down, adds the given task to a submission queue
1440 >     * at submitter's current queue index (modulo submission
1441 >     * range). If no queue exists at the index, one is created.  If
1442 >     * the queue is busy, another index is randomly chosen. The
1443 >     * submitMask bounds the effective number of queues to the
1444 >     * (nearest power of two for) parallelism level.
1445       *
1446 <     * @param idx the workQueues array index to register the queue
1447 <     * @return the queue, or null if could not add because could
1448 <     * not acquire lock or idx is unusable
1449 <     */
1450 <    private WorkQueue tryAddSharedQueue(int idx) {
1451 <        WorkQueue q = null;
1452 <        ReentrantLock lock = this.lock;
1453 <        if (idx >= 0 && (idx & 1) == 0 && !lock.isLocked()) {
1454 <            // create queue outside of lock but only if apparently free
1455 <            WorkQueue nq = new WorkQueue(null, SHARED_QUEUE);
1456 <            if (lock.tryLock()) {
1446 >     * @param task the task. Caller must ensure non-null.
1447 >     */
1448 >    private void doSubmit(ForkJoinTask<?> task) {
1449 >        Submitter s = submitters.get();
1450 >        for (int r = s.seed, m = submitMask;;) {
1451 >            WorkQueue[] ws; WorkQueue q;
1452 >            int k = r & m & SQMASK;          // use only even indices
1453 >            if (runState < 0)
1454 >                throw new RejectedExecutionException(); // shutting down
1455 >            else if ((ws = workQueues) == null || ws.length <= k) {
1456 >                while (!U.compareAndSwapInt(this, MAINLOCK, 0, 1))
1457 >                    tryAwaitMainLock();
1458                  try {
1459 <                    WorkQueue[] ws = workQueues;
1460 <                    if (ws != null && idx < ws.length) {
1461 <                        if ((q = ws[idx]) == null) {
1462 <                            int rs;         // update runState seq
1463 <                            ws[idx] = q = nq;
1464 <                            runState = (((rs = runState) & SHUTDOWN) |
1465 <                                        ((rs + RS_SEQ) & ~SHUTDOWN));
1466 <                        }
1459 >                    if (workQueues == null)
1460 >                        workQueues = new WorkQueue[submitMask + 1];
1461 >                } finally {
1462 >                    if (!U.compareAndSwapInt(this, MAINLOCK, 1, 0)) {
1463 >                        mainLock = 0;
1464 >                        synchronized (this) { notifyAll(); };
1465 >                    }
1466 >                }
1467 >            }
1468 >            else if ((q = ws[k]) == null) {  // create new queue
1469 >                WorkQueue nq = new WorkQueue(this, null, SHARED_QUEUE);
1470 >                while (!U.compareAndSwapInt(this, MAINLOCK, 0, 1))
1471 >                    tryAwaitMainLock();
1472 >                try {
1473 >                    int rs = runState;       // to update seq
1474 >                    if (ws == workQueues && ws[k] == null) {
1475 >                        ws[k] = nq;
1476 >                        runState = ((rs & SHUTDOWN) | ((rs + 2) & ~SHUTDOWN));
1477                      }
1478                  } finally {
1479 <                    lock.unlock();
1479 >                    if (!U.compareAndSwapInt(this, MAINLOCK, 1, 0)) {
1480 >                        mainLock = 0;
1481 >                        synchronized (this) { notifyAll(); };
1482 >                    }
1483                  }
1484              }
1485 +            else if (q.trySharedPush(task)) {
1486 +                signalWork();
1487 +                return;
1488 +            }
1489 +            else if (m > 1) {                // move to a different index
1490 +                r ^= r << 13;                // same xorshift as WorkQueues
1491 +                r ^= r >>> 17;
1492 +                s.seed = r ^= r << 5;
1493 +            }
1494 +            else
1495 +                Thread.yield();              // yield if no alternatives
1496          }
1497 <        return q;
1497 >    }
1498 >
1499 >    /**
1500 >     * Submits the given (non-null) task to the common pool, if possible.
1501 >     */
1502 >    static void submitToCommonPool(ForkJoinTask<?> task) {
1503 >        ForkJoinPool p;
1504 >        if ((p = commonPool) == null)
1505 >            throw new RejectedExecutionException("Common Pool Unavailable");
1506 >        p.doSubmit(task);
1507 >    }
1508 >
1509 >    /**
1510 >     * Returns true if the given task was submitted to common pool
1511 >     * and has not yet commenced execution, and is available for
1512 >     * removal according to execution policies; if so removing the
1513 >     * submission from the pool.
1514 >     *
1515 >     * @param task the task
1516 >     * @return true if successful
1517 >     */
1518 >    static boolean tryUnsubmitFromCommonPool(ForkJoinTask<?> task) {
1519 >        // Peek, looking for task and eligibility before
1520 >        // using trySharedUnpush to actually take it under lock
1521 >        ForkJoinPool p; WorkQueue[] ws; WorkQueue q;
1522 >        ForkJoinTask<?>[] a; int t, s, n;
1523 >        int k = submitters.get().seed & SQMASK;
1524 >        return ((p = commonPool) != null &&
1525 >                (ws = p.workQueues) != null &&
1526 >                ws.length > (k &= p.submitMask) &&
1527 >                (q = ws[k]) != null &&
1528 >                (a = q.array) != null &&
1529 >                (n = (t = q.top) - q.base) > 0 &&
1530 >                (n > 1 || (int)(p.ctl >> AC_SHIFT) < 0) &&
1531 >                (s = t - 1) >= 0 && s < a.length && a[s] == task &&
1532 >                q.trySharedUnpush(task));
1533      }
1534  
1535      // Maintaining ctl counts
# Line 1294 | Line 1543 | public class ForkJoinPool extends Abstra
1543      }
1544  
1545      /**
1546 <     * Activates or creates a worker.
1546 >     * Tries to create one or activate one or more workers if too few are active.
1547       */
1548      final void signalWork() {
1549 <        /*
1550 <         * The while condition is true if: (there is are too few total
1551 <         * workers OR there is at least one waiter) AND (there are too
1552 <         * few active workers OR the pool is terminating).  The value
1553 <         * of e distinguishes the remaining cases: zero (no waiters)
1554 <         * for create, negative if terminating (in which case do
1555 <         * nothing), else release a waiter. The secondary checks for
1556 <         * release (non-null array etc) can fail if the pool begins
1557 <         * terminating after the test, and don't impose any added cost
1558 <         * because JVMs must perform null and bounds checks anyway.
1559 <         */
1560 <        long c; int e, u;
1561 <        while ((((e = (int)(c = ctl)) | (u = (int)(c >>> 32))) &
1562 <                (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;
1549 >        long c; int u;
1550 >        while ((u = (int)((c = ctl) >>> 32)) < 0) {     // too few active
1551 >            WorkQueue[] ws = workQueues; int e, i; WorkQueue w; Thread p;
1552 >            if ((e = (int)c) > 0) {                     // at least one waiting
1553 >                if (ws != null && (i = e & SMASK) < ws.length &&
1554 >                    (w = ws[i]) != null && w.eventCount == (e | INT_SIGN)) {
1555 >                    long nc = (((long)(w.nextWait & E_MASK)) |
1556 >                               ((long)(u + UAC_UNIT) << 32));
1557 >                    if (U.compareAndSwapLong(this, CTL, c, nc)) {
1558 >                        w.eventCount = (e + E_SEQ) & E_MASK;
1559 >                        if ((p = w.parker) != null)
1560 >                            U.unpark(p);                // activate and release
1561 >                        break;
1562 >                    }
1563                  }
1564 <            }
1323 <            else if (e > 0 && ws != null &&
1324 <                     (i = ((~e << 1) | 1) & SMASK) < ws.length &&
1325 <                     (w = ws[i]) != null &&
1326 <                     w.eventCount == (e | INT_SIGN)) {
1327 <                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
1564 >                else
1565                      break;
1334                }
1335            }
1336            else
1337                break;
1338        }
1339    }
1340
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
1566              }
1567 <            else if (tc + pc < MAX_ID) {
1568 <                long nc = ((c + TC_UNIT) & TC_MASK) | (c & ~TC_MASK);
1567 >            else if (e == 0 && (u & SHORT_SIGN) != 0) { // too few total
1568 >                long nc = (long)(((u + UTC_UNIT) & UTC_MASK) |
1569 >                                 ((u + UAC_UNIT) & UAC_MASK)) << 32;
1570                  if (U.compareAndSwapLong(this, CTL, c, nc)) {
1571                      addWorker();
1572 <                    return true;             // create replacement
1572 >                    break;
1573                  }
1574              }
1575 +            else
1576 +                break;
1577          }
1381        return false;
1578      }
1579  
1580 <    // Submissions
1580 >    // Scanning for tasks
1581  
1582      /**
1583 <     * 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.
1583 >     * Top-level runloop for workers, called by ForkJoinWorkerThread.run.
1584       */
1585 <    private void doSubmit(ForkJoinTask<?> task) {
1586 <        if (task == null)
1587 <            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 <        }
1585 >    final void runWorker(WorkQueue w) {
1586 >        w.growArray(false);         // initialize queue array in this thread
1587 >        do { w.runTask(scan(w)); } while (w.runState >= 0);
1588      }
1589  
1416
1417    // Scanning for tasks
1418
1590      /**
1591       * Scans for and, if found, returns one task, else possibly
1592       * inactivates the worker. This method operates on single reads of
1593 <     * volatile state and is designed to be re-invoked continuously in
1594 <     * part because it returns upon detecting inconsistencies,
1593 >     * volatile state and is designed to be re-invoked continuously,
1594 >     * in part because it returns upon detecting inconsistencies,
1595       * contention, or state changes that indicate possible success on
1596       * re-invocation.
1597       *
1598 <     * The scan searches for tasks across queues, randomly selecting
1599 <     * the first #queues probes, favoring steals 2:1 over submissions
1600 <     * (by exploiting even/odd indexing), and then performing a
1601 <     * circular sweep of all queues.  The scan terminates upon either
1602 <     * finding a non-empty queue, or completing a full sweep. If the
1603 <     * worker is not inactivated, it takes and returns a task from
1604 <     * this queue.  On failure to find a task, we take one of the
1605 <     * following actions, after which the caller will retry calling
1606 <     * this method unless terminated.
1598 >     * The scan searches for tasks across a random permutation of
1599 >     * queues (starting at a random index and stepping by a random
1600 >     * relative prime, checking each at least once).  The scan
1601 >     * terminates upon either finding a non-empty queue, or completing
1602 >     * the sweep. If the worker is not inactivated, it takes and
1603 >     * returns a task from this queue.  On failure to find a task, we
1604 >     * take one of the following actions, after which the caller will
1605 >     * retry calling this method unless terminated.
1606 >     *
1607 >     * * If pool is terminating, terminate the worker.
1608       *
1609       * * If not a complete sweep, try to release a waiting worker.  If
1610       * the scan terminated because the worker is inactivated, then the
# Line 1441 | Line 1613 | public class ForkJoinPool extends Abstra
1613       * another worker, but with same net effect. Releasing in other
1614       * cases as well ensures that we have enough workers running.
1615       *
1444     * * If the caller has run a task since 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     *
1616       * * If not already enqueued, try to inactivate and enqueue the
1617 <     * worker on wait queue.
1617 >     * worker on wait queue. Or, if inactivating has caused the pool
1618 >     * to be quiescent, relay to idleAwaitWork to check for
1619 >     * termination and possibly shrink pool.
1620 >     *
1621 >     * * If already inactive, and the caller has run a task since the
1622 >     * last empty scan, return (to allow rescan) unless others are
1623 >     * also inactivated.  Field WorkQueue.rescans counts down on each
1624 >     * scan to ensure eventual inactivation and blocking.
1625       *
1626 <     * * If already enqueued and none of the above apply, either park
1627 <     * 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.
1626 >     * * If already enqueued and none of the above apply, park
1627 >     * awaiting signal,
1628       *
1629       * @param w the worker (via its WorkQueue)
1630 <     * @return a task or null of none found
1630 >     * @return a task or null if none found
1631       */
1632      private final ForkJoinTask<?> scan(WorkQueue w) {
1633 <        boolean swept = false;                 // true after full empty scan
1634 <        WorkQueue[] ws;                        // volatile read order matters
1635 <        int r = w.seed, ec = w.eventCount;     // ec is negative if inactive
1636 <        int rs = runState, m = rs & SMASK;
1637 <        if ((ws = workQueues) != null && ws.length > m) {
1638 <            ForkJoinTask<?> task = null;
1639 <            for (int k = 0, j = -2 - m; ; ++j) {
1640 <                WorkQueue q; int b;
1641 <                if (j < 0) {                   // random probes while j negative
1642 <                    r ^= r << 13; r ^= r >>> 17; k = (r ^= r << 5) | (j & 1);
1643 <                }                              // worker (not submit) for odd j
1644 <                else                           // cyclic scan when j >= 0
1645 <                    k += (m >>> 1) | 1;        // step by half to reduce bias
1646 <
1647 <                if ((q = ws[k & m]) != null && (b = q.base) - q.top < 0) {
1648 <                    if (ec >= 0)
1649 <                        task = q.pollAt(b);    // steal
1650 <                    break;
1633 >        WorkQueue[] ws;                       // first update random seed
1634 >        int r = w.seed; r ^= r << 13; r ^= r >>> 17; w.seed = r ^= r << 5;
1635 >        int rs = runState, m;                 // volatile read order matters
1636 >        if ((ws = workQueues) != null && (m = ws.length - 1) > 0) {
1637 >            int ec = w.eventCount;            // ec is negative if inactive
1638 >            int step = (r >>> 16) | 1;        // relative prime
1639 >            for (int j = (m + 1) << 2; ; r += step) {
1640 >                WorkQueue q; ForkJoinTask<?> t; ForkJoinTask<?>[] a; int b;
1641 >                if ((q = ws[r & m]) != null && (b = q.base) - q.top < 0 &&
1642 >                    (a = q.array) != null) {  // probably nonempty
1643 >                    int i = (((a.length - 1) & b) << ASHIFT) + ABASE;
1644 >                    t = (ForkJoinTask<?>)U.getObjectVolatile(a, i);
1645 >                    if (q.base == b && ec >= 0 && t != null &&
1646 >                        U.compareAndSwapObject(a, i, t, null)) {
1647 >                        if (q.top - (q.base = b + 1) > 0)
1648 >                            signalWork();    // help pushes signal
1649 >                        return t;
1650 >                    }
1651 >                    else if (ec < 0 || j <= m) {
1652 >                        rs = 0;               // mark scan as imcomplete
1653 >                        break;                // caller can retry after release
1654 >                    }
1655                  }
1656 <                else if (j > m) {
1485 <                    if (rs == runState)        // staleness check
1486 <                        swept = true;
1656 >                if (--j < 0)
1657                      break;
1658 +            }
1659 +
1660 +            long c = ctl; int e = (int)c, a = (int)(c >> AC_SHIFT), nr, ns;
1661 +            if (e < 0)                        // decode ctl on empty scan
1662 +                w.runState = -1;              // pool is terminating
1663 +            else if (rs == 0 || rs != runState) { // incomplete scan
1664 +                WorkQueue v; Thread p;        // try to release a waiter
1665 +                if (e > 0 && a < 0 && w.eventCount == ec &&
1666 +                    (v = ws[e & m]) != null && v.eventCount == (e | INT_SIGN)) {
1667 +                    long nc = ((long)(v.nextWait & E_MASK) |
1668 +                               ((c + AC_UNIT) & (AC_MASK|TC_MASK)));
1669 +                    if (ctl == c && U.compareAndSwapLong(this, CTL, c, nc)) {
1670 +                        v.eventCount = (e + E_SEQ) & E_MASK;
1671 +                        if ((p = v.parker) != null)
1672 +                            U.unpark(p);
1673 +                    }
1674                  }
1675              }
1676 <            w.seed = r;                        // save seed for next scan
1677 <            if (task != null)
1678 <                return task;
1679 <        }
1680 <
1681 <        // Decode ctl on empty scan
1682 <        long c = ctl; int e = (int)c, a = (int)(c >> AC_SHIFT), nr, ns;
1683 <        if (!swept) {                          // try to release a waiter
1684 <            WorkQueue v; Thread p;
1685 <            if (e > 0 && a < 0 && ws != null &&
1686 <                (v = ws[((~e << 1) | 1) & m]) != null &&
1687 <                v.eventCount == (e | INT_SIGN) && U.compareAndSwapLong
1688 <                (this, CTL, c, ((long)(v.nextWait & E_MASK) |
1689 <                                ((c + AC_UNIT) & (AC_MASK|TC_MASK))))) {
1690 <                v.eventCount = (e + E_SEQ) & E_MASK;
1691 <                if ((p = v.parker) != null)
1692 <                    U.unpark(p);
1693 <            }
1694 <        }
1695 <        else if ((nr = w.rescans) > 0) {       // continue rescanning
1696 <            int ac = a + parallelism;
1697 <            if ((w.rescans = (ac < nr) ? ac : nr - 1) > 0 && w.seed < 0 &&
1698 <                w.eventCount == ec)
1699 <                Thread.yield();                // 1 bit randomness for yield call
1700 <        }
1701 <        else if (e < 0)                        // pool is terminating
1702 <            w.runState = -1;
1703 <        else if (ec >= 0) {                    // try to enqueue
1704 <            long nc = (long)ec | ((c - AC_UNIT) & (AC_MASK|TC_MASK));
1705 <            w.nextWait = e;
1520 <            w.eventCount = ec | INT_SIGN;      // mark as inactive
1521 <            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);
1676 >            else if (ec >= 0) {               // try to enqueue/inactivate
1677 >                long nc = (long)ec | ((c - AC_UNIT) & (AC_MASK|TC_MASK));
1678 >                w.nextWait = e;
1679 >                w.eventCount = ec | INT_SIGN; // mark as inactive
1680 >                if (ctl != c || !U.compareAndSwapLong(this, CTL, c, nc))
1681 >                    w.eventCount = ec;        // unmark on CAS failure
1682 >                else {
1683 >                    if ((ns = w.nsteals) != 0) {
1684 >                        w.nsteals = 0;        // set rescans if ran task
1685 >                        w.rescans = (a > 0) ? 0 : a + parallelism;
1686 >                        w.totalSteals += ns;
1687 >                    }
1688 >                    if (a == 1 - parallelism) // quiescent
1689 >                        idleAwaitWork(w, nc, c);
1690 >                }
1691 >            }
1692 >            else if (w.eventCount < 0) {      // already queued
1693 >                int ac = a + parallelism;
1694 >                if ((nr = w.rescans) > 0)     // continue rescanning
1695 >                    w.rescans = (ac < nr) ? ac : nr - 1;
1696 >                else if (((w.seed >>> 16) & ac) == 0) { // randomize park
1697 >                    Thread.interrupted();     // clear status
1698 >                    Thread wt = Thread.currentThread();
1699 >                    U.putObject(wt, PARKBLOCKER, this);
1700 >                    w.parker = wt;            // emulate LockSupport.park
1701 >                    if (w.eventCount < 0)     // recheck
1702 >                        U.park(false, 0L);
1703 >                    w.parker = null;
1704 >                    U.putObject(wt, PARKBLOCKER, null);
1705 >                }
1706              }
1707          }
1708          return null;
1709      }
1710  
1711      /**
1712 <     * If inactivating worker w has caused pool to become quiescent,
1713 <     * checks for pool termination, and, so long as this is not the
1714 <     * only worker, waits for event for up to SHRINK_RATE nanosecs.
1715 <     * On timeout, if ctl has not changed, terminates the worker,
1716 <     * which will in turn wake up another worker to possibly repeat
1717 <     * this process.
1712 >     * If inactivating worker w has caused the pool to become
1713 >     * quiescent, checks for pool termination, and, so long as this is
1714 >     * not the only worker, waits for event for up to a given
1715 >     * duration.  On timeout, if ctl has not changed, terminates the
1716 >     * worker, which will in turn wake up another worker to possibly
1717 >     * repeat this process.
1718       *
1719       * @param w the calling worker
1720 +     * @param currentCtl the ctl value triggering possible quiescence
1721 +     * @param prevCtl the ctl value to restore if thread is terminated
1722       */
1723 <    private void idleAwaitWork(WorkQueue w) {
1724 <        long c; int nw, ec;
1725 <        if (!tryTerminate(false) &&
1726 <            (int)((c = ctl) >> AC_SHIFT) + parallelism == 0 &&
1727 <            (ec = w.eventCount) == ((int)c | INT_SIGN) &&
1728 <            (nw = w.nextWait) != 0) {
1729 <            long nc = ((long)(nw & E_MASK) | // ctl to restore on timeout
1730 <                       ((c + AC_UNIT) & AC_MASK) | (c & TC_MASK));
1565 <            ForkJoinTask.helpExpungeStaleExceptions(); // help clean
1566 <            ForkJoinWorkerThread wt = w.owner;
1567 <            while (ctl == c) {
1568 <                long startTime = System.nanoTime();
1723 >    private void idleAwaitWork(WorkQueue w, long currentCtl, long prevCtl) {
1724 >        if (w.eventCount < 0 && !tryTerminate(false, false) &&
1725 >            (int)prevCtl != 0 && !hasQueuedSubmissions() && ctl == currentCtl) {
1726 >            int dc = -(short)(currentCtl >>> TC_SHIFT);
1727 >            long parkTime = dc < 0 ? FAST_IDLE_TIMEOUT: (dc + 1) * IDLE_TIMEOUT;
1728 >            long deadline = System.nanoTime() + parkTime - 100000L; // 1ms slop
1729 >            Thread wt = Thread.currentThread();
1730 >            while (ctl == currentCtl) {
1731                  Thread.interrupted();  // timed variant of version in scan()
1732                  U.putObject(wt, PARKBLOCKER, this);
1733                  w.parker = wt;
1734 <                if (ctl == c)
1735 <                    U.park(false, SHRINK_RATE);
1734 >                if (ctl == currentCtl)
1735 >                    U.park(false, parkTime);
1736                  w.parker = null;
1737                  U.putObject(wt, PARKBLOCKER, null);
1738 <                if (ctl != c)
1738 >                if (ctl != currentCtl)
1739                      break;
1740 <                if (System.nanoTime() - startTime >= SHRINK_TIMEOUT &&
1741 <                    U.compareAndSwapLong(this, CTL, c, nc)) {
1742 <                    w.runState = -1;          // shrink
1743 <                    w.eventCount = (ec + E_SEQ) | E_MASK;
1740 >                if (deadline - System.nanoTime() <= 0L &&
1741 >                    U.compareAndSwapLong(this, CTL, currentCtl, prevCtl)) {
1742 >                    w.eventCount = (w.eventCount + E_SEQ) | E_MASK;
1743 >                    w.runState = -1;   // shrink
1744                      break;
1745                  }
1746              }
# Line 1596 | Line 1758 | public class ForkJoinPool extends Abstra
1758       * leaves hints in workers to speed up subsequent calls. The
1759       * implementation is very branchy to cope with potential
1760       * inconsistencies or loops encountering chains that are stale,
1761 <     * unknown, or of length greater than MAX_HELP_DEPTH links.  All
1600 <     * of these cases are dealt with by just retrying by caller.
1761 >     * unknown, or so long that they are likely cyclic.
1762       *
1763       * @param joiner the joining worker
1764       * @param task the task to join
1765 <     * @return true if found or ran a task (and so is immediately retryable)
1765 >     * @return 0 if no progress can be made, negative if task
1766 >     * known complete, else positive
1767       */
1768 <    final boolean tryHelpStealer(WorkQueue joiner, ForkJoinTask<?> task) {
1769 <        ForkJoinTask<?> subtask;    // current target
1770 <        boolean progress = false;
1771 <        int depth = 0;              // current chain depth
1772 <        int m = runState & SMASK;
1773 <        WorkQueue[] ws = workQueues;
1774 <
1775 <        if (ws != null && ws.length > m && (subtask = task).status >= 0) {
1776 <            outer:for (WorkQueue j = joiner;;) {
1777 <                // Try to find the stealer of subtask, by first using hint
1616 <                WorkQueue stealer = null;
1617 <                WorkQueue v = ws[j.stealHint & m];
1618 <                if (v != null && v.currentSteal == subtask)
1619 <                    stealer = v;
1620 <                else {
1621 <                    for (int i = 1; i <= m; i += 2) {
1622 <                        if ((v = ws[i]) != null && v.currentSteal == subtask) {
1623 <                            stealer = v;
1624 <                            j.stealHint = i; // save hint
1625 <                            break;
1626 <                        }
1768 >    private int tryHelpStealer(WorkQueue joiner, ForkJoinTask<?> task) {
1769 >        int stat = 0, steps = 0;                    // bound to avoid cycles
1770 >        if (joiner != null && task != null) {       // hoist null checks
1771 >            restart: for (;;) {
1772 >                ForkJoinTask<?> subtask = task;     // current target
1773 >                for (WorkQueue j = joiner, v;;) {   // v is stealer of subtask
1774 >                    WorkQueue[] ws; int m, s, h;
1775 >                    if ((s = task.status) < 0) {
1776 >                        stat = s;
1777 >                        break restart;
1778                      }
1779 <                    if (stealer == null)
1780 <                        break;
1781 <                }
1782 <
1783 <                for (WorkQueue q = stealer;;) { // Try to help stealer
1784 <                    ForkJoinTask<?> t; int b;
1785 <                    if (task.status < 0)
1786 <                        break outer;
1787 <                    if ((b = q.base) - q.top < 0) {
1788 <                        progress = true;
1789 <                        if (subtask.status < 0)
1790 <                            break outer;               // stale
1791 <                        if ((t = q.pollAt(b)) != null) {
1792 <                            stealer.stealHint = joiner.poolIndex;
1793 <                            joiner.runSubtask(t);
1779 >                    if ((ws = workQueues) == null || (m = ws.length - 1) <= 0)
1780 >                        break restart;              // shutting down
1781 >                    if ((v = ws[h = (j.stealHint | 1) & m]) == null ||
1782 >                        v.currentSteal != subtask) {
1783 >                        for (int origin = h;;) {    // find stealer
1784 >                            if (((h = (h + 2) & m) & 15) == 1 &&
1785 >                                (subtask.status < 0 || j.currentJoin != subtask))
1786 >                                continue restart;   // occasional staleness check
1787 >                            if ((v = ws[h]) != null &&
1788 >                                v.currentSteal == subtask) {
1789 >                                j.stealHint = h;    // save hint
1790 >                                break;
1791 >                            }
1792 >                            if (h == origin)
1793 >                                break restart;      // cannot find stealer
1794                          }
1795                      }
1796 <                    else { // empty - try to descend to find stealer's stealer
1797 <                        ForkJoinTask<?> next = stealer.currentJoin;
1798 <                        if (++depth == MAX_HELP_DEPTH || subtask.status < 0 ||
1799 <                            next == null || next == subtask)
1800 <                            break outer;  // max depth, stale, dead-end, cyclic
1801 <                        subtask = next;
1802 <                        j = stealer;
1803 <                        break;
1796 >                    for (;;) { // help stealer or descend to its stealer
1797 >                        ForkJoinTask[] a;  int b;
1798 >                        if (subtask.status < 0)     // surround probes with
1799 >                            continue restart;       //   consistency checks
1800 >                        if ((b = v.base) - v.top < 0 && (a = v.array) != null) {
1801 >                            int i = (((a.length - 1) & b) << ASHIFT) + ABASE;
1802 >                            ForkJoinTask<?> t =
1803 >                                (ForkJoinTask<?>)U.getObjectVolatile(a, i);
1804 >                            if (subtask.status < 0 || j.currentJoin != subtask ||
1805 >                                v.currentSteal != subtask)
1806 >                                continue restart;   // stale
1807 >                            stat = 1;               // apparent progress
1808 >                            if (t != null && v.base == b &&
1809 >                                U.compareAndSwapObject(a, i, t, null)) {
1810 >                                v.base = b + 1;     // help stealer
1811 >                                joiner.runSubtask(t);
1812 >                            }
1813 >                            else if (v.base == b && ++steps == MAX_HELP)
1814 >                                break restart;      // v apparently stalled
1815 >                        }
1816 >                        else {                      // empty -- try to descend
1817 >                            ForkJoinTask<?> next = v.currentJoin;
1818 >                            if (subtask.status < 0 || j.currentJoin != subtask ||
1819 >                                v.currentSteal != subtask)
1820 >                                continue restart;   // stale
1821 >                            else if (next == null || ++steps == MAX_HELP)
1822 >                                break restart;      // dead-end or maybe cyclic
1823 >                            else {
1824 >                                subtask = next;
1825 >                                j = v;
1826 >                                break;
1827 >                            }
1828 >                        }
1829                      }
1830                  }
1831              }
1832          }
1833 <        return progress;
1833 >        return stat;
1834      }
1835  
1836      /**
# Line 1663 | Line 1839 | public class ForkJoinPool extends Abstra
1839       * @param joiner the joining worker
1840       * @param task the task
1841       */
1842 <    final void tryPollForAndExec(WorkQueue joiner, ForkJoinTask<?> task) {
1842 >    private void tryPollForAndExec(WorkQueue joiner, ForkJoinTask<?> task) {
1843          WorkQueue[] ws;
1844 <        int m = runState & SMASK;
1845 <        if ((ws = workQueues) != null && ws.length > m) {
1670 <            for (int j = 1; j <= m && task.status >= 0; j += 2) {
1844 >        if ((ws = workQueues) != null) {
1845 >            for (int j = 1; j < ws.length && task.status >= 0; j += 2) {
1846                  WorkQueue q = ws[j];
1847                  if (q != null && q.pollFor(task)) {
1848                      joiner.runSubtask(task);
# Line 1678 | Line 1853 | public class ForkJoinPool extends Abstra
1853      }
1854  
1855      /**
1856 <     * Returns a non-empty steal queue, if one is found during a random,
1857 <     * then cyclic scan, else null.  This method must be retried by
1858 <     * caller if, by the time it tries to use the queue, it is empty.
1856 >     * Tries to decrement active count (sometimes implicitly) and
1857 >     * possibly release or create a compensating worker in preparation
1858 >     * for blocking. Fails on contention or termination. Otherwise,
1859 >     * adds a new thread if no idle workers are available and either
1860 >     * pool would become completely starved or: (at least half
1861 >     * starved, and fewer than 50% spares exist, and there is at least
1862 >     * one task apparently available). Even though the availability
1863 >     * check requires a full scan, it is worthwhile in reducing false
1864 >     * alarms.
1865 >     *
1866 >     * @param task if non-null, a task being waited for
1867 >     * @param blocker if non-null, a blocker being waited for
1868 >     * @return true if the caller can block, else should recheck and retry
1869 >     */
1870 >    final boolean tryCompensate(ForkJoinTask<?> task, ManagedBlocker blocker) {
1871 >        int pc = parallelism, e;
1872 >        long c = ctl;
1873 >        WorkQueue[] ws = workQueues;
1874 >        if ((e = (int)c) >= 0 && ws != null) {
1875 >            int u, a, ac, hc;
1876 >            int tc = (short)((u = (int)(c >>> 32)) >>> UTC_SHIFT) + pc;
1877 >            boolean replace = false;
1878 >            if ((a = u >> UAC_SHIFT) <= 0) {
1879 >                if ((ac = a + pc) <= 1)
1880 >                    replace = true;
1881 >                else if ((e > 0 || (task != null &&
1882 >                                    ac <= (hc = pc >>> 1) && tc < pc + hc))) {
1883 >                    WorkQueue w;
1884 >                    for (int j = 0; j < ws.length; ++j) {
1885 >                        if ((w = ws[j]) != null && !w.isEmpty()) {
1886 >                            replace = true;
1887 >                            break;   // in compensation range and tasks available
1888 >                        }
1889 >                    }
1890 >                }
1891 >            }
1892 >            if ((task == null || task.status >= 0) && // recheck need to block
1893 >                (blocker == null || !blocker.isReleasable()) && ctl == c) {
1894 >                if (!replace) {          // no compensation
1895 >                    long nc = ((c - AC_UNIT) & AC_MASK) | (c & ~AC_MASK);
1896 >                    if (U.compareAndSwapLong(this, CTL, c, nc))
1897 >                        return true;
1898 >                }
1899 >                else if (e != 0) {       // release an idle worker
1900 >                    WorkQueue w; Thread p; int i;
1901 >                    if ((i = e & SMASK) < ws.length && (w = ws[i]) != null) {
1902 >                        long nc = ((long)(w.nextWait & E_MASK) |
1903 >                                   (c & (AC_MASK|TC_MASK)));
1904 >                        if (w.eventCount == (e | INT_SIGN) &&
1905 >                            U.compareAndSwapLong(this, CTL, c, nc)) {
1906 >                            w.eventCount = (e + E_SEQ) & E_MASK;
1907 >                            if ((p = w.parker) != null)
1908 >                                U.unpark(p);
1909 >                            return true;
1910 >                        }
1911 >                    }
1912 >                }
1913 >                else if (tc < MAX_CAP) { // create replacement
1914 >                    long nc = ((c + TC_UNIT) & TC_MASK) | (c & ~TC_MASK);
1915 >                    if (U.compareAndSwapLong(this, CTL, c, nc)) {
1916 >                        addWorker();
1917 >                        return true;
1918 >                    }
1919 >                }
1920 >            }
1921 >        }
1922 >        return false;
1923 >    }
1924 >
1925 >    /**
1926 >     * Helps and/or blocks until the given task is done.
1927 >     *
1928 >     * @param joiner the joining worker
1929 >     * @param task the task
1930 >     * @return task status on exit
1931 >     */
1932 >    final int awaitJoin(WorkQueue joiner, ForkJoinTask<?> task) {
1933 >        int s;
1934 >        if ((s = task.status) >= 0) {
1935 >            ForkJoinTask<?> prevJoin = joiner.currentJoin;
1936 >            joiner.currentJoin = task;
1937 >            long startTime = 0L;
1938 >            for (int k = 0;;) {
1939 >                if ((s = (joiner.isEmpty() ?           // try to help
1940 >                          tryHelpStealer(joiner, task) :
1941 >                          joiner.tryRemoveAndExec(task))) == 0 &&
1942 >                    (s = task.status) >= 0) {
1943 >                    if (k == 0) {
1944 >                        startTime = System.nanoTime();
1945 >                        tryPollForAndExec(joiner, task); // check uncommon case
1946 >                    }
1947 >                    else if ((k & (MAX_HELP - 1)) == 0 &&
1948 >                             System.nanoTime() - startTime >=
1949 >                             COMPENSATION_DELAY &&
1950 >                             tryCompensate(task, null)) {
1951 >                        if (task.trySetSignal()) {
1952 >                            synchronized (task) {
1953 >                                if (task.status >= 0) {
1954 >                                    try {                // see ForkJoinTask
1955 >                                        task.wait();     //  for explanation
1956 >                                    } catch (InterruptedException ie) {
1957 >                                    }
1958 >                                }
1959 >                                else
1960 >                                    task.notifyAll();
1961 >                            }
1962 >                        }
1963 >                        long c;                          // re-activate
1964 >                        do {} while (!U.compareAndSwapLong
1965 >                                     (this, CTL, c = ctl, c + AC_UNIT));
1966 >                    }
1967 >                }
1968 >                if (s < 0 || (s = task.status) < 0) {
1969 >                    joiner.currentJoin = prevJoin;
1970 >                    break;
1971 >                }
1972 >                else if ((k++ & (MAX_HELP - 1)) == MAX_HELP >>> 1)
1973 >                    Thread.yield();                     // for politeness
1974 >            }
1975 >        }
1976 >        return s;
1977 >    }
1978 >
1979 >    /**
1980 >     * Stripped-down variant of awaitJoin used by timed joins. Tries
1981 >     * to help join only while there is continuous progress. (Caller
1982 >     * will then enter a timed wait.)
1983 >     *
1984 >     * @param joiner the joining worker
1985 >     * @param task the task
1986 >     * @return task status on exit
1987 >     */
1988 >    final int helpJoinOnce(WorkQueue joiner, ForkJoinTask<?> task) {
1989 >        int s;
1990 >        while ((s = task.status) >= 0 &&
1991 >               (joiner.isEmpty() ?
1992 >                tryHelpStealer(joiner, task) :
1993 >                joiner.tryRemoveAndExec(task)) != 0)
1994 >            ;
1995 >        return s;
1996 >    }
1997 >
1998 >    /**
1999 >     * Returns a (probably) non-empty steal queue, if one is found
2000 >     * during a random, then cyclic scan, else null.  This method must
2001 >     * be retried by caller if, by the time it tries to use the queue,
2002 >     * it is empty.
2003       */
2004      private WorkQueue findNonEmptyStealQueue(WorkQueue w) {
2005 <        int r = w.seed;    // Same idea as scan(), but ignoring submissions
2005 >        // Similar to loop in scan(), but ignoring submissions
2006 >        int r = w.seed; r ^= r << 13; r ^= r >>> 17; w.seed = r ^= r << 5;
2007 >        int step = (r >>> 16) | 1;
2008          for (WorkQueue[] ws;;) {
2009 <            int m = runState & SMASK;
2010 <            if ((ws = workQueues) == null)
2009 >            int rs = runState, m;
2010 >            if ((ws = workQueues) == null || (m = ws.length - 1) < 1)
2011                  return null;
2012 <            if (ws.length > m) {
2013 <                WorkQueue q;
2014 <                for (int n = m << 2, k = r, j = -n;;) {
2015 <                    r ^= r << 13; r ^= r >>> 17; r ^= r << 5;
2016 <                    if ((q = ws[(k | 1) & m]) != null && q.base - q.top < 0) {
2017 <                        w.seed = r;
1697 <                        return q;
1698 <                    }
1699 <                    else if (j > n)
2012 >            for (int j = (m + 1) << 2; ; r += step) {
2013 >                WorkQueue q = ws[((r << 1) | 1) & m];
2014 >                if (q != null && !q.isEmpty())
2015 >                    return q;
2016 >                else if (--j < 0) {
2017 >                    if (runState == rs)
2018                          return null;
2019 <                    else
1702 <                        k = (j++ < 0) ? r : k + ((m >>> 1) | 1);
1703 <
2019 >                    break;
2020                  }
2021              }
2022          }
# Line 1714 | Line 2030 | public class ForkJoinPool extends Abstra
2030       */
2031      final void helpQuiescePool(WorkQueue w) {
2032          for (boolean active = true;;) {
2033 <            w.runLocalTasks();      // exhaust local queue
2033 >            ForkJoinTask<?> localTask; // exhaust local queue
2034 >            while ((localTask = w.nextLocalTask()) != null)
2035 >                localTask.doExec();
2036              WorkQueue q = findNonEmptyStealQueue(w);
2037              if (q != null) {
2038 <                ForkJoinTask<?> t;
2038 >                ForkJoinTask<?> t; int b;
2039                  if (!active) {      // re-establish active count
2040                      long c;
2041                      active = true;
2042                      do {} while (!U.compareAndSwapLong
2043                                   (this, CTL, c = ctl, c + AC_UNIT));
2044                  }
2045 <                if ((t = q.poll()) != null)
2045 >                if ((b = q.base) - q.top < 0 && (t = q.pollAt(b)) != null)
2046                      w.runSubtask(t);
2047              }
2048              else {
# Line 1746 | Line 2064 | public class ForkJoinPool extends Abstra
2064      }
2065  
2066      /**
2067 +     * Restricted version of helpQuiescePool for non-FJ callers
2068 +     */
2069 +    static void externalHelpQuiescePool() {
2070 +        ForkJoinPool p; WorkQueue[] ws; WorkQueue w, q;
2071 +        ForkJoinTask<?> t; int b;
2072 +        int k = submitters.get().seed & SQMASK;
2073 +        if ((p = commonPool) != null &&
2074 +            (ws = p.workQueues) != null &&
2075 +            ws.length > (k &= p.submitMask) &&
2076 +            (w = ws[k]) != null &&
2077 +            (q = p.findNonEmptyStealQueue(w)) != null &&
2078 +            (b = q.base) - q.top < 0 &&
2079 +            (t = q.pollAt(b)) != null)
2080 +            t.doExec();
2081 +    }
2082 +
2083 +    /**
2084       * Gets and removes a local or stolen task for the given worker.
2085       *
2086       * @return a task, if available
2087       */
2088      final ForkJoinTask<?> nextTaskFor(WorkQueue w) {
2089          for (ForkJoinTask<?> t;;) {
2090 <            WorkQueue q;
2090 >            WorkQueue q; int b;
2091              if ((t = w.nextLocalTask()) != null)
2092                  return t;
2093              if ((q = findNonEmptyStealQueue(w)) == null)
2094                  return null;
2095 <            if ((t = q.poll()) != null)
2095 >            if ((b = q.base) - q.top < 0 && (t = q.pollAt(b)) != null)
2096                  return t;
2097          }
2098      }
# Line 1778 | Line 2113 | public class ForkJoinPool extends Abstra
2113                  8);
2114      }
2115  
1781    // Termination
1782
2116      /**
2117 <     * Sets SHUTDOWN bit of runState under lock
2117 >     * Returns approximate submission queue length for the given caller
2118       */
2119 <    private void enableShutdown() {
2120 <        ReentrantLock lock = this.lock;
2121 <        if (runState >= 0) {
2122 <            lock.lock();                       // don't need try/finally
2123 <            runState |= SHUTDOWN;
2124 <            lock.unlock();
2125 <        }
2119 >    static int getEstimatedSubmitterQueueLength() {
2120 >        ForkJoinPool p; WorkQueue[] ws; WorkQueue q;
2121 >        int k = submitters.get().seed & SQMASK;
2122 >        return ((p = commonPool) != null &&
2123 >                p.runState >= 0 &&
2124 >                (ws = p.workQueues) != null &&
2125 >                ws.length > (k &= p.submitMask) &&
2126 >                (q = ws[k]) != null) ?
2127 >            q.queueSize() : 0;
2128      }
2129  
2130 +    //  Termination
2131 +
2132      /**
2133 <     * Possibly initiates and/or completes termination.  Upon
2134 <     * termination, cancels all queued tasks and then
2133 >     * Possibly initiates and/or completes termination.  The caller
2134 >     * triggering termination runs three passes through workQueues:
2135 >     * (0) Setting termination status, followed by wakeups of queued
2136 >     * workers; (1) cancelling all tasks; (2) interrupting lagging
2137 >     * threads (likely in external tasks, but possibly also blocked in
2138 >     * joins).  Each pass repeats previous steps because of potential
2139 >     * lagging thread creation.
2140       *
2141       * @param now if true, unconditionally terminate, else only
2142       * if no work and no active workers
2143 +     * @param enable if true, enable shutdown when next possible
2144       * @return true if now terminating or terminated
2145       */
2146 <    private boolean tryTerminate(boolean now) {
2146 >    private boolean tryTerminate(boolean now, boolean enable) {
2147          for (long c;;) {
2148              if (((c = ctl) & STOP_BIT) != 0) {      // already terminating
2149                  if ((short)(c >>> TC_SHIFT) == -parallelism) {
2150 <                    ReentrantLock lock = this.lock; // signal when no workers
2151 <                    lock.lock();                    // don't need try/finally
2152 <                    termination.signalAll();        // signal when 0 workers
1810 <                    lock.unlock();
2150 >                    synchronized(this) {
2151 >                        notifyAll();                // signal when 0 workers
2152 >                    }
2153                  }
2154                  return true;
2155              }
2156 <            if (!now) {
2157 <                if ((int)(c >> AC_SHIFT) != -parallelism || runState >= 0 ||
2156 >            if (runState >= 0) {                    // not yet enabled
2157 >                if (!enable)
2158 >                    return false;
2159 >                while (!U.compareAndSwapInt(this, MAINLOCK, 0, 1))
2160 >                    tryAwaitMainLock();
2161 >                try {
2162 >                    runState |= SHUTDOWN;
2163 >                } finally {
2164 >                    if (!U.compareAndSwapInt(this, MAINLOCK, 1, 0)) {
2165 >                        mainLock = 0;
2166 >                        synchronized (this) { notifyAll(); };
2167 >                    }
2168 >                }
2169 >            }
2170 >            if (!now) {                             // check if idle & no tasks
2171 >                if ((int)(c >> AC_SHIFT) != -parallelism ||
2172                      hasQueuedSubmissions())
2173                      return false;
2174                  // Check for unqueued inactive workers. One pass suffices.
2175                  WorkQueue[] ws = workQueues; WorkQueue w;
2176                  if (ws != null) {
2177 <                    int n = ws.length;
1822 <                    for (int i = 1; i < n; i += 2) {
2177 >                    for (int i = 1; i < ws.length; i += 2) {
2178                          if ((w = ws[i]) != null && w.eventCount >= 0)
2179                              return false;
2180                      }
2181                  }
2182              }
2183 <            if (U.compareAndSwapLong(this, CTL, c, c | STOP_BIT))
2184 <                startTerminating();
2185 <        }
2186 <    }
2187 <
2188 <    /**
2189 <     * Initiates termination: Runs three passes through workQueues:
2190 <     * (0) Setting termination status, followed by wakeups of queued
2191 <     * workers; (1) cancelling all tasks; (2) interrupting lagging
2192 <     * threads (likely in external tasks, but possibly also blocked in
2193 <     * joins).  Each pass repeats previous steps because of potential
2194 <     * lagging thread creation.
2195 <     */
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) {
2183 >            if (U.compareAndSwapLong(this, CTL, c, c | STOP_BIT)) {
2184 >                for (int pass = 0; pass < 3; ++pass) {
2185 >                    WorkQueue[] ws = workQueues;
2186 >                    if (ws != null) {
2187 >                        WorkQueue w;
2188 >                        int n = ws.length;
2189 >                        for (int i = 0; i < n; ++i) {
2190 >                            if ((w = ws[i]) != null) {
2191 >                                w.runState = -1;
2192 >                                if (pass > 0) {
2193 >                                    w.cancelAll();
2194 >                                    if (pass > 1)
2195 >                                        w.interruptOwner();
2196                                  }
2197                              }
2198                          }
2199 <                    }
2200 <                }
2201 <                // Wake up workers parked on event queue
2202 <                int i, e; long c; Thread p;
2203 <                while ((i = ((~(e = (int)(c = ctl)) << 1) | 1) & SMASK) < n &&
2204 <                       (w = ws[i]) != null &&
2205 <                       w.eventCount == (e | INT_SIGN)) {
2206 <                    long nc = ((long)(w.nextWait & E_MASK) |
2207 <                               ((c + AC_UNIT) & AC_MASK) |
2208 <                               (c & (TC_MASK|STOP_BIT)));
2209 <                    if (U.compareAndSwapLong(this, CTL, c, nc)) {
2210 <                        w.eventCount = (e + E_SEQ) & E_MASK;
2211 <                        if ((p = w.parker) != null)
2212 <                            U.unpark(p);
2199 >                        // Wake up workers parked on event queue
2200 >                        int i, e; long cc; Thread p;
2201 >                        while ((e = (int)(cc = ctl) & E_MASK) != 0 &&
2202 >                               (i = e & SMASK) < n &&
2203 >                               (w = ws[i]) != null) {
2204 >                            long nc = ((long)(w.nextWait & E_MASK) |
2205 >                                       ((cc + AC_UNIT) & AC_MASK) |
2206 >                                       (cc & (TC_MASK|STOP_BIT)));
2207 >                            if (w.eventCount == (e | INT_SIGN) &&
2208 >                                U.compareAndSwapLong(this, CTL, cc, nc)) {
2209 >                                w.eventCount = (e + E_SEQ) & E_MASK;
2210 >                                w.runState = -1;
2211 >                                if ((p = w.parker) != null)
2212 >                                    U.unpark(p);
2213 >                            }
2214 >                        }
2215                      }
2216                  }
2217              }
# Line 1946 | Line 2287 | public class ForkJoinPool extends Abstra
2287          checkPermission();
2288          if (factory == null)
2289              throw new NullPointerException();
2290 <        if (parallelism <= 0 || parallelism > MAX_ID)
2290 >        if (parallelism <= 0 || parallelism > MAX_CAP)
2291              throw new IllegalArgumentException();
2292          this.parallelism = parallelism;
2293          this.factory = factory;
2294          this.ueh = handler;
2295          this.localMode = asyncMode ? FIFO_QUEUE : LIFO_QUEUE;
1955        this.nextPoolIndex = 1;
2296          long np = (long)(-parallelism); // offset ctl counts
2297          this.ctl = ((np << AC_SHIFT) & AC_MASK) | ((np << TC_SHIFT) & TC_MASK);
2298 <        // initialize workQueues array with room for 2*parallelism if possible
2299 <        int n = parallelism << 1;
2300 <        if (n >= MAX_ID)
2301 <            n = MAX_ID;
2302 <        else { // See Hackers Delight, sec 3.2, where n < (1 << 16)
1963 <            n |= n >>> 1; n |= n >>> 2; n |= n >>> 4; n |= n >>> 8;
1964 <        }
1965 <        this.workQueues = new WorkQueue[(n + 1) << 1];
1966 <        ReentrantLock lck = this.lock = new ReentrantLock();
1967 <        this.termination = lck.newCondition();
1968 <        this.stealCount = new AtomicLong();
1969 <        this.nextWorkerNumber = new AtomicInteger();
2298 >        // Use nearest power 2 for workQueues size. See Hackers Delight sec 3.2.
2299 >        int n = parallelism - 1;
2300 >        n |= n >>> 1; n |= n >>> 2; n |= n >>> 4; n |= n >>> 8; n |= n >>> 16;
2301 >        this.submitMask = ((n + 1) << 1) - 1;
2302 >        int pn = poolNumberGenerator.incrementAndGet();
2303          StringBuilder sb = new StringBuilder("ForkJoinPool-");
2304 <        sb.append(poolNumberGenerator.incrementAndGet());
2304 >        sb.append(Integer.toString(pn));
2305          sb.append("-worker-");
2306          this.workerNamePrefix = sb.toString();
2307 <        // Create initial submission queue
2308 <        WorkQueue sq = tryAddSharedQueue(0);
2309 <        if (sq != null)
2310 <            sq.growArray(false);
2307 >        this.runState = 1;              // set init flag
2308 >    }
2309 >
2310 >    /**
2311 >     * Constructor for common pool, suitable only for static initialization.
2312 >     * Basically the same as above, but uses smallest possible initial footprint.
2313 >     */
2314 >    ForkJoinPool(int parallelism, int submitMask,
2315 >                 ForkJoinWorkerThreadFactory factory,
2316 >                 Thread.UncaughtExceptionHandler handler) {
2317 >        this.factory = factory;
2318 >        this.ueh = handler;
2319 >        this.submitMask = submitMask;
2320 >        this.parallelism = parallelism;
2321 >        long np = (long)(-parallelism);
2322 >        this.ctl = ((np << AC_SHIFT) & AC_MASK) | ((np << TC_SHIFT) & TC_MASK);
2323 >        this.localMode = LIFO_QUEUE;
2324 >        this.workerNamePrefix = "ForkJoinPool.commonPool-worker-";
2325 >        this.runState = 1;
2326 >    }
2327 >
2328 >    /**
2329 >     * Returns the common pool instance.
2330 >     *
2331 >     * @return the common pool instance
2332 >     */
2333 >    public static ForkJoinPool commonPool() {
2334 >        ForkJoinPool p;
2335 >        if ((p = commonPool) == null)
2336 >            throw new Error("Common Pool Unavailable");
2337 >        return p;
2338      }
2339  
2340      // Execution methods
# Line 1996 | Line 2356 | public class ForkJoinPool extends Abstra
2356       *         scheduled for execution
2357       */
2358      public <T> T invoke(ForkJoinTask<T> task) {
2359 +        if (task == null)
2360 +            throw new NullPointerException();
2361          doSubmit(task);
2362          return task.join();
2363      }
# Line 2009 | Line 2371 | public class ForkJoinPool extends Abstra
2371       *         scheduled for execution
2372       */
2373      public void execute(ForkJoinTask<?> task) {
2374 +        if (task == null)
2375 +            throw new NullPointerException();
2376          doSubmit(task);
2377      }
2378  
# Line 2026 | Line 2390 | public class ForkJoinPool extends Abstra
2390          if (task instanceof ForkJoinTask<?>) // avoid re-wrap
2391              job = (ForkJoinTask<?>) task;
2392          else
2393 <            job = ForkJoinTask.adapt(task, null);
2393 >            job = new ForkJoinTask.AdaptedRunnableAction(task);
2394          doSubmit(job);
2395      }
2396  
# Line 2040 | Line 2404 | public class ForkJoinPool extends Abstra
2404       *         scheduled for execution
2405       */
2406      public <T> ForkJoinTask<T> submit(ForkJoinTask<T> task) {
2407 +        if (task == null)
2408 +            throw new NullPointerException();
2409          doSubmit(task);
2410          return task;
2411      }
# Line 2050 | Line 2416 | public class ForkJoinPool extends Abstra
2416       *         scheduled for execution
2417       */
2418      public <T> ForkJoinTask<T> submit(Callable<T> task) {
2419 <        if (task == null)
2054 <            throw new NullPointerException();
2055 <        ForkJoinTask<T> job = ForkJoinTask.adapt(task);
2419 >        ForkJoinTask<T> job = new ForkJoinTask.AdaptedCallable<T>(task);
2420          doSubmit(job);
2421          return job;
2422      }
# Line 2063 | Line 2427 | public class ForkJoinPool extends Abstra
2427       *         scheduled for execution
2428       */
2429      public <T> ForkJoinTask<T> submit(Runnable task, T result) {
2430 <        if (task == null)
2067 <            throw new NullPointerException();
2068 <        ForkJoinTask<T> job = ForkJoinTask.adapt(task, result);
2430 >        ForkJoinTask<T> job = new ForkJoinTask.AdaptedRunnable<T>(task, result);
2431          doSubmit(job);
2432          return job;
2433      }
# Line 2082 | Line 2444 | public class ForkJoinPool extends Abstra
2444          if (task instanceof ForkJoinTask<?>) // avoid re-wrap
2445              job = (ForkJoinTask<?>) task;
2446          else
2447 <            job = ForkJoinTask.adapt(task, null);
2447 >            job = new ForkJoinTask.AdaptedRunnableAction(task);
2448          doSubmit(job);
2449          return job;
2450      }
# Line 2092 | Line 2454 | public class ForkJoinPool extends Abstra
2454       * @throws RejectedExecutionException {@inheritDoc}
2455       */
2456      public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) {
2457 <        ArrayList<ForkJoinTask<T>> forkJoinTasks =
2458 <            new ArrayList<ForkJoinTask<T>>(tasks.size());
2459 <        for (Callable<T> task : tasks)
2460 <            forkJoinTasks.add(ForkJoinTask.adapt(task));
2461 <        invoke(new InvokeAll<T>(forkJoinTasks));
2462 <
2457 >        // In previous versions of this class, this method constructed
2458 >        // a task to run ForkJoinTask.invokeAll, but now external
2459 >        // invocation of multiple tasks is at least as efficient.
2460 >        List<ForkJoinTask<T>> fs = new ArrayList<ForkJoinTask<T>>(tasks.size());
2461 >        // Workaround needed because method wasn't declared with
2462 >        // wildcards in return type but should have been.
2463          @SuppressWarnings({"unchecked", "rawtypes"})
2464 <            List<Future<T>> futures = (List<Future<T>>) (List) forkJoinTasks;
2103 <        return futures;
2104 <    }
2464 >            List<Future<T>> futures = (List<Future<T>>) (List) fs;
2465  
2466 <    static final class InvokeAll<T> extends RecursiveAction {
2467 <        final ArrayList<ForkJoinTask<T>> tasks;
2468 <        InvokeAll(ArrayList<ForkJoinTask<T>> tasks) { this.tasks = tasks; }
2469 <        public void compute() {
2470 <            try { invokeAll(tasks); }
2471 <            catch (Exception ignore) {}
2466 >        boolean done = false;
2467 >        try {
2468 >            for (Callable<T> t : tasks) {
2469 >                ForkJoinTask<T> f = new ForkJoinTask.AdaptedCallable<T>(t);
2470 >                doSubmit(f);
2471 >                fs.add(f);
2472 >            }
2473 >            for (ForkJoinTask<T> f : fs)
2474 >                f.quietlyJoin();
2475 >            done = true;
2476 >            return futures;
2477 >        } finally {
2478 >            if (!done)
2479 >                for (ForkJoinTask<T> f : fs)
2480 >                    f.cancel(false);
2481          }
2113        private static final long serialVersionUID = -7914297376763021607L;
2482      }
2483  
2484      /**
# Line 2142 | Line 2510 | public class ForkJoinPool extends Abstra
2510      }
2511  
2512      /**
2513 +     * Returns the targeted parallelism level of the common pool.
2514 +     *
2515 +     * @return the targeted parallelism level of the common pool
2516 +     */
2517 +    public static int getCommonPoolParallelism() {
2518 +        return commonPoolParallelism;
2519 +    }
2520 +
2521 +    /**
2522       * Returns the number of worker threads that have started but not
2523       * yet terminated.  The result returned by this method may differ
2524       * from {@link #getParallelism} when threads are created to
# Line 2175 | Line 2552 | public class ForkJoinPool extends Abstra
2552          int rc = 0;
2553          WorkQueue[] ws; WorkQueue w;
2554          if ((ws = workQueues) != null) {
2555 <            int n = ws.length;
2556 <            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)
2555 >            for (int i = 1; i < ws.length; i += 2) {
2556 >                if ((w = ws[i]) != null && w.isApparentlyUnblocked())
2557                      ++rc;
2558              }
2559          }
# Line 2228 | Line 2599 | public class ForkJoinPool extends Abstra
2599       * @return the number of steals
2600       */
2601      public long getStealCount() {
2602 <        long count = stealCount.get();
2602 >        long count = stealCount;
2603          WorkQueue[] ws; WorkQueue w;
2604          if ((ws = workQueues) != null) {
2605 <            int n = ws.length;
2235 <            for (int i = 1; i < n; i += 2) {
2605 >            for (int i = 1; i < ws.length; i += 2) {
2606                  if ((w = ws[i]) != null)
2607                      count += w.totalSteals;
2608              }
# Line 2254 | Line 2624 | public class ForkJoinPool extends Abstra
2624          long count = 0;
2625          WorkQueue[] ws; WorkQueue w;
2626          if ((ws = workQueues) != null) {
2627 <            int n = ws.length;
2258 <            for (int i = 1; i < n; i += 2) {
2627 >            for (int i = 1; i < ws.length; i += 2) {
2628                  if ((w = ws[i]) != null)
2629                      count += w.queueSize();
2630              }
# Line 2274 | Line 2643 | public class ForkJoinPool extends Abstra
2643          int count = 0;
2644          WorkQueue[] ws; WorkQueue w;
2645          if ((ws = workQueues) != null) {
2646 <            int n = ws.length;
2278 <            for (int i = 0; i < n; i += 2) {
2646 >            for (int i = 0; i < ws.length; i += 2) {
2647                  if ((w = ws[i]) != null)
2648                      count += w.queueSize();
2649              }
# Line 2292 | Line 2660 | public class ForkJoinPool extends Abstra
2660      public boolean hasQueuedSubmissions() {
2661          WorkQueue[] ws; WorkQueue w;
2662          if ((ws = workQueues) != null) {
2663 <            int n = ws.length;
2664 <            for (int i = 0; i < n; i += 2) {
2297 <                if ((w = ws[i]) != null && w.queueSize() != 0)
2663 >            for (int i = 0; i < ws.length; i += 2) {
2664 >                if ((w = ws[i]) != null && !w.isEmpty())
2665                      return true;
2666              }
2667          }
# Line 2311 | Line 2678 | public class ForkJoinPool extends Abstra
2678      protected ForkJoinTask<?> pollSubmission() {
2679          WorkQueue[] ws; WorkQueue w; ForkJoinTask<?> t;
2680          if ((ws = workQueues) != null) {
2681 <            int n = ws.length;
2315 <            for (int i = 0; i < n; i += 2) {
2681 >            for (int i = 0; i < ws.length; i += 2) {
2682                  if ((w = ws[i]) != null && (t = w.poll()) != null)
2683                      return t;
2684              }
# Line 2341 | Line 2707 | public class ForkJoinPool extends Abstra
2707          int count = 0;
2708          WorkQueue[] ws; WorkQueue w; ForkJoinTask<?> t;
2709          if ((ws = workQueues) != null) {
2710 <            int n = ws.length;
2345 <            for (int i = 0; i < n; ++i) {
2710 >            for (int i = 0; i < ws.length; ++i) {
2711                  if ((w = ws[i]) != null) {
2712                      while ((t = w.poll()) != null) {
2713                          c.add(t);
# Line 2362 | Line 2727 | public class ForkJoinPool extends Abstra
2727       * @return a string identifying this pool, as well as its state
2728       */
2729      public String toString() {
2730 <        long st = getStealCount();
2731 <        long qt = getQueuedTaskCount();
2732 <        long qs = getQueuedSubmissionCount();
2368 <        int rc = getRunningThreadCount();
2369 <        int pc = parallelism;
2730 >        // Use a single pass through workQueues to collect counts
2731 >        long qt = 0L, qs = 0L; int rc = 0;
2732 >        long st = stealCount;
2733          long c = ctl;
2734 +        WorkQueue[] ws; WorkQueue w;
2735 +        if ((ws = workQueues) != null) {
2736 +            for (int i = 0; i < ws.length; ++i) {
2737 +                if ((w = ws[i]) != null) {
2738 +                    int size = w.queueSize();
2739 +                    if ((i & 1) == 0)
2740 +                        qs += size;
2741 +                    else {
2742 +                        qt += size;
2743 +                        st += w.totalSteals;
2744 +                        if (w.isApparentlyUnblocked())
2745 +                            ++rc;
2746 +                    }
2747 +                }
2748 +            }
2749 +        }
2750 +        int pc = parallelism;
2751          int tc = pc + (short)(c >>> TC_SHIFT);
2752          int ac = pc + (int)(c >> AC_SHIFT);
2753          if (ac < 0) // ignore transient negative
# Line 2390 | Line 2770 | public class ForkJoinPool extends Abstra
2770      }
2771  
2772      /**
2773 <     * Initiates an orderly shutdown in which previously submitted
2774 <     * tasks are executed, but no new tasks will be accepted.
2775 <     * Invocation has no additional effect if already shut down.
2776 <     * Tasks that are in the process of being submitted concurrently
2777 <     * during the course of this method may or may not be rejected.
2773 >     * Possibly initiates an orderly shutdown in which previously
2774 >     * submitted tasks are executed, but no new tasks will be
2775 >     * accepted. Invocation has no effect on execution state if this
2776 >     * is the {@link #commonPool}, and no additional effect if
2777 >     * already shut down.  Tasks that are in the process of being
2778 >     * submitted concurrently during the course of this method may or
2779 >     * may not be rejected.
2780       *
2781       * @throws SecurityException if a security manager exists and
2782       *         the caller is not permitted to modify threads
# Line 2403 | Line 2785 | public class ForkJoinPool extends Abstra
2785       */
2786      public void shutdown() {
2787          checkPermission();
2788 <        enableShutdown();
2789 <        tryTerminate(false);
2788 >        if (this != commonPool)
2789 >            tryTerminate(false, true);
2790      }
2791  
2792      /**
2793 <     * Attempts to cancel and/or stop all tasks, and reject all
2794 <     * subsequently submitted tasks.  Tasks that are in the process of
2795 <     * being submitted or executed concurrently during the course of
2796 <     * this method may or may not be rejected. This method cancels
2797 <     * both existing and unexecuted tasks, in order to permit
2798 <     * termination in the presence of task dependencies. So the method
2799 <     * always returns an empty list (unlike the case for some other
2800 <     * Executors).
2793 >     * Possibly attempts to cancel and/or stop all tasks, and reject
2794 >     * all subsequently submitted tasks.  Invocation has no effect on
2795 >     * execution state if this is the {@link #commonPool}, and no
2796 >     * additional effect if already shut down. Otherwise, tasks that
2797 >     * are in the process of being submitted or executed concurrently
2798 >     * during the course of this method may or may not be
2799 >     * rejected. This method cancels both existing and unexecuted
2800 >     * tasks, in order to permit termination in the presence of task
2801 >     * dependencies. So the method always returns an empty list
2802 >     * (unlike the case for some other Executors).
2803       *
2804       * @return an empty list
2805       * @throws SecurityException if a security manager exists and
# Line 2425 | Line 2809 | public class ForkJoinPool extends Abstra
2809       */
2810      public List<Runnable> shutdownNow() {
2811          checkPermission();
2812 <        enableShutdown();
2813 <        tryTerminate(true);
2812 >        if (this != commonPool)
2813 >            tryTerminate(true, true);
2814          return Collections.emptyList();
2815      }
2816  
# Line 2483 | Line 2867 | public class ForkJoinPool extends Abstra
2867      public boolean awaitTermination(long timeout, TimeUnit unit)
2868          throws InterruptedException {
2869          long nanos = unit.toNanos(timeout);
2870 <        final ReentrantLock lock = this.lock;
2871 <        lock.lock();
2872 <        try {
2873 <            for (;;) {
2874 <                if (isTerminated())
2875 <                    return true;
2876 <                if (nanos <= 0)
2877 <                    return false;
2878 <                nanos = termination.awaitNanos(nanos);
2870 >        if (isTerminated())
2871 >            return true;
2872 >        long startTime = System.nanoTime();
2873 >        boolean terminated = false;
2874 >        synchronized(this) {
2875 >            for (long waitTime = nanos, millis = 0L;;) {
2876 >                if (terminated = isTerminated() ||
2877 >                    waitTime <= 0L ||
2878 >                    (millis = unit.toMillis(waitTime)) <= 0L)
2879 >                    break;
2880 >                wait(millis);
2881 >                waitTime = nanos - (System.nanoTime() - startTime);
2882              }
2496        } finally {
2497            lock.unlock();
2883          }
2884 +        return terminated;
2885      }
2886  
2887      /**
# Line 2597 | Line 2983 | public class ForkJoinPool extends Abstra
2983          ForkJoinPool p = ((t instanceof ForkJoinWorkerThread) ?
2984                            ((ForkJoinWorkerThread)t).pool : null);
2985          while (!blocker.isReleasable()) {
2986 <            if (p == null || p.tryCompensate()) {
2986 >            if (p == null || p.tryCompensate(null, blocker)) {
2987                  try {
2988                      do {} while (!blocker.isReleasable() && !blocker.block());
2989                  } finally {
# Line 2614 | Line 3000 | public class ForkJoinPool extends Abstra
3000      // implement RunnableFuture.
3001  
3002      protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
3003 <        return (RunnableFuture<T>) ForkJoinTask.adapt(runnable, value);
3003 >        return new ForkJoinTask.AdaptedRunnable<T>(runnable, value);
3004      }
3005  
3006      protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
3007 <        return (RunnableFuture<T>) ForkJoinTask.adapt(callable);
3007 >        return new ForkJoinTask.AdaptedCallable<T>(callable);
3008      }
3009  
3010      // Unsafe mechanics
3011      private static final sun.misc.Unsafe U;
3012      private static final long CTL;
2627    private static final long RUNSTATE;
3013      private static final long PARKBLOCKER;
3014 +    private static final int ABASE;
3015 +    private static final int ASHIFT;
3016 +    private static final long NEXTWORKERNUMBER;
3017 +    private static final long STEALCOUNT;
3018 +    private static final long MAINLOCK;
3019  
3020      static {
3021          poolNumberGenerator = new AtomicInteger();
3022 +        nextSubmitterSeed = new AtomicInteger(0x55555555);
3023          modifyThreadPermission = new RuntimePermission("modifyThread");
3024          defaultForkJoinWorkerThreadFactory =
3025              new DefaultForkJoinWorkerThreadFactory();
3026 +        submitters = new ThreadSubmitter();
3027          int s;
3028          try {
3029              U = getUnsafe();
3030              Class<?> k = ForkJoinPool.class;
3031 <            Class<?> tk = Thread.class;
3031 >            Class<?> ak = ForkJoinTask[].class;
3032              CTL = U.objectFieldOffset
3033                  (k.getDeclaredField("ctl"));
3034 <            RUNSTATE = U.objectFieldOffset
3035 <                (k.getDeclaredField("runState"));
3034 >            NEXTWORKERNUMBER = U.objectFieldOffset
3035 >                (k.getDeclaredField("nextWorkerNumber"));
3036 >            STEALCOUNT = U.objectFieldOffset
3037 >                (k.getDeclaredField("stealCount"));
3038 >            MAINLOCK = U.objectFieldOffset
3039 >                (k.getDeclaredField("mainLock"));
3040 >            Class<?> tk = Thread.class;
3041              PARKBLOCKER = U.objectFieldOffset
3042                  (tk.getDeclaredField("parkBlocker"));
3043 +            ABASE = U.arrayBaseOffset(ak);
3044 +            s = U.arrayIndexScale(ak);
3045 +            ASHIFT = 31 - Integer.numberOfLeadingZeros(s);
3046 +        } catch (Exception e) {
3047 +            throw new Error(e);
3048 +        }
3049 +        if ((s & (s-1)) != 0)
3050 +            throw new Error("data type scale not a power of two");
3051 +        try { // Establish common pool
3052 +            String pp = System.getProperty(propPrefix + "parallelism");
3053 +            String fp = System.getProperty(propPrefix + "threadFactory");
3054 +            String up = System.getProperty(propPrefix + "exceptionHandler");
3055 +            ForkJoinWorkerThreadFactory fac = (fp == null) ?
3056 +                defaultForkJoinWorkerThreadFactory :
3057 +                ((ForkJoinWorkerThreadFactory)ClassLoader.
3058 +                 getSystemClassLoader().loadClass(fp).newInstance());
3059 +            Thread.UncaughtExceptionHandler ueh = (up == null)? null :
3060 +                ((Thread.UncaughtExceptionHandler)ClassLoader.
3061 +                 getSystemClassLoader().loadClass(up).newInstance());
3062 +            int par;
3063 +            if ((pp == null || (par = Integer.parseInt(pp)) <= 0))
3064 +                par = Runtime.getRuntime().availableProcessors();
3065 +            if (par > MAX_CAP)
3066 +                par = MAX_CAP;
3067 +            commonPoolParallelism = par;
3068 +            int n = par - 1; // precompute submit mask
3069 +            n |= n >>> 1; n |= n >>> 2; n |= n >>> 4;
3070 +            n |= n >>> 8; n |= n >>> 16;
3071 +            int mask = ((n + 1) << 1) - 1;
3072 +            commonPool = new ForkJoinPool(par, mask, fac, ueh);
3073          } catch (Exception e) {
3074              throw new Error(e);
3075          }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines