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

Comparing jsr166/src/jsr166e/ForkJoinPool.java (file contents):
Revision 1.9 by dl, Tue Oct 30 14:23:03 2012 UTC vs.
Revision 1.15 by jsr166, Sun Nov 18 06:31:13 2012 UTC

# Line 11 | Line 11 | import java.util.Arrays;
11   import java.util.Collection;
12   import java.util.Collections;
13   import java.util.List;
14 import java.util.Random;
14   import java.util.concurrent.AbstractExecutorService;
15   import java.util.concurrent.Callable;
16   import java.util.concurrent.ExecutorService;
# Line 20 | Line 19 | import java.util.concurrent.RejectedExec
19   import java.util.concurrent.RunnableFuture;
20   import java.util.concurrent.ThreadLocalRandom;
21   import java.util.concurrent.TimeUnit;
23 import java.util.concurrent.atomic.AtomicInteger;
24 import java.util.concurrent.atomic.AtomicLong;
25 import java.util.concurrent.locks.AbstractQueuedSynchronizer;
26 import java.util.concurrent.locks.Condition;
22  
23   /**
24   * An {@link ExecutorService} for running {@link ForkJoinTask}s.
# Line 48 | Line 43 | import java.util.concurrent.locks.Condit
43   * is not explicitly submitted to a specified pool. Using the common
44   * pool normally reduces resource usage (its threads are slowly
45   * reclaimed during periods of non-use, and reinstated upon subsequent
46 < * use).  The common pool is by default constructed with default
52 < * parameters, but these may be controlled by setting any or all of
53 < * the three properties {@code
54 < * java.util.concurrent.ForkJoinPool.common.{parallelism,
55 < * threadFactory, exceptionHandler}}.
46 > * use).
47   *
48   * <p>For applications that require separate or custom pools, a {@code
49   * ForkJoinPool} may be constructed with a given target parallelism
# Line 107 | Line 98 | import java.util.concurrent.locks.Condit
98   *  </tr>
99   * </table>
100   *
101 + * <p>The common pool is by default constructed with default
102 + * parameters, but these may be controlled by setting three {@link
103 + * System#getProperty properties} with prefix {@code
104 + * java.util.concurrent.ForkJoinPool.common}: {@code parallelism} --
105 + * an integer greater than zero, {@code threadFactory} -- the class
106 + * name of a {@link ForkJoinWorkerThreadFactory}, and {@code
107 + * exceptionHandler} -- the class name of a {@link
108 + * java.lang.Thread.UncaughtExceptionHandler
109 + * Thread.UncaughtExceptionHandler}. Upon any error in establishing
110 + * these settings, default parameters are used.
111 + *
112   * <p><b>Implementation notes</b>: This implementation restricts the
113   * maximum number of running threads to 32767. Attempts to create
114   * pools with greater than the maximum number result in
# Line 193 | Line 195 | public class ForkJoinPool extends Abstra
195       * WorkQueues are also used in a similar way for tasks submitted
196       * to the pool. We cannot mix these tasks in the same queues used
197       * for work-stealing (this would contaminate lifo/fifo
198 <     * processing). Instead, we loosely associate submission queues
198 >     * processing). Instead, we randomly associate submission queues
199       * with submitting threads, using a form of hashing.  The
200       * ThreadLocal Submitter class contains a value initially used as
201       * a hash code for choosing existing queues, but may be randomly
202       * repositioned upon contention with other submitters.  In
203 <     * essence, submitters act like workers except that they never
204 <     * take tasks, and they are multiplexed on to a finite number of
205 <     * shared work queues. However, classes are set up so that future
206 <     * extensions could allow submitters to optionally help perform
207 <     * tasks as well. Insertion of tasks in shared mode requires a
208 <     * lock (mainly to protect in the case of resizing) but we use
209 <     * only a simple spinlock (using bits in field runState), because
210 <     * submitters encountering a busy queue move on to try or create
211 <     * other queues -- they block only when creating and registering
212 <     * new queues.
203 >     * essence, submitters act like workers except that they are
204 >     * restricted to executing local tasks that they submitted (or in
205 >     * the case of CountedCompleters, others with the same root task).
206 >     * However, because most shared/external queue operations are more
207 >     * expensive than internal, and because, at steady state, external
208 >     * submitters will compete for CPU with workers, ForkJoinTask.join
209 >     * and related methods disable them from repeatedly helping to
210 >     * process tasks if all workers are active.  Insertion of tasks in
211 >     * shared mode requires a lock (mainly to protect in the case of
212 >     * resizing) but we use only a simple spinlock (using bits in
213 >     * field qlock), because submitters encountering a busy queue move
214 >     * on to try or create other queues -- they block only when
215 >     * creating and registering new queues.
216       *
217       * Management
218       * ==========
# Line 229 | Line 234 | public class ForkJoinPool extends Abstra
234       * and their negations (used for thresholding) to fit into 16bit
235       * fields.
236       *
237 <     * Field "runState" contains 32 bits needed to register and
238 <     * deregister WorkQueues, as well as to enable shutdown. It is
239 <     * only modified under a lock (normally briefly held, but
240 <     * occasionally protecting allocations and resizings) but even
241 <     * when locked remains available to check consistency.
237 >     * Field "plock" is a form of sequence lock with a saturating
238 >     * shutdown bit (similarly for per-queue "qlocks"), mainly
239 >     * protecting updates to the workQueues array, as well as to
240 >     * enable shutdown.  When used as a lock, it is normally only very
241 >     * briefly held, so is nearly always available after at most a
242 >     * brief spin, but we use a monitor-based backup strategy to
243 >     * blocking when needed.
244       *
245       * Recording WorkQueues.  WorkQueues are recorded in the
246       * "workQueues" array that is created upon first use and expanded
# Line 242 | Line 249 | public class ForkJoinPool extends Abstra
249       * by a lock but the array is otherwise concurrently readable, and
250       * accessed directly.  To simplify index-based operations, the
251       * array size is always a power of two, and all readers must
252 <     * tolerate null slots. Shared (submission) queues are at even
253 <     * indices, worker queues at odd indices. Grouping them together
254 <     * in this way simplifies and speeds up task scanning.
252 >     * tolerate null slots. Worker queues are at odd indices Shared
253 >     * (submission) queues are at even indices, up to a maximum of 64
254 >     * slots, to limit growth even if array needs to expand to add
255 >     * more workers. Grouping them together in this way simplifies and
256 >     * speeds up task scanning.
257       *
258       * All worker thread creation is on-demand, triggered by task
259       * submissions, replacement of terminated workers, and/or
# Line 305 | Line 314 | public class ForkJoinPool extends Abstra
314       *
315       * Signalling.  We create or wake up workers only when there
316       * appears to be at least one task they might be able to find and
317 <     * execute.  When a submission is added or another worker adds a
318 <     * task to a queue that previously had fewer than two tasks, they
319 <     * signal waiting workers (or trigger creation of new ones if
320 <     * fewer than the given parallelism level -- see signalWork).
321 <     * These primary signals are buttressed by signals during rescans;
322 <     * together these cover the signals needed in cases when more
323 <     * tasks are pushed but untaken, and improve performance compared
324 <     * to having one thread wake up all workers.
317 >     * execute. However, many other threads may notice the same task
318 >     * and each signal to wake up a thread that might take it. So in
319 >     * general, pools will be over-signalled.  When a submission is
320 >     * added or another worker adds a task to a queue that is
321 >     * apparently empty, they signal waiting workers (or trigger
322 >     * creation of new ones if fewer than the given parallelism level
323 >     * -- see signalWork).  These primary signals are buttressed by
324 >     * signals whenever other threads scan for work or do not have a
325 >     * task to process. On most platforms, signalling (unpark)
326 >     * overhead time is noticeably long, and the time between
327 >     * signalling a thread and it actually making progress can be very
328 >     * noticeably long, so it is worth offloading these delays from
329 >     * critical paths as much as possible.
330       *
331       * Trimming workers. To release resources after periods of lack of
332       * use, a worker starting to wait when the pool is quiescent will
# Line 323 | Line 337 | public class ForkJoinPool extends Abstra
337       * periods of non-use.
338       *
339       * Shutdown and Termination. A call to shutdownNow atomically sets
340 <     * a runState bit and then (non-atomically) sets each worker's
341 <     * runState status, cancels all unprocessed tasks, and wakes up
340 >     * a plock bit and then (non-atomically) sets each worker's
341 >     * qlock status, cancels all unprocessed tasks, and wakes up
342       * all waiting workers.  Detecting whether termination should
343       * commence after a non-abrupt shutdown() call requires more work
344       * and bookkeeping. We need consensus about quiescence (i.e., that
# Line 352 | Line 366 | public class ForkJoinPool extends Abstra
366       *      method tryCompensate() may create or re-activate a spare
367       *      thread to compensate for blocked joiners until they unblock.
368       *
369 <     * A third form (implemented in tryRemoveAndExec and
370 <     * tryPollForAndExec) amounts to helping a hypothetical
371 <     * compensator: If we can readily tell that a possible action of a
372 <     * compensator is to steal and execute the task being joined, the
373 <     * joining thread can do so directly, without the need for a
374 <     * compensation thread (although at the expense of larger run-time
375 <     * stacks, but the tradeoff is typically worthwhile).
369 >     * A third form (implemented in tryRemoveAndExec) amounts to
370 >     * helping a hypothetical compensator: If we can readily tell that
371 >     * a possible action of a compensator is to steal and execute the
372 >     * task being joined, the joining thread can do so directly,
373 >     * without the need for a compensation thread (although at the
374 >     * expense of larger run-time stacks, but the tradeoff is
375 >     * typically worthwhile).
376       *
377       * The ManagedBlocker extension API can't use helping so relies
378       * only on compensation in method awaitBlocker.
# Line 393 | Line 407 | public class ForkJoinPool extends Abstra
407       * to find work (see MAX_HELP) and fall back to suspending the
408       * worker and if necessary replacing it with another.
409       *
410 +     * Helping actions for CountedCompleters are much simpler: Method
411 +     * helpComplete can take and execute any task with the same root
412 +     * as the task being waited on. However, this still entails some
413 +     * traversal of completer chains, so is less efficient than using
414 +     * CountedCompleters without explicit joins.
415 +     *
416       * It is impossible to keep exactly the target parallelism number
417       * of threads running at any given time.  Determining the
418       * existence of conservatively safe helping targets, the
# Line 414 | Line 434 | public class ForkJoinPool extends Abstra
434       * intractable) game with an opponent that may choose the worst
435       * (for us) active thread to stall at any time.  We take several
436       * precautions to bound losses (and thus bound gains), mainly in
437 <     * methods tryCompensate and awaitJoin: (1) We only try
438 <     * compensation after attempting enough helping steps (measured
439 <     * via counting and timing) that we have already consumed the
440 <     * estimated cost of creating and activating a new thread.  (2) We
441 <     * allow up to 50% of threads to be blocked before initially
442 <     * adding any others, and unless completely saturated, check that
443 <     * some work is available for a new worker before adding. Also, we
444 <     * create up to only 50% more threads until entering a mode that
445 <     * only adds a thread if all others are possibly blocked.  All
446 <     * together, this means that we might be half as fast to react,
447 <     * and create half as many threads as possible in the ideal case,
448 <     * but present vastly fewer anomalies in all other cases compared
449 <     * to both more aggressive and more conservative alternatives.
450 <     *
451 <     * Style notes: There is a lot of representation-level coupling
452 <     * among classes ForkJoinPool, ForkJoinWorkerThread, and
453 <     * ForkJoinTask.  The fields of WorkQueue maintain data structures
454 <     * managed by ForkJoinPool, so are directly accessed.  There is
455 <     * little point trying to reduce this, since any associated future
456 <     * changes in representations will need to be accompanied by
457 <     * algorithmic changes anyway. Several methods intrinsically
458 <     * sprawl because they must accumulate sets of consistent reads of
459 <     * volatiles held in local variables.  Methods signalWork() and
460 <     * scan() are the main bottlenecks, so are especially heavily
437 >     * methods tryCompensate and awaitJoin.
438 >     *
439 >     * Common Pool
440 >     * ===========
441 >     *
442 >     * The static commonPool always exists after static
443 >     * initialization.  Since it (or any other created pool) need
444 >     * never be used, we minimize initial construction overhead and
445 >     * footprint to the setup of about a dozen fields, with no nested
446 >     * allocation. Most bootstrapping occurs within method
447 >     * fullExternalPush during the first submission to the pool.
448 >     *
449 >     * When external threads submit to the common pool, they can
450 >     * perform some subtask processing (see externalHelpJoin and
451 >     * related methods).  We do not need to record whether these
452 >     * submissions are to the common pool -- if not, externalHelpJoin
453 >     * returns quickly (at the most helping to signal some common pool
454 >     * workers). These submitters would otherwise be blocked waiting
455 >     * for completion, so the extra effort (with liberally sprinkled
456 >     * task status checks) in inapplicable cases amounts to an odd
457 >     * form of limited spin-wait before blocking in ForkJoinTask.join.
458 >     *
459 >     * Style notes
460 >     * ===========
461 >     *
462 >     * There is a lot of representation-level coupling among classes
463 >     * ForkJoinPool, ForkJoinWorkerThread, and ForkJoinTask.  The
464 >     * fields of WorkQueue maintain data structures managed by
465 >     * ForkJoinPool, so are directly accessed.  There is little point
466 >     * trying to reduce this, since any associated future changes in
467 >     * representations will need to be accompanied by algorithmic
468 >     * changes anyway. Several methods intrinsically sprawl because
469 >     * they must accumulate sets of consistent reads of volatiles held
470 >     * in local variables.  Methods signalWork() and scan() are the
471 >     * main bottlenecks, so are especially heavily
472       * micro-optimized/mangled.  There are lots of inline assignments
473       * (of form "while ((local = field) != 0)") which are usually the
474       * simplest way to ensure the required read orderings (which are
# Line 445 | Line 476 | public class ForkJoinPool extends Abstra
476       * declarations of these locals at the heads of methods or blocks.
477       * There are several occurrences of the unusual "do {} while
478       * (!cas...)"  which is the simplest way to force an update of a
479 <     * CAS'ed variable. There are also other coding oddities that help
479 >     * CAS'ed variable. There are also other coding oddities (including
480 >     * several unnecessary-looking hoisted null checks) that help
481       * some methods perform reasonably even when interpreted (not
482       * compiled).
483       *
# Line 508 | Line 540 | public class ForkJoinPool extends Abstra
540       * actually do anything beyond having a unique identity.
541       */
542      static final class EmptyTask extends ForkJoinTask<Void> {
543 +        private static final long serialVersionUID = -7721805057305804111L;
544          EmptyTask() { status = ForkJoinTask.NORMAL; } // force done
545          public final Void getRawResult() { return null; }
546          public final void setRawResult(Void x) {}
# Line 528 | Line 561 | public class ForkJoinPool extends Abstra
561       *
562       * Field "top" is the index (mod array.length) of the next queue
563       * slot to push to or pop from. It is written only by owner thread
564 <     * for push, or under lock for trySharedPush, and accessed by
565 <     * other threads only after reading (volatile) base.  Both top and
566 <     * base are allowed to wrap around on overflow, but (top - base)
567 <     * (or more commonly -(base - top) to force volatile read of base
568 <     * before top) still estimates size.
564 >     * for push, or under lock for external/shared push, and accessed
565 >     * by other threads only after reading (volatile) base.  Both top
566 >     * and base are allowed to wrap around on overflow, but (top -
567 >     * base) (or more commonly -(base - top) to force volatile read of
568 >     * base before top) still estimates size. The lock ("qlock") is
569 >     * forced to -1 on termination, causing all further lock attempts
570 >     * to fail. (Note: we don't need CAS for termination state because
571 >     * upon pool shutdown, all shared-queues will stop being used
572 >     * anyway.)  Nearly all lock bodies are set up so that exceptions
573 >     * within lock bodies are "impossible" (modulo JVM errors that
574 >     * would cause failure anyway.)
575       *
576       * The array slots are read and written using the emulation of
577       * volatiles/atomics provided by Unsafe. Insertions must in
578       * general use putOrderedObject as a form of releasing store to
579       * ensure that all writes to the task object are ordered before
580 <     * its publication in the queue. (Although we can avoid one case
581 <     * of this when locked in trySharedPush.) All removals entail a
582 <     * CAS to null.  The array is always a power of two. To ensure
583 <     * safety of Unsafe array operations, all accesses perform
545 <     * explicit null checks and implicit bounds checks via
546 <     * power-of-two masking.
580 >     * its publication in the queue.  All removals entail a CAS to
581 >     * null.  The array is always a power of two. To ensure safety of
582 >     * Unsafe array operations, all accesses perform explicit null
583 >     * checks and implicit bounds checks via power-of-two masking.
584       *
585       * In addition to basic queuing support, this class contains
586       * fields described elsewhere to control execution. It turns out
587 <     * to work better memory-layout-wise to include them in this
588 <     * class rather than a separate class.
587 >     * to work better memory-layout-wise to include them in this class
588 >     * rather than a separate class.
589       *
590       * Performance on most platforms is very sensitive to placement of
591       * instances of both WorkQueues and their arrays -- we absolutely
# Line 564 | Line 601 | public class ForkJoinPool extends Abstra
601       * support is in place, this padding is dependent on transient
602       * properties of JVM field layout rules.)  We also take care in
603       * allocating, sizing and resizing the array. Non-shared queue
604 <     * arrays are initialized (via method growArray) by workers before
605 <     * use. Others are allocated on first use.
604 >     * arrays are initialized by workers before use. Others are
605 >     * allocated on first use.
606       */
607      static final class WorkQueue {
608          /**
# Line 588 | Line 625 | public class ForkJoinPool extends Abstra
625           */
626          static final int MAXIMUM_QUEUE_CAPACITY = 1 << 26; // 64M
627  
591        volatile long totalSteals; // cumulative number of steals
628          int seed;                  // for random scanning; initialize nonzero
629          volatile int eventCount;   // encoded inactivation count; < 0 if inactive
630          int nextWait;              // encoded record of next event waiter
595        int rescans;               // remaining scans until block
596        int nsteals;               // top-level task executions since last idle
631          final int mode;            // lifo, fifo, or shared
632 +        int nsteals;               // cumulative number of steals
633          int poolIndex;             // index of this queue in pool (or 0)
634          int stealHint;             // index of most recent known stealer
635 <        volatile int runState;     // 1: locked, -1: terminate; else 0
635 >        volatile int qlock;        // 1: locked, -1: terminate; else 0
636          volatile int base;         // index of next slot for poll
637          int top;                   // index of next slot for push
638          ForkJoinTask<?>[] array;   // the elements (initially unallocated)
# Line 619 | Line 654 | public class ForkJoinPool extends Abstra
654          }
655  
656          /**
622         * Returns the approximate number of tasks in the queue.
623         */
624        final int queueSize() {
625            int n = base - top;       // non-owner callers must read base first
626            return (n >= 0) ? 0 : -n; // ignore transient negative
627        }
628
629        /**
630         * Provides a more accurate estimate of whether this queue has
631         * any tasks than does queueSize, by checking whether a
632         * near-empty queue has at least one unclaimed task.
633         */
634        final boolean isEmpty() {
635            ForkJoinTask<?>[] a; int m, s;
636            int n = base - (s = top);
637            return (n >= 0 ||
638                    (n == -1 &&
639                     ((a = array) == null ||
640                      (m = a.length - 1) < 0 ||
641                      U.getObjectVolatile
642                      (a, ((m & (s - 1)) << ASHIFT) + ABASE) == null)));
643        }
644
645        /**
657           * Pushes a task. Call only by owner in unshared queues.
658 +         * Cases needing resizing or rejection are relayed to fullPush
659 +         * (that also handles shared queues).
660           *
661           * @param task the task. Caller must ensure non-null.
662           * @throw RejectedExecutionException if array cannot be resized
663           */
664          final void push(ForkJoinTask<?> task) {
665 <            ForkJoinTask<?>[] a; ForkJoinPool p;
666 <            int s = top, m, n;
667 <            if ((a = array) != null) {    // ignore if queue removed
665 >            ForkJoinPool p; ForkJoinTask<?>[] a;
666 >            int s = top, n;
667 >            if ((a = array) != null && a.length > (n = s + 1 - base)) {
668                  U.putOrderedObject
669 <                    (a, (((m = a.length - 1) & s) << ASHIFT) + ABASE, task);
670 <                if ((n = (top = s + 1) - base) <= 2) {
671 <                    if ((p = pool) != null)
672 <                        p.signalWork();
660 <                }
661 <                else if (n >= m)
662 <                    growArray(true);
669 >                    (a, (((a.length - 1) & s) << ASHIFT) + ABASE, task);
670 >                top = s + 1;
671 >                if (n <= 1 && (p = pool) != null)
672 >                    p.signalWork(this, 1);
673              }
674 +            else
675 +                fullPush(task, true);
676          }
677  
678          /**
679           * Pushes a task if lock is free and array is either big
680 <         * enough or can be resized to be big enough.
680 >         * enough or can be resized to be big enough. Note: a
681 >         * specialization of a common fast path of this method is in
682 >         * ForkJoinPool.externalPush. When called from a FJWT queue,
683 >         * this can fail only if the pool has been shut down or
684 >         * an out of memory error.
685           *
686           * @param task the task. Caller must ensure non-null.
687 <         * @return true if submitted
687 >         * @param owned if true, throw RJE on failure
688           */
689 <        final boolean trySharedPush(ForkJoinTask<?> task) {
690 <            boolean submitted = false;
691 <            if (runState == 0 && U.compareAndSwapInt(this, RUNSTATE, 0, 1)) {
692 <                ForkJoinTask<?>[] a = array;
693 <                int s = top;
694 <                try {
695 <                    if ((a != null && a.length > s + 1 - base) ||
696 <                        (a = growArray(false)) != null) { // must presize
697 <                        int j = (((a.length - 1) & s) << ASHIFT) + ABASE;
698 <                        U.putObject(a, (long)j, task);    // don't need "ordered"
699 <                        top = s + 1;
700 <                        submitted = true;
689 >        final boolean fullPush(ForkJoinTask<?> task, boolean owned) {
690 >            ForkJoinPool p; ForkJoinTask<?>[] a;
691 >            if (owned) {
692 >                if (qlock < 0) // must be shutting down
693 >                    throw new RejectedExecutionException();
694 >            }
695 >            else if (!U.compareAndSwapInt(this, QLOCK, 0, 1))
696 >                return false;
697 >            try {
698 >                int s = top, oldLen, len;
699 >                if ((a = array) == null)
700 >                    a = array = new ForkJoinTask<?>[len=INITIAL_QUEUE_CAPACITY];
701 >                else if ((oldLen = a.length) > s + 1 - base)
702 >                    len = oldLen;
703 >                else if ((len = oldLen << 1) > MAXIMUM_QUEUE_CAPACITY)
704 >                    throw new RejectedExecutionException("Capacity exceeded");
705 >                else {
706 >                    int oldMask, b;
707 >                    ForkJoinTask<?>[] oldA = a;
708 >                    a = array = new ForkJoinTask<?>[len];
709 >                    if ((oldMask = oldLen - 1) >= 0 && s - (b = base) > 0) {
710 >                        int mask = len - 1;
711 >                        do {
712 >                            ForkJoinTask<?> x;
713 >                            int oldj = ((b & oldMask) << ASHIFT) + ABASE;
714 >                            int j    = ((b &    mask) << ASHIFT) + ABASE;
715 >                            x = (ForkJoinTask<?>)
716 >                                U.getObjectVolatile(oldA, oldj);
717 >                            if (x != null &&
718 >                                U.compareAndSwapObject(oldA, oldj, x, null))
719 >                                U.putObjectVolatile(a, j, x);
720 >                        } while (++b != s);
721                      }
686                } finally {
687                    runState = 0;                         // unlock
722                  }
723 +                U.putOrderedObject
724 +                    (a, (((len - 1) & s) << ASHIFT) + ABASE, task);
725 +                top = s + 1;
726 +            } finally {
727 +                if (!owned)
728 +                    qlock = 0;
729              }
730 <            return submitted;
730 >            if ((p = pool) != null)
731 >                p.signalWork(this, 1);
732 >            return true;
733          }
734  
735          /**
# Line 710 | Line 752 | public class ForkJoinPool extends Abstra
752              return null;
753          }
754  
713        final ForkJoinTask<?> sharedPop() {
714            ForkJoinTask<?> task = null;
715            if (runState == 0 && U.compareAndSwapInt(this, RUNSTATE, 0, 1)) {
716                try {
717                    ForkJoinTask<?>[] a; int m;
718                    if ((a = array) != null && (m = a.length - 1) >= 0) {
719                        for (int s; (s = top - 1) - base >= 0;) {
720                            long j = ((m & s) << ASHIFT) + ABASE;
721                            ForkJoinTask<?> t =
722                                (ForkJoinTask<?>)U.getObject(a, j);
723                            if (t == null)
724                                break;
725                            if (U.compareAndSwapObject(a, j, t, null)) {
726                                top = s;
727                                task = t;
728                                break;
729                            }
730                        }
731                    }
732                } finally {
733                    runState = 0;
734                }
735            }
736            return task;
737        }
738
739        /**
740         * Version of pop that takes top element only if it
741         * its root is the given CountedCompleter.
742         */
743        final ForkJoinTask<?> popCC(CountedCompleter<?> root) {
744            ForkJoinTask<?>[] a; int m;
745            if (root != null && (a = array) != null && (m = a.length - 1) >= 0) {
746                for (int s; (s = top - 1) - base >= 0;) {
747                    long j = ((m & s) << ASHIFT) + ABASE;
748                    ForkJoinTask<?> t =
749                        (ForkJoinTask<?>)U.getObject(a, j);
750                    if (t == null || !(t instanceof CountedCompleter) ||
751                        ((CountedCompleter<?>)t).getRoot() != root)
752                        break;
753                    if (U.compareAndSwapObject(a, j, t, null)) {
754                        top = s;
755                        return t;
756                    }
757                    if (root.status < 0)
758                        break;
759                }
760            }
761            return null;
762        }
763
764        /**
765         * Shared version of popCC
766         */
767        final ForkJoinTask<?> sharedPopCC(CountedCompleter<?> root) {
768            ForkJoinTask<?> task = null;
769            if (root != null &&
770                runState == 0 && U.compareAndSwapInt(this, RUNSTATE, 0, 1)) {
771                try {
772                    ForkJoinTask<?>[] a; int m;
773                    if ((a = array) != null && (m = a.length - 1) >= 0) {
774                        for (int s; (s = top - 1) - base >= 0;) {
775                            long j = ((m & s) << ASHIFT) + ABASE;
776                            ForkJoinTask<?> t =
777                                (ForkJoinTask<?>)U.getObject(a, j);
778                            if (t == null || !(t instanceof CountedCompleter) ||
779                                ((CountedCompleter<?>)t).getRoot() != root)
780                                break;
781                            if (U.compareAndSwapObject(a, j, t, null)) {
782                                top = s;
783                                task = t;
784                                break;
785                            }
786                            if (root.status < 0)
787                                break;
788                        }
789                    }
790                } finally {
791                    runState = 0;
792                }
793            }
794            return task;
795        }
796
755          /**
756           * Takes a task in FIFO order if b is base of queue and a task
757           * can be claimed without contention. Specialized versions
# Line 831 | Line 789 | public class ForkJoinPool extends Abstra
789                  else if (base == b) {
790                      if (b + 1 == top)
791                          break;
792 <                    Thread.yield(); // wait for lagging update
792 >                    Thread.yield(); // wait for lagging update (very rare)
793                  }
794              }
795              return null;
# Line 858 | Line 816 | public class ForkJoinPool extends Abstra
816  
817          /**
818           * Pops the given task only if it is at the current top.
819 +         * (A shared version is available only via FJP.tryExternalUnpush)
820           */
821          final boolean tryUnpush(ForkJoinTask<?> t) {
822              ForkJoinTask<?>[] a; int s;
# Line 871 | Line 830 | public class ForkJoinPool extends Abstra
830          }
831  
832          /**
874         * Version of tryUnpush for shared queues; called by non-FJ
875         * submitters after prechecking that task probably exists.
876         */
877        final boolean trySharedUnpush(ForkJoinTask<?> t) {
878            boolean success = false;
879            if (runState == 0 && U.compareAndSwapInt(this, RUNSTATE, 0, 1)) {
880                try {
881                    ForkJoinTask<?>[] a; int s;
882                    if ((a = array) != null && (s = top) != base &&
883                        U.compareAndSwapObject
884                        (a, (((a.length - 1) & --s) << ASHIFT) + ABASE, t, null)) {
885                        top = s;
886                        success = true;
887                    }
888                } finally {
889                    runState = 0;                         // unlock
890                }
891            }
892            return success;
893        }
894
895        /**
896         * Polls the given task only if it is at the current base.
897         */
898        final boolean pollFor(ForkJoinTask<?> task) {
899            ForkJoinTask<?>[] a; int b;
900            if ((b = base) - top < 0 && (a = array) != null) {
901                int j = (((a.length - 1) & b) << ASHIFT) + ABASE;
902                if (U.getObjectVolatile(a, j) == task && base == b &&
903                    U.compareAndSwapObject(a, j, task, null)) {
904                    base = b + 1;
905                    return true;
906                }
907            }
908            return false;
909        }
910
911        /**
912         * Initializes or doubles the capacity of array. Call either
913         * by owner or with lock held -- it is OK for base, but not
914         * top, to move while resizings are in progress.
915         *
916         * @param rejectOnFailure if true, throw exception if capacity
917         * exceeded (relayed ultimately to user); else return null.
918         */
919        final ForkJoinTask<?>[] growArray(boolean rejectOnFailure) {
920            ForkJoinTask<?>[] oldA = array;
921            int size = oldA != null ? oldA.length << 1 : INITIAL_QUEUE_CAPACITY;
922            if (size <= MAXIMUM_QUEUE_CAPACITY) {
923                int oldMask, t, b;
924                ForkJoinTask<?>[] a = array = new ForkJoinTask<?>[size];
925                if (oldA != null && (oldMask = oldA.length - 1) >= 0 &&
926                    (t = top) - (b = base) > 0) {
927                    int mask = size - 1;
928                    do {
929                        ForkJoinTask<?> x;
930                        int oldj = ((b & oldMask) << ASHIFT) + ABASE;
931                        int j    = ((b &    mask) << ASHIFT) + ABASE;
932                        x = (ForkJoinTask<?>)U.getObjectVolatile(oldA, oldj);
933                        if (x != null &&
934                            U.compareAndSwapObject(oldA, oldj, x, null))
935                            U.putObjectVolatile(a, j, x);
936                    } while (++b != t);
937                }
938                return a;
939            }
940            else if (!rejectOnFailure)
941                return null;
942            else
943                throw new RejectedExecutionException("Queue capacity exceeded");
944        }
945
946        /**
833           * Removes and cancels all known tasks, ignoring any exceptions.
834           */
835          final void cancelAll() {
# Line 967 | Line 853 | public class ForkJoinPool extends Abstra
853              return seed = r ^= r << 5;
854          }
855  
856 <        // Execution methods
856 >        /**
857 >         * Provides a more accurate estimate of size than (top - base)
858 >         * by ordering reads and checking whether a near-empty queue
859 >         * has at least one unclaimed task.
860 >         */
861 >        final int queueSize() {
862 >            ForkJoinTask<?>[] a; int k, s, n;
863 >            return ((n = base - (s = top)) < 0 &&
864 >                    (n != -1 ||
865 >                     ((a = array) != null && (k = a.length) > 0 &&
866 >                      U.getObject
867 >                      (a, (long)((((k - 1) & (s - 1)) << ASHIFT) + ABASE)) != null))) ?
868 >                -n : 0;
869 >        }
870 >
871 >        // Specialized execution methods
872  
873          /**
874           * Pops and runs tasks until empty.
# Line 996 | Line 897 | public class ForkJoinPool extends Abstra
897          }
898  
899          /**
900 <         * If present, removes from queue and executes the given task, or
901 <         * any other cancelled task. Returns (true) immediately on any CAS
900 >         * If present, removes from queue and executes the given task,
901 >         * or any other cancelled task. Returns (true) on any CAS
902           * or consistency check failure so caller can retry.
903           *
904 <         * @return 0 if no progress can be made, else positive
1004 <         * (this unusual convention simplifies use with tryHelpStealer.)
904 >         * @return false if no progress can be made, else true;
905           */
906 <        final int tryRemoveAndExec(ForkJoinTask<?> task) {
907 <            int stat = 1;
1008 <            boolean removed = false, empty = true;
906 >        final boolean tryRemoveAndExec(ForkJoinTask<?> task) {
907 >            boolean stat = true, removed = false, empty = true;
908              ForkJoinTask<?>[] a; int m, s, b, n;
909              if ((a = array) != null && (m = a.length - 1) >= 0 &&
910                  (n = (s = top) - (b = base)) > 0) {
# Line 1035 | Line 934 | public class ForkJoinPool extends Abstra
934                      }
935                      if (--n == 0) {
936                          if (!empty && base == b)
937 <                            stat = 0;
937 >                            stat = false;
938                          break;
939                      }
940                  }
# Line 1046 | Line 945 | public class ForkJoinPool extends Abstra
945          }
946  
947          /**
948 +         * Polls for and executes the given task or any other task in
949 +         * its CountedCompleter computation
950 +         */
951 +        final boolean pollAndExecCC(ForkJoinTask<?> root) {
952 +            ForkJoinTask<?>[] a; int b; Object o;
953 +            outer: while ((b = base) - top < 0 && (a = array) != null) {
954 +                long j = (((a.length - 1) & b) << ASHIFT) + ABASE;
955 +                if ((o = U.getObject(a, j)) == null ||
956 +                    !(o instanceof CountedCompleter))
957 +                    break;
958 +                for (CountedCompleter<?> t = (CountedCompleter<?>)o, r = t;;) {
959 +                    if (r == root) {
960 +                        if (base == b &&
961 +                            U.compareAndSwapObject(a, j, t, null)) {
962 +                            base = b + 1;
963 +                            t.doExec();
964 +                            return true;
965 +                        }
966 +                        else
967 +                            break; // restart
968 +                    }
969 +                    if ((r = r.completer) == null)
970 +                        break outer; // not part of root computation
971 +                }
972 +            }
973 +            return false;
974 +        }
975 +
976 +        /**
977           * Executes a top-level task and any local tasks remaining
978           * after execution.
979           */
980          final void runTask(ForkJoinTask<?> t) {
981              if (t != null) {
982 <                currentSteal = t;
983 <                t.doExec();
982 >                (currentSteal = t).doExec();
983 >                currentSteal = null;
984 >                if (++nsteals < 0) {     // spill on overflow
985 >                    ForkJoinPool p;
986 >                    if ((p = pool) != null)
987 >                        p.collectStealCount(this);
988 >                }
989                  if (top != base) {       // process remaining local tasks
990                      if (mode == 0)
991                          popAndExecAll();
992                      else
993                          pollAndExecAll();
994                  }
1062                ++nsteals;
1063                currentSteal = null;
995              }
996          }
997  
# Line 1070 | Line 1001 | public class ForkJoinPool extends Abstra
1001          final void runSubtask(ForkJoinTask<?> t) {
1002              if (t != null) {
1003                  ForkJoinTask<?> ps = currentSteal;
1004 <                currentSteal = t;
1074 <                t.doExec();
1004 >                (currentSteal = t).doExec();
1005                  currentSteal = ps;
1006              }
1007          }
# Line 1106 | Line 1036 | public class ForkJoinPool extends Abstra
1036  
1037          // Unsafe mechanics
1038          private static final sun.misc.Unsafe U;
1039 <        private static final long RUNSTATE;
1039 >        private static final long QLOCK;
1040          private static final int ABASE;
1041          private static final int ASHIFT;
1042          static {
# Line 1115 | Line 1045 | public class ForkJoinPool extends Abstra
1045                  U = getUnsafe();
1046                  Class<?> k = WorkQueue.class;
1047                  Class<?> ak = ForkJoinTask[].class;
1048 <                RUNSTATE = U.objectFieldOffset
1049 <                    (k.getDeclaredField("runState"));
1048 >                QLOCK = U.objectFieldOffset
1049 >                    (k.getDeclaredField("qlock"));
1050                  ABASE = U.arrayBaseOffset(ak);
1051                  s = U.arrayIndexScale(ak);
1052              } catch (Exception e) {
# Line 1131 | Line 1061 | public class ForkJoinPool extends Abstra
1061      /**
1062       * Per-thread records for threads that submit to pools. Currently
1063       * holds only pseudo-random seed / index that is used to choose
1064 <     * submission queues in method doSubmit. In the future, this may
1064 >     * submission queues in method externalPush. In the future, this may
1065       * also incorporate a means to implement different task rejection
1066       * and resubmission policies.
1067       *
# Line 1139 | Line 1069 | public class ForkJoinPool extends Abstra
1069       * the same way but are initialized and updated using slightly
1070       * different mechanics. Both are initialized using the same
1071       * approach as in class ThreadLocal, where successive values are
1072 <     * unlikely to collide with previous values. This is done during
1073 <     * registration for workers, but requires a separate AtomicInteger
1074 <     * for submitters. Seeds are then randomly modified upon
1145 <     * collisions using xorshifts, which requires a non-zero seed.
1072 >     * unlikely to collide with previous values. Seeds are then
1073 >     * randomly modified upon collisions using xorshifts, which
1074 >     * requires a non-zero seed.
1075       */
1076      static final class Submitter {
1077          int seed;
1078 <        Submitter() {
1150 <            int s = nextSubmitterSeed.getAndAdd(SEED_INCREMENT);
1151 <            seed = (s == 0) ? 1 : s; // ensure non-zero
1152 <        }
1078 >        Submitter(int s) { seed = s; }
1079      }
1080  
1081 <    /** ThreadLocal class for Submitters */
1082 <    static final class ThreadSubmitter extends ThreadLocal<Submitter> {
1083 <        public Submitter initialValue() { return new Submitter(); }
1158 <    }
1081 >    /** Property prefix for constructing common pool */
1082 >    private static final String propPrefix =
1083 >        "java.util.concurrent.ForkJoinPool.common.";
1084  
1085      // static fields (initialized in static initializer below)
1086  
# Line 1166 | Line 1091 | public class ForkJoinPool extends Abstra
1091      public static final ForkJoinWorkerThreadFactory
1092          defaultForkJoinWorkerThreadFactory;
1093  
1169
1170    /** Property prefix for constructing common pool */
1171    private static final String propPrefix =
1172        "java.util.concurrent.ForkJoinPool.common.";
1173
1094      /**
1095       * Common (static) pool. Non-null for public use unless a static
1096 <     * construction exception, but internal usages must null-check on
1097 <     * use.
1096 >     * construction exception, but internal usages null-check on use
1097 >     * to paranoically avoid potential initialization circularities
1098 >     * as well as to simplify generated code.
1099       */
1100      static final ForkJoinPool commonPool;
1101  
1102      /**
1103 <     * Common pool parallelism. Must equal commonPool.parallelism.
1103 >     * Permission required for callers of methods that may start or
1104 >     * kill threads.
1105       */
1106 <    static final int commonPoolParallelism;
1106 >    private static final RuntimePermission modifyThreadPermission;
1107  
1108      /**
1109 <     * Generator for assigning sequence numbers as pool names.
1109 >     * Per-thread submission bookkeeping. Shared across all pools
1110 >     * to reduce ThreadLocal pollution and because random motion
1111 >     * to avoid contention in one pool is likely to hold for others.
1112 >     * Lazily initialized on first submission (but null-checked
1113 >     * in other contexts to avoid unnecessary initialization).
1114       */
1115 <    private static final AtomicInteger poolNumberGenerator;
1115 >    static final ThreadLocal<Submitter> submitters;
1116  
1117      /**
1118 <     * Generator for initial hashes/seeds for submitters. Accessed by
1193 <     * Submitter class constructor.
1118 >     * Common pool parallelism. Must equal commonPool.parallelism.
1119       */
1120 <    static final AtomicInteger nextSubmitterSeed;
1120 >    static final int commonPoolParallelism;
1121  
1122      /**
1123 <     * Permission required for callers of methods that may start or
1199 <     * kill threads.
1123 >     * Sequence number for creating workerNamePrefix.
1124       */
1125 <    private static final RuntimePermission modifyThreadPermission;
1125 >    private static int poolNumberSequence;
1126  
1127      /**
1128 <     * Per-thread submission bookkeeping. Shared across all pools
1129 <     * to reduce ThreadLocal pollution and because random motion
1206 <     * to avoid contention in one pool is likely to hold for others.
1128 >     * Return the next sequence number. We don't expect this to
1129 >     * ever contend so use simple builtin sync.
1130       */
1131 <    private static final ThreadSubmitter submitters;
1131 >    private static final synchronized int nextPoolId() {
1132 >        return ++poolNumberSequence;
1133 >    }
1134  
1135      // static constants
1136  
1137      /**
1138 <     * Initial timeout value (in nanoseconds) for the thread triggering
1139 <     * quiescence to park waiting for new work. On timeout, the thread
1140 <     * will instead try to shrink the number of workers.
1138 >     * Initial timeout value (in nanoseconds) for the thread
1139 >     * triggering quiescence to park waiting for new work. On timeout,
1140 >     * the thread will instead try to shrink the number of
1141 >     * workers. The value should be large enough to avoid overly
1142 >     * aggressive shrinkage during most transient stalls (long GCs
1143 >     * etc).
1144       */
1145 <    private static final long IDLE_TIMEOUT      = 1000L * 1000L * 1000L; // 1sec
1145 >    private static final long IDLE_TIMEOUT      = 2000L * 1000L * 1000L; // 2sec
1146  
1147      /**
1148       * Timeout value when there are more threads than parallelism level
1149       */
1150 <    private static final long FAST_IDLE_TIMEOUT =  100L * 1000L * 1000L;
1150 >    private static final long FAST_IDLE_TIMEOUT =  200L * 1000L * 1000L;
1151  
1152      /**
1153       * The maximum stolen->joining link depth allowed in method
1154 <     * tryHelpStealer.  Must be a power of two. This value also
1227 <     * controls the maximum number of times to try to help join a task
1228 <     * without any apparent progress or change in pool state before
1229 <     * giving up and blocking (see awaitJoin).  Depths for legitimate
1154 >     * tryHelpStealer.  Must be a power of two.  Depths for legitimate
1155       * chains are unbounded, but we use a fixed constant to avoid
1156       * (otherwise unchecked) cycles and to bound staleness of
1157       * traversal parameters at the expense of sometimes blocking when
# Line 1235 | Line 1160 | public class ForkJoinPool extends Abstra
1160      private static final int MAX_HELP = 64;
1161  
1162      /**
1238     * Secondary time-based bound (in nanosecs) for helping attempts
1239     * before trying compensated blocking in awaitJoin. Used in
1240     * conjunction with MAX_HELP to reduce variance due to different
1241     * polling rates associated with different helping options. The
1242     * value should roughly approximate the time required to create
1243     * and/or activate a worker thread.
1244     */
1245    private static final long COMPENSATION_DELAY = 1L << 18; // ~0.25 millisec
1246
1247    /**
1163       * Increment for seed generators. See class ThreadLocal for
1164       * explanation.
1165       */
# Line 1278 | Line 1193 | public class ForkJoinPool extends Abstra
1193       * scan for them to avoid queuing races. Note however that
1194       * eventCount updates lag releases so usage requires care.
1195       *
1196 <     * Field runState is an int packed with:
1196 >     * Field plock is an int packed with:
1197       * SHUTDOWN: true if shutdown is enabled (1 bit)
1198 <     * SEQ:  a sequence number updated upon (de)registering workers (30 bits)
1199 <     * INIT: set true after workQueues array construction (1 bit)
1198 >     * SEQ:  a sequence lock, with PL_LOCK bit set if locked (30 bits)
1199 >     * SIGNAL: set when threads may be waiting on the lock (1 bit)
1200       *
1201       * The sequence number enables simple consistency checks:
1202       * Staleness of read-only operations on the workQueues array can
1203 <     * be checked by comparing runState before vs after the reads.
1203 >     * be checked by comparing plock before vs after the reads.
1204       */
1205  
1206      // bit positions/shifts for fields
# Line 1297 | Line 1212 | public class ForkJoinPool extends Abstra
1212      // bounds
1213      private static final int  SMASK      = 0xffff;  // short bits
1214      private static final int  MAX_CAP    = 0x7fff;  // max #workers - 1
1215 <    private static final int  SQMASK     = 0xfffe;  // even short bits
1215 >    private static final int  EVENMASK   = 0xfffe;  // even short bits
1216 >    private static final int  SQMASK     = 0x007e;  // max 64 (even) slots
1217      private static final int  SHORT_SIGN = 1 << 15;
1218      private static final int  INT_SIGN   = 1 << 31;
1219  
# Line 1322 | Line 1238 | public class ForkJoinPool extends Abstra
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
1241 >    // plock bits
1242      private static final int SHUTDOWN    = 1 << 31;
1243 +    private static final int PL_LOCK     = 2;
1244 +    private static final int PL_SIGNAL   = 1;
1245 +    private static final int PL_SPINS    = 1 << 8;
1246  
1247      // access mode for WorkQueue
1248      static final int LIFO_QUEUE          =  0;
# Line 1338 | Line 1257 | public class ForkJoinPool extends Abstra
1257       * declaration order and may differ across JVMs, but the following
1258       * empirically works OK on current JVMs.
1259       */
1341
1260      volatile long stealCount;                  // collects worker counts
1261      volatile long ctl;                         // main pool control
1262      final int parallelism;                     // parallelism level
1263      final int localMode;                       // per-worker scheduling mode
1264 <    volatile int nextWorkerNumber;             // to create worker name string
1265 <    final int submitMask;                      // submit queue index bound
1348 <    int nextSeed;                              // for initializing worker seeds
1349 <    volatile int mainLock;                     // spinlock for array updates
1350 <    volatile int runState;                     // shutdown status and seq
1264 >    volatile int indexSeed;                    // worker/submitter index seed
1265 >    volatile int plock;                        // shutdown status and seqLock
1266      WorkQueue[] workQueues;                    // main registry
1267      final ForkJoinWorkerThreadFactory factory; // factory for new workers
1268      final Thread.UncaughtExceptionHandler ueh; // per-worker UEH
1269      final String workerNamePrefix;             // to create worker name string
1270  
1271      /*
1272 <     * Mechanics for main lock protecting worker array updates.  Uses
1273 <     * the same strategy as ConcurrentHashMap bins -- a spinLock for
1274 <     * normal cases, but falling back to builtin lock when (rarely)
1275 <     * needed.  See internal ConcurrentHashMap documentation for
1276 <     * explanation.
1277 <     */
1278 <
1279 <    static final int LOCK_WAITING = 2; // bit to indicate need for signal
1280 <    static final int MAX_LOCK_SPINS = 1 << 8;
1281 <
1282 <    private void tryAwaitMainLock() {
1283 <        int spins = MAX_LOCK_SPINS, r = 0, h;
1284 <        while (((h = mainLock) & 1) != 0) {
1285 <            if (r == 0)
1272 >     * Acquires the plock lock to protect worker array and related
1273 >     * updates. This method is called only if an initial CAS on plock
1274 >     * fails. This acts as a spinLock for normal cases, but falls back
1275 >     * to builtin monitor to block when (rarely) needed. This would be
1276 >     * a terrible idea for a highly contended lock, but works fine as
1277 >     * a more conservative alternative to a pure spinlock.  See
1278 >     * internal ConcurrentHashMap documentation for further
1279 >     * explanation of nearly the same construction.
1280 >     */
1281 >    private int acquirePlock() {
1282 >        int spins = PL_SPINS, r = 0, ps, nps;
1283 >        for (;;) {
1284 >            if (((ps = plock) & PL_LOCK) == 0 &&
1285 >                U.compareAndSwapInt(this, PLOCK, ps, nps = ps + PL_LOCK))
1286 >                return nps;
1287 >            else if (r == 0)
1288                  r = ThreadLocalRandom.current().nextInt(); // randomize spins
1289              else if (spins >= 0) {
1290                  r ^= r << 1; r ^= r >>> 3; r ^= r << 10; // xorshift
1291                  if (r >= 0)
1292                      --spins;
1293              }
1294 <            else if (U.compareAndSwapInt(this, MAINLOCK, h, h | LOCK_WAITING)) {
1294 >            else if (U.compareAndSwapInt(this, PLOCK, ps, ps | PL_SIGNAL)) {
1295                  synchronized (this) {
1296 <                    if ((mainLock & LOCK_WAITING) != 0) {
1296 >                    if ((plock & PL_SIGNAL) != 0) {
1297                          try {
1298                              wait();
1299                          } catch (InterruptedException ie) {
1300 <                            Thread.currentThread().interrupt();
1300 >                            try {
1301 >                                Thread.currentThread().interrupt();
1302 >                            } catch (SecurityException ignore) {
1303 >                            }
1304                          }
1305                      }
1306                      else
1307 <                        notifyAll(); // possibly won race vs signaller
1307 >                        notifyAll();
1308                  }
1389                break;
1309              }
1310          }
1311      }
1312  
1394    //  Creating, registering, and deregistering workers
1395
1313      /**
1314 <     * Tries to create and start a worker
1314 >     * Unlocks and signals any thread waiting for plock. Called only
1315 >     * when CAS of seq value for unlock fails.
1316       */
1317 <    private void addWorker() {
1318 <        Throwable ex = null;
1319 <        ForkJoinWorkerThread wt = null;
1402 <        try {
1403 <            if ((wt = factory.newThread(this)) != null) {
1404 <                wt.start();
1405 <                return;
1406 <            }
1407 <        } catch (Throwable e) {
1408 <            ex = e;
1409 <        }
1410 <        deregisterWorker(wt, ex); // adjust counts etc on failure
1317 >    private void releasePlock(int ps) {
1318 >        plock = ps;
1319 >        synchronized (this) { notifyAll(); }
1320      }
1321  
1322 <    /**
1414 <     * Callback from ForkJoinWorkerThread constructor to assign a
1415 <     * public name. This must be separate from registerWorker because
1416 <     * it is called during the "super" constructor call in
1417 <     * ForkJoinWorkerThread.
1418 <     */
1419 <    final String nextWorkerName() {
1420 <        int n;
1421 <        do {} while(!U.compareAndSwapInt(this, NEXTWORKERNUMBER,
1422 <                                         n = nextWorkerNumber, ++n));
1423 <        return workerNamePrefix.concat(Integer.toString(n));
1424 <    }
1322 >    //  Registering and deregistering workers
1323  
1324      /**
1325       * Callback from ForkJoinWorkerThread constructor to establish its
# Line 1433 | Line 1331 | public class ForkJoinPool extends Abstra
1331       * @param w the worker's queue
1332       */
1333      final void registerWorker(WorkQueue w) {
1334 <        while (!U.compareAndSwapInt(this, MAINLOCK, 0, 1))
1335 <            tryAwaitMainLock();
1334 >        int s, ps; // generate a rarely colliding candidate index seed
1335 >        do {} while (!U.compareAndSwapInt(this, INDEXSEED,
1336 >                                          s = indexSeed, s += SEED_INCREMENT) ||
1337 >                     s == 0); // skip 0
1338 >        if (((ps = plock) & PL_LOCK) != 0 ||
1339 >            !U.compareAndSwapInt(this, PLOCK, ps, ps += PL_LOCK))
1340 >            ps = acquirePlock();
1341 >        int nps = (ps & SHUTDOWN) | ((ps + PL_LOCK) & ~SHUTDOWN);
1342          try {
1343              WorkQueue[] ws;
1344 <            if ((ws = workQueues) == null)
1345 <                ws = workQueues = new WorkQueue[submitMask + 1];
1346 <            if (w != null) {
1443 <                int rs, n =  ws.length, m = n - 1;
1444 <                int s = nextSeed += SEED_INCREMENT; // rarely-colliding sequence
1445 <                w.seed = (s == 0) ? 1 : s;          // ensure non-zero seed
1344 >            if (w != null && (ws = workQueues) != null) {
1345 >                w.seed = s;
1346 >                int n = ws.length, m = n - 1;
1347                  int r = (s << 1) | 1;               // use odd-numbered indices
1348                  if (ws[r &= m] != null) {           // collision
1349                      int probes = 0;                 // step by approx half size
1350 <                    int step = (n <= 4) ? 2 : ((n >>> 1) & SQMASK) + 2;
1350 >                    int step = (n <= 4) ? 2 : ((n >>> 1) & EVENMASK) + 2;
1351                      while (ws[r = (r + step) & m] != null) {
1352                          if (++probes >= n) {
1353                              workQueues = ws = Arrays.copyOf(ws, n <<= 1);
# Line 1456 | Line 1357 | public class ForkJoinPool extends Abstra
1357                      }
1358                  }
1359                  w.eventCount = w.poolIndex = r;     // establish before recording
1360 <                ws[r] = w;                          // also update seq
1460 <                runState = ((rs = runState) & SHUTDOWN) | ((rs + 2) & ~SHUTDOWN);
1360 >                ws[r] = w;
1361              }
1362          } finally {
1363 <            if (!U.compareAndSwapInt(this, MAINLOCK, 1, 0)) {
1364 <                mainLock = 0;
1465 <                synchronized (this) { notifyAll(); };
1466 <            }
1363 >            if (!U.compareAndSwapInt(this, PLOCK, ps, nps))
1364 >                releasePlock(nps);
1365          }
1468
1366      }
1367  
1368      /**
1369       * Final callback from terminating worker, as well as upon failure
1370 <     * to construct or start a worker in addWorker.  Removes record of
1371 <     * worker from array, and adjusts counts. If pool is shutting
1372 <     * down, tries to complete termination.
1370 >     * to construct or start a worker.  Removes record of worker from
1371 >     * array, and adjusts counts. If pool is shutting down, tries to
1372 >     * complete termination.
1373       *
1374 <     * @param wt the worker thread or null if addWorker failed
1374 >     * @param wt the worker thread or null if construction failed
1375       * @param ex the exception causing failure, or null if none
1376       */
1377      final void deregisterWorker(ForkJoinWorkerThread wt, Throwable ex) {
1378          WorkQueue w = null;
1379          if (wt != null && (w = wt.workQueue) != null) {
1380 <            w.runState = -1;                // ensure runState is set
1381 <            long steals = w.totalSteals + w.nsteals, sc;
1382 <            do {} while(!U.compareAndSwapLong(this, STEALCOUNT,
1383 <                                              sc = stealCount, sc + steals));
1384 <            int idx = w.poolIndex;
1385 <            while (!U.compareAndSwapInt(this, MAINLOCK, 0, 1))
1386 <                tryAwaitMainLock();
1380 >            int ps;
1381 >            collectStealCount(w);
1382 >            w.qlock = -1;                // ensure set
1383 >            if (((ps = plock) & PL_LOCK) != 0 ||
1384 >                !U.compareAndSwapInt(this, PLOCK, ps, ps += PL_LOCK))
1385 >                ps = acquirePlock();
1386 >            int nps = (ps & SHUTDOWN) | ((ps + PL_LOCK) & ~SHUTDOWN);
1387              try {
1388 +                int idx = w.poolIndex;
1389                  WorkQueue[] ws = workQueues;
1390                  if (ws != null && idx >= 0 && idx < ws.length && ws[idx] == w)
1391                      ws[idx] = null;
1392              } finally {
1393 <                if (!U.compareAndSwapInt(this, MAINLOCK, 1, 0)) {
1394 <                    mainLock = 0;
1497 <                    synchronized (this) { notifyAll(); };
1498 <                }
1393 >                if (!U.compareAndSwapInt(this, PLOCK, ps, nps))
1394 >                    releasePlock(nps);
1395              }
1396          }
1397  
# Line 1508 | Line 1404 | public class ForkJoinPool extends Abstra
1404          if (!tryTerminate(false, false) && w != null) {
1405              w.cancelAll();                  // cancel remaining tasks
1406              if (w.array != null)            // suppress signal if never ran
1407 <                signalWork();               // wake up or create replacement
1407 >                signalWork(null, 1);        // wake up or create replacement
1408              if (ex == null)                 // help clean refs on way out
1409                  ForkJoinTask.helpExpungeStaleExceptions();
1410          }
1411  
1412          if (ex != null)                     // rethrow
1413 <            U.throwException(ex);
1413 >            ForkJoinTask.rethrow(ex);
1414 >    }
1415 >
1416 >    /**
1417 >     * Collect worker steal count into total. Called on termination
1418 >     * and upon int overflow of local count. (There is a possible race
1419 >     * in the latter case vs any caller of getStealCount, which can
1420 >     * make its results less accurate than usual.)
1421 >     */
1422 >    final void collectStealCount(WorkQueue w) {
1423 >        if (w != null) {
1424 >            long sc;
1425 >            int ns = w.nsteals;
1426 >            w.nsteals = 0; // handle overflow
1427 >            long steals = (ns >= 0) ? ns : 1L + (long)(Integer.MAX_VALUE);
1428 >            do {} while (!U.compareAndSwapLong(this, STEALCOUNT,
1429 >                                               sc = stealCount, sc + steals));
1430 >        }
1431      }
1432  
1433      // Submissions
# Line 1522 | Line 1435 | public class ForkJoinPool extends Abstra
1435      /**
1436       * Unless shutting down, adds the given task to a submission queue
1437       * at submitter's current queue index (modulo submission
1438 <     * range). If no queue exists at the index, one is created.  If
1439 <     * the queue is busy, another index is randomly chosen. The
1527 <     * submitMask bounds the effective number of queues to the
1528 <     * (nearest power of two for) parallelism level.
1438 >     * range). Only the most common path is directly handled in this
1439 >     * method. All others are relayed to fullExternalPush.
1440       *
1441       * @param task the task. Caller must ensure non-null.
1442       */
1443 <    private void doSubmit(ForkJoinTask<?> task) {
1444 <        Submitter s = submitters.get();
1445 <        for (int r = s.seed, m = submitMask;;) {
1446 <            WorkQueue[] ws; WorkQueue q;
1447 <            int k = r & m & SQMASK;          // use only even indices
1448 <            if (runState < 0)
1449 <                throw new RejectedExecutionException(); // shutting down
1450 <            else if ((ws = workQueues) == null || ws.length <= k) {
1451 <                while (!U.compareAndSwapInt(this, MAINLOCK, 0, 1))
1452 <                    tryAwaitMainLock();
1453 <                try {
1454 <                    if (workQueues == null)
1455 <                        workQueues = new WorkQueue[submitMask + 1];
1456 <                } finally {
1546 <                    if (!U.compareAndSwapInt(this, MAINLOCK, 1, 0)) {
1547 <                        mainLock = 0;
1548 <                        synchronized (this) { notifyAll(); };
1549 <                    }
1550 <                }
1551 <            }
1552 <            else if ((q = ws[k]) == null) {  // create new queue
1553 <                WorkQueue nq = new WorkQueue(this, null, SHARED_QUEUE);
1554 <                while (!U.compareAndSwapInt(this, MAINLOCK, 0, 1))
1555 <                    tryAwaitMainLock();
1556 <                try {
1557 <                    int rs = runState;       // to update seq
1558 <                    if (ws == workQueues && ws[k] == null) {
1559 <                        ws[k] = nq;
1560 <                        runState = ((rs & SHUTDOWN) | ((rs + 2) & ~SHUTDOWN));
1561 <                    }
1562 <                } finally {
1563 <                    if (!U.compareAndSwapInt(this, MAINLOCK, 1, 0)) {
1564 <                        mainLock = 0;
1565 <                        synchronized (this) { notifyAll(); };
1566 <                    }
1567 <                }
1568 <            }
1569 <            else if (q.trySharedPush(task)) {
1570 <                signalWork();
1443 >    final void externalPush(ForkJoinTask<?> task) {
1444 >        WorkQueue[] ws; WorkQueue q; Submitter z; int m; ForkJoinTask<?>[] a;
1445 >        if ((z = submitters.get()) != null && plock > 0 &&
1446 >            (ws = workQueues) != null && (m = (ws.length - 1)) >= 0 &&
1447 >            (q = ws[m & z.seed & SQMASK]) != null &&
1448 >            U.compareAndSwapInt(q, QLOCK, 0, 1)) { // lock
1449 >            int s = q.top, n;
1450 >            if ((a = q.array) != null && a.length > (n = s + 1 - q.base)) {
1451 >                U.putObject(a, (long)(((a.length - 1) & s) << ASHIFT) + ABASE,
1452 >                            task);
1453 >                q.top = s + 1;                     // push on to deque
1454 >                q.qlock = 0;
1455 >                if (n <= 1)
1456 >                    signalWork(q, 1);
1457                  return;
1458              }
1459 <            else if (m > 1) {                // move to a different index
1574 <                r ^= r << 13;                // same xorshift as WorkQueues
1575 <                r ^= r >>> 17;
1576 <                s.seed = r ^= r << 5;
1577 <            }
1578 <            else
1579 <                Thread.yield();              // yield if no alternatives
1459 >            q.qlock = 0;
1460          }
1461 +        fullExternalPush(task);
1462      }
1463  
1464      /**
1465 <     * Submits the given (non-null) task to the common pool, if possible.
1466 <     */
1467 <    static void submitToCommonPool(ForkJoinTask<?> task) {
1468 <        ForkJoinPool p;
1469 <        if ((p = commonPool) == null)
1470 <            throw new RejectedExecutionException("Common Pool Unavailable");
1471 <        p.doSubmit(task);
1472 <    }
1473 <
1474 <    /**
1475 <     * Returns true if caller is (or may be) submitter to the common
1476 <     * pool, and not all workers are active, and there appear to be
1477 <     * tasks in the associated submission queue.
1478 <     */
1479 <    static boolean canHelpCommonPool() {
1480 <        ForkJoinPool p; WorkQueue[] ws; WorkQueue q;
1481 <        int k = submitters.get().seed & SQMASK;
1482 <        return ((p = commonPool) != null &&
1483 <                (int)(p.ctl >> AC_SHIFT) < 0 &&
1484 <                (ws = p.workQueues) != null &&
1485 <                ws.length > (k &= p.submitMask) &&
1486 <                (q = ws[k]) != null &&
1487 <                q.top - q.base > 0);
1488 <    }
1489 <
1490 <    /**
1491 <     * Returns true if the given task was submitted to common pool
1492 <     * and has not yet commenced execution, and is available for
1493 <     * removal according to execution policies; if so removing the
1494 <     * submission from the pool.
1495 <     *
1496 <     * @param task the task
1497 <     * @return true if successful
1498 <     */
1499 <    static boolean tryUnsubmitFromCommonPool(ForkJoinTask<?> task) {
1500 <        // Peek, looking for task and eligibility before
1501 <        // using trySharedUnpush to actually take it under lock
1502 <        ForkJoinPool p; WorkQueue[] ws; WorkQueue q;
1503 <        ForkJoinTask<?>[] a; int s;
1504 <        int k = submitters.get().seed & SQMASK;
1505 <        return ((p = commonPool) != null &&
1506 <                (int)(p.ctl >> AC_SHIFT) < 0 &&
1507 <                (ws = p.workQueues) != null &&
1508 <                ws.length > (k &= p.submitMask) &&
1509 <                (q = ws[k]) != null &&
1510 <                (a = q.array) != null &&
1511 <                (s = q.top - 1) - q.base >= 0 &&
1512 <                s >= 0 && s < a.length &&
1513 <                a[s] == task &&
1514 <                q.trySharedUnpush(task));
1515 <    }
1516 <
1517 <    /**
1518 <     * Tries to pop a task from common pool with given root
1519 <     */
1520 <    static ForkJoinTask<?> popCCFromCommonPool(CountedCompleter<?> root) {
1521 <        ForkJoinPool p; WorkQueue[] ws; WorkQueue q;
1522 <        ForkJoinTask<?> t;
1523 <        int k = submitters.get().seed & SQMASK;
1524 <        if (root != null &&
1525 <            (p = commonPool) != null &&
1645 <            (int)(p.ctl >> AC_SHIFT) < 0 &&
1646 <            (ws = p.workQueues) != null &&
1647 <            ws.length > (k &= p.submitMask) &&
1648 <            (q = ws[k]) != null && q.top - q.base > 0 &&
1649 <            root.status < 0 &&
1650 <            (t = q.sharedPopCC(root)) != null)
1651 <            return t;
1652 <        return null;
1465 >     * Full version of externalPush. This method is called, among
1466 >     * other times, upon the first submission of the first task to the
1467 >     * pool, so must perform secondary initialization: creating
1468 >     * workQueue array and setting plock to a valid value. It also
1469 >     * detects first submission by an external thread by looking up
1470 >     * its ThreadLocal, and creates a new shared queue if the one at
1471 >     * index if empty or contended. The lock bodies must be
1472 >     * exception-free (so no try/finally) so we optimistically
1473 >     * allocate new queues/arrays outside the locks and throw them
1474 >     * away if (very rarely) not needed. Note that the plock seq value
1475 >     * can eventually wrap around zero, but if so harmlessly fails to
1476 >     * reinitialize.
1477 >     */
1478 >    private void fullExternalPush(ForkJoinTask<?> task) {
1479 >        for (Submitter z = null;;) {
1480 >            WorkQueue[] ws; WorkQueue q; int ps, m, r, s;
1481 >            if ((ps = plock) < 0)
1482 >                throw new RejectedExecutionException();
1483 >            else if ((ws = workQueues) == null || (m = ws.length - 1) < 0) {
1484 >                int n = parallelism - 1; n |= n >>> 1; n |= n >>> 2;
1485 >                n |= n >>> 4; n |= n >>> 8; n |= n >>> 16;
1486 >                WorkQueue[] nws = new WorkQueue[(n + 1) << 1]; // power of two
1487 >                if ((ps & PL_LOCK) != 0 ||
1488 >                    !U.compareAndSwapInt(this, PLOCK, ps, ps += PL_LOCK))
1489 >                    ps = acquirePlock();
1490 >                if ((ws = workQueues) == null)
1491 >                    workQueues = nws;
1492 >                int nps = (ps & SHUTDOWN) | ((ps + PL_LOCK) & ~SHUTDOWN);
1493 >                if (!U.compareAndSwapInt(this, PLOCK, ps, nps))
1494 >                    releasePlock(nps);
1495 >            }
1496 >            else if (z == null && (z = submitters.get()) == null) {
1497 >                if (U.compareAndSwapInt(this, INDEXSEED,
1498 >                                        s = indexSeed, s += SEED_INCREMENT) &&
1499 >                    s != 0) // skip 0
1500 >                    submitters.set(z = new Submitter(s));
1501 >            }
1502 >            else {
1503 >                int k = (r = z.seed) & m & SQMASK;
1504 >                if ((q = ws[k]) == null && (ps & PL_LOCK) == 0) {
1505 >                    (q = new WorkQueue(this, null, SHARED_QUEUE)).poolIndex = k;
1506 >                    if (((ps = plock) & PL_LOCK) != 0 ||
1507 >                        !U.compareAndSwapInt(this, PLOCK, ps, ps += PL_LOCK))
1508 >                        ps = acquirePlock();
1509 >                    WorkQueue w = null;
1510 >                    if ((ws = workQueues) != null && k < ws.length &&
1511 >                        (w = ws[k]) == null)
1512 >                        ws[k] = q;
1513 >                    else
1514 >                        q = w;
1515 >                    int nps = (ps & SHUTDOWN) | ((ps + PL_LOCK) & ~SHUTDOWN);
1516 >                    if (!U.compareAndSwapInt(this, PLOCK, ps, nps))
1517 >                        releasePlock(nps);
1518 >                }
1519 >                if (q != null && q.qlock == 0 && q.fullPush(task, false))
1520 >                    return;
1521 >                r ^= r << 13;                // same xorshift as WorkQueues
1522 >                r ^= r >>> 17;
1523 >                z.seed = r ^= r << 5;        // move to a different index
1524 >            }
1525 >        }
1526      }
1527  
1655
1528      // Maintaining ctl counts
1529  
1530      /**
# Line 1664 | Line 1536 | public class ForkJoinPool extends Abstra
1536      }
1537  
1538      /**
1539 <     * Tries to create one or activate one or more workers if too few are active.
1540 <     */
1541 <    final void signalWork() {
1542 <        long c; int u;
1543 <        while ((u = (int)((c = ctl) >>> 32)) < 0) {     // too few active
1544 <            WorkQueue[] ws = workQueues; int e, i; WorkQueue w; Thread p;
1545 <            if ((e = (int)c) > 0) {                     // at least one waiting
1546 <                if (ws != null && (i = e & SMASK) < ws.length &&
1539 >     * Tries to create (at most one) or activate (possibly several)
1540 >     * workers if too few are active. On contention failure, continues
1541 >     * until at least one worker is signalled or the given queue is
1542 >     * empty or all workers are active.
1543 >     *
1544 >     * @param q if non-null, the queue holding tasks to be signalled
1545 >     * @param signals the target number of signals.
1546 >     */
1547 >    final void signalWork(WorkQueue q, int signals) {
1548 >        long c; int e, u, i; WorkQueue[] ws; WorkQueue w; Thread p;
1549 >        while ((u = (int)((c = ctl) >>> 32)) < 0) {
1550 >            if ((e = (int)c) > 0) {
1551 >                if ((ws = workQueues) != null && ws.length > (i = e & SMASK) &&
1552                      (w = ws[i]) != null && w.eventCount == (e | INT_SIGN)) {
1553                      long nc = (((long)(w.nextWait & E_MASK)) |
1554                                 ((long)(u + UAC_UNIT) << 32));
1555                      if (U.compareAndSwapLong(this, CTL, c, nc)) {
1556                          w.eventCount = (e + E_SEQ) & E_MASK;
1557                          if ((p = w.parker) != null)
1558 <                            U.unpark(p);                // activate and release
1559 <                        break;
1558 >                            U.unpark(p);
1559 >                        if (--signals <= 0)
1560 >                            break;
1561                      }
1562 +                    else
1563 +                        signals = 1;
1564 +                    if ((q != null && q.queueSize() == 0))
1565 +                        break;
1566                  }
1567                  else
1568                      break;
1569              }
1570 <            else if (e == 0 && (u & SHORT_SIGN) != 0) { // too few total
1570 >            else if (e == 0 && (u & SHORT_SIGN) != 0) {
1571                  long nc = (long)(((u + UTC_UNIT) & UTC_MASK) |
1572                                   ((u + UAC_UNIT) & UAC_MASK)) << 32;
1573                  if (U.compareAndSwapLong(this, CTL, c, nc)) {
1574 <                    addWorker();
1574 >                    ForkJoinWorkerThread wt = null;
1575 >                    Throwable ex = null;
1576 >                    boolean started = false;
1577 >                    try {
1578 >                        ForkJoinWorkerThreadFactory fac;
1579 >                        if ((fac = factory) != null &&
1580 >                            (wt = fac.newThread(this)) != null) {
1581 >                            wt.start();
1582 >                            started = true;
1583 >                        }
1584 >                    } catch (Throwable rex) {
1585 >                        ex = rex;
1586 >                    }
1587 >                    if (!started)
1588 >                        deregisterWorker(wt, ex); // adjust counts on failure
1589                      break;
1590                  }
1591              }
# Line 1704 | Line 1600 | public class ForkJoinPool extends Abstra
1600       * Top-level runloop for workers, called by ForkJoinWorkerThread.run.
1601       */
1602      final void runWorker(WorkQueue w) {
1603 <        w.growArray(false);         // initialize queue array in this thread
1604 <        do { w.runTask(scan(w)); } while (w.runState >= 0);
1603 >        // initialize queue array in this thread
1604 >        w.array = new ForkJoinTask<?>[WorkQueue.INITIAL_QUEUE_CAPACITY];
1605 >        do { w.runTask(scan(w)); } while (w.qlock >= 0);
1606      }
1607  
1608      /**
# Line 1721 | Line 1618 | public class ForkJoinPool extends Abstra
1618       * relative prime, checking each at least once).  The scan
1619       * terminates upon either finding a non-empty queue, or completing
1620       * the sweep. If the worker is not inactivated, it takes and
1621 <     * returns a task from this queue.  On failure to find a task, we
1621 >     * returns a task from this queue. Otherwise, if not activated, it
1622 >     * signals workers (that may include itself) and returns so caller
1623 >     * can retry. Also returns for trtry if the worker array may have
1624 >     * changed during an empty scan.  On failure to find a task, we
1625       * take one of the following actions, after which the caller will
1626       * retry calling this method unless terminated.
1627       *
1628       * * If pool is terminating, terminate the worker.
1629       *
1730     * * If not a complete sweep, try to release a waiting worker.  If
1731     * the scan terminated because the worker is inactivated, then the
1732     * released worker will often be the calling worker, and it can
1733     * succeed obtaining a task on the next call. Or maybe it is
1734     * another worker, but with same net effect. Releasing in other
1735     * cases as well ensures that we have enough workers running.
1736     *
1630       * * If not already enqueued, try to inactivate and enqueue the
1631       * worker on wait queue. Or, if inactivating has caused the pool
1632       * to be quiescent, relay to idleAwaitWork to check for
1633       * termination and possibly shrink pool.
1634       *
1635 <     * * If already inactive, and the caller has run a task since the
1636 <     * last empty scan, return (to allow rescan) unless others are
1637 <     * also inactivated.  Field WorkQueue.rescans counts down on each
1745 <     * scan to ensure eventual inactivation and blocking.
1746 <     *
1747 <     * * If already enqueued and none of the above apply, park
1748 <     * awaiting signal,
1635 >     * * If already enqueued and none of the above apply, possibly
1636 >     * (with 1/2 probability) park awaiting signal, else lingering to
1637 >     * help scan and signal.
1638       *
1639       * @param w the worker (via its WorkQueue)
1640       * @return a task or null if none found
1641       */
1642      private final ForkJoinTask<?> scan(WorkQueue w) {
1643 <        WorkQueue[] ws;                       // first update random seed
1643 >        WorkQueue[] ws; WorkQueue q;           // first update random seed
1644          int r = w.seed; r ^= r << 13; r ^= r >>> 17; w.seed = r ^= r << 5;
1645 <        int rs = runState, m;                 // volatile read order matters
1645 >        int ps = plock, m;                     // volatile read order matters
1646          if ((ws = workQueues) != null && (m = ws.length - 1) > 0) {
1647 <            int ec = w.eventCount;            // ec is negative if inactive
1648 <            int step = (r >>> 16) | 1;        // relative prime
1649 <            for (int j = (m + 1) << 2; ; r += step) {
1650 <                WorkQueue q; ForkJoinTask<?> t; ForkJoinTask<?>[] a; int b;
1647 >            int ec = w.eventCount;             // ec is negative if inactive
1648 >            int step = (r >>> 16) | 1;         // relatively prime
1649 >            for (int j = (m + 1) << 2;  ; --j, r += step) {
1650 >                ForkJoinTask<?> t; ForkJoinTask<?>[] a; int b, n;
1651                  if ((q = ws[r & m]) != null && (b = q.base) - q.top < 0 &&
1652 <                    (a = q.array) != null) {  // probably nonempty
1652 >                    (a = q.array) != null) {   // probably nonempty
1653                      int i = (((a.length - 1) & b) << ASHIFT) + ABASE;
1654                      t = (ForkJoinTask<?>)U.getObjectVolatile(a, i);
1655                      if (q.base == b && ec >= 0 && t != null &&
1656                          U.compareAndSwapObject(a, i, t, null)) {
1657 <                        if (q.top - (q.base = b + 1) > 0)
1658 <                            signalWork();    // help pushes signal
1659 <                        return t;
1660 <                    }
1661 <                    else if (ec < 0 || j <= m) {
1662 <                        rs = 0;               // mark scan as imcomplete
1663 <                        break;                // caller can retry after release
1657 >                        if ((n = q.top - (q.base = b + 1)) > 0)
1658 >                            signalWork(q, n);
1659 >                        return t;              // taken
1660 >                    }
1661 >                    if (j < m || (ec < 0 && (ec = w.eventCount) < 0)) {
1662 >                        if ((n = q.queueSize() - 1) > 0)
1663 >                            signalWork(q, n);
1664 >                        break;                 // let caller retry after signal
1665                      }
1666                  }
1667 <                if (--j < 0)
1668 <                    break;
1669 <            }
1670 <
1671 <            long c = ctl; int e = (int)c, a = (int)(c >> AC_SHIFT), nr, ns;
1672 <            if (e < 0)                        // decode ctl on empty scan
1673 <                w.runState = -1;              // pool is terminating
1674 <            else if (rs == 0 || rs != runState) { // incomplete scan
1675 <                WorkQueue v; Thread p;        // try to release a waiter
1676 <                if (e > 0 && a < 0 && w.eventCount == ec &&
1677 <                    (v = ws[e & m]) != null && v.eventCount == (e | INT_SIGN)) {
1678 <                    long nc = ((long)(v.nextWait & E_MASK) |
1679 <                               ((c + AC_UNIT) & (AC_MASK|TC_MASK)));
1680 <                    if (ctl == c && U.compareAndSwapLong(this, CTL, c, nc)) {
1681 <                        v.eventCount = (e + E_SEQ) & E_MASK;
1682 <                        if ((p = v.parker) != null)
1683 <                            U.unpark(p);
1667 >                else if (j < 0) {              // end of scan
1668 >                    long c = ctl; int e;
1669 >                    if (plock != ps)           // incomplete sweep
1670 >                        break;
1671 >                    if ((e = (int)c) < 0)      // pool is terminating
1672 >                        w.qlock = -1;
1673 >                    else if (ec >= 0) {        // try to enqueue/inactivate
1674 >                        long nc = ((long)ec |
1675 >                                   ((c - AC_UNIT) & (AC_MASK|TC_MASK)));
1676 >                        w.nextWait = e;
1677 >                        w.eventCount = ec | INT_SIGN; // mark as inactive
1678 >                        if (ctl != c ||
1679 >                            !U.compareAndSwapLong(this, CTL, c, nc))
1680 >                            w.eventCount = ec; // unmark on CAS failure
1681 >                        else if ((int)(c >> AC_SHIFT) == 1 - parallelism)
1682 >                            idleAwaitWork(w, nc, c);  // quiescent
1683 >                    }
1684 >                    else if (w.seed >= 0 && w.eventCount < 0) {
1685 >                        Thread wt = Thread.currentThread();
1686 >                        Thread.interrupted();  // clear status
1687 >                        U.putObject(wt, PARKBLOCKER, this);
1688 >                        w.parker = wt;         // emulate LockSupport.park
1689 >                        if (w.eventCount < 0)  // recheck
1690 >                            U.park(false, 0L);
1691 >                        w.parker = null;
1692 >                        U.putObject(wt, PARKBLOCKER, null);
1693                      }
1694 <                }
1796 <            }
1797 <            else if (ec >= 0) {               // try to enqueue/inactivate
1798 <                long nc = (long)ec | ((c - AC_UNIT) & (AC_MASK|TC_MASK));
1799 <                w.nextWait = e;
1800 <                w.eventCount = ec | INT_SIGN; // mark as inactive
1801 <                if (ctl != c || !U.compareAndSwapLong(this, CTL, c, nc))
1802 <                    w.eventCount = ec;        // unmark on CAS failure
1803 <                else {
1804 <                    if ((ns = w.nsteals) != 0) {
1805 <                        w.nsteals = 0;        // set rescans if ran task
1806 <                        w.rescans = (a > 0) ? 0 : a + parallelism;
1807 <                        w.totalSteals += ns;
1808 <                    }
1809 <                    if (a == 1 - parallelism) // quiescent
1810 <                        idleAwaitWork(w, nc, c);
1811 <                }
1812 <            }
1813 <            else if (w.eventCount < 0) {      // already queued
1814 <                int ac = a + parallelism;
1815 <                if ((nr = w.rescans) > 0)     // continue rescanning
1816 <                    w.rescans = (ac < nr) ? ac : nr - 1;
1817 <                else if (((w.seed >>> 16) & ac) == 0) { // randomize park
1818 <                    Thread.interrupted();     // clear status
1819 <                    Thread wt = Thread.currentThread();
1820 <                    U.putObject(wt, PARKBLOCKER, this);
1821 <                    w.parker = wt;            // emulate LockSupport.park
1822 <                    if (w.eventCount < 0)     // recheck
1823 <                        U.park(false, 0L);
1824 <                    w.parker = null;
1825 <                    U.putObject(wt, PARKBLOCKER, null);
1694 >                    break;
1695                  }
1696              }
1697          }
# Line 1842 | Line 1711 | public class ForkJoinPool extends Abstra
1711       * @param prevCtl the ctl value to restore if thread is terminated
1712       */
1713      private void idleAwaitWork(WorkQueue w, long currentCtl, long prevCtl) {
1714 <        if (w.eventCount < 0 && !tryTerminate(false, false) &&
1715 <            (int)prevCtl != 0 && !hasQueuedSubmissions() && ctl == currentCtl) {
1714 >        if (w.eventCount < 0 &&
1715 >            (this == commonPool || !tryTerminate(false, false)) &&
1716 >            (int)prevCtl != 0) {
1717              int dc = -(short)(currentCtl >>> TC_SHIFT);
1718              long parkTime = dc < 0 ? FAST_IDLE_TIMEOUT: (dc + 1) * IDLE_TIMEOUT;
1719              long deadline = System.nanoTime() + parkTime - 100000L; // 1ms slop
# Line 1861 | Line 1731 | public class ForkJoinPool extends Abstra
1731                  if (deadline - System.nanoTime() <= 0L &&
1732                      U.compareAndSwapLong(this, CTL, currentCtl, prevCtl)) {
1733                      w.eventCount = (w.eventCount + E_SEQ) | E_MASK;
1734 <                    w.runState = -1;   // shrink
1734 >                    w.qlock = -1;   // shrink
1735                      break;
1736                  }
1737              }
# Line 1869 | Line 1739 | public class ForkJoinPool extends Abstra
1739      }
1740  
1741      /**
1742 +     * Scans through queues looking for work while joining a task;
1743 +     * if any are present, signals.
1744 +     *
1745 +     * @param task to return early if done
1746 +     * @param origin an index to start scan
1747 +     */
1748 +    final int helpSignal(ForkJoinTask<?> task, int origin) {
1749 +        WorkQueue[] ws; WorkQueue q; int m, n, s;
1750 +        if (task != null && (ws = workQueues) != null &&
1751 +            (m = ws.length - 1) >= 0) {
1752 +            for (int i = 0; i <= m; ++i) {
1753 +                if ((s = task.status) < 0)
1754 +                    return s;
1755 +                if ((q = ws[(i + origin) & m]) != null &&
1756 +                    (n = q.queueSize()) > 0) {
1757 +                    signalWork(q, n);
1758 +                    if ((int)(ctl >> AC_SHIFT) >= 0)
1759 +                        break;
1760 +                }
1761 +            }
1762 +        }
1763 +        return 0;
1764 +    }
1765 +
1766 +    /**
1767       * Tries to locate and execute tasks for a stealer of the given
1768       * task, or in turn one of its stealers, Traces currentSteal ->
1769       * currentJoin links looking for a thread working on a descendant
# Line 1955 | Line 1850 | public class ForkJoinPool extends Abstra
1850      }
1851  
1852      /**
1853 <     * If task is at base of some steal queue, steals and executes it.
1853 >     * Analog of tryHelpStealer for CountedCompleters. Tries to steal
1854 >     * and run tasks within the target's computation
1855 >     *
1856 >     * @param task the task to join
1857 >     * @param mode if shared, exit upon completing any task
1858 >     * if all workers are active
1859       *
1960     * @param joiner the joining worker
1961     * @param task the task
1860       */
1861 <    private void tryPollForAndExec(WorkQueue joiner, ForkJoinTask<?> task) {
1862 <        WorkQueue[] ws;
1863 <        if ((ws = workQueues) != null) {
1864 <            for (int j = 1; j < ws.length && task.status >= 0; j += 2) {
1865 <                WorkQueue q = ws[j];
1866 <                if (q != null && q.pollFor(task)) {
1867 <                    joiner.runSubtask(task);
1868 <                    break;
1861 >    private int helpComplete(ForkJoinTask<?> task, int mode) {
1862 >        WorkQueue[] ws; WorkQueue q; int m, n, s;
1863 >        if (task != null && (ws = workQueues) != null &&
1864 >            (m = ws.length - 1) >= 0) {
1865 >            for (int j = 1, origin = j;;) {
1866 >                if ((s = task.status) < 0)
1867 >                    return s;
1868 >                if ((q = ws[j & m]) != null && q.pollAndExecCC(task)) {
1869 >                    origin = j;
1870 >                    if (mode == SHARED_QUEUE && (int)(ctl >> AC_SHIFT) >= 0)
1871 >                        break;
1872                  }
1873 +                else if ((j = (j + 2) & m) == origin)
1874 +                    break;
1875              }
1876          }
1877 +        return 0;
1878      }
1879  
1880      /**
1881       * Tries to decrement active count (sometimes implicitly) and
1882       * possibly release or create a compensating worker in preparation
1883       * for blocking. Fails on contention or termination. Otherwise,
1884 <     * adds a new thread if no idle workers are available and either
1885 <     * pool would become completely starved or: (at least half
1982 <     * starved, and fewer than 50% spares exist, and there is at least
1983 <     * one task apparently available). Even though the availability
1984 <     * check requires a full scan, it is worthwhile in reducing false
1985 <     * alarms.
1986 <     *
1987 <     * @param task if non-null, a task being waited for
1988 <     * @param blocker if non-null, a blocker being waited for
1989 <     * @return true if the caller can block, else should recheck and retry
1884 >     * adds a new thread if no idle workers are available and pool
1885 >     * may become starved.
1886       */
1887 <    final boolean tryCompensate(ForkJoinTask<?> task, ManagedBlocker blocker) {
1888 <        int pc = parallelism, e;
1889 <        long c = ctl;
1890 <        WorkQueue[] ws = workQueues;
1891 <        if ((e = (int)c) >= 0 && ws != null) {
1892 <            int u, a, ac, hc;
1893 <            int tc = (short)((u = (int)(c >>> 32)) >>> UTC_SHIFT) + pc;
1894 <            boolean replace = false;
1895 <            if ((a = u >> UAC_SHIFT) <= 0) {
1896 <                if ((ac = a + pc) <= 1)
1897 <                    replace = true;
1898 <                else if ((e > 0 || (task != null &&
1899 <                                    ac <= (hc = pc >>> 1) && tc < pc + hc))) {
2004 <                    WorkQueue w;
2005 <                    for (int j = 0; j < ws.length; ++j) {
2006 <                        if ((w = ws[j]) != null && !w.isEmpty()) {
2007 <                            replace = true;
2008 <                            break;   // in compensation range and tasks available
2009 <                        }
2010 <                    }
1887 >    final boolean tryCompensate() {
1888 >        int pc = parallelism, e, u, i, tc; long c;
1889 >        WorkQueue[] ws; WorkQueue w; Thread p;
1890 >        if ((e = (int)(c = ctl)) >= 0 && (ws = workQueues) != null) {
1891 >            if (e != 0 && (i = e & SMASK) < ws.length &&
1892 >                (w = ws[i]) != null && w.eventCount == (e | INT_SIGN)) {
1893 >                long nc = ((long)(w.nextWait & E_MASK) |
1894 >                           (c & (AC_MASK|TC_MASK)));
1895 >                if (U.compareAndSwapLong(this, CTL, c, nc)) {
1896 >                    w.eventCount = (e + E_SEQ) & E_MASK;
1897 >                    if ((p = w.parker) != null)
1898 >                        U.unpark(p);
1899 >                    return true;   // replace with idle worker
1900                  }
1901              }
1902 <            if ((task == null || task.status >= 0) && // recheck need to block
1903 <                (blocker == null || !blocker.isReleasable()) && ctl == c) {
1904 <                if (!replace) {          // no compensation
1905 <                    long nc = ((c - AC_UNIT) & AC_MASK) | (c & ~AC_MASK);
1906 <                    if (U.compareAndSwapLong(this, CTL, c, nc))
1907 <                        return true;
1908 <                }
1909 <                else if (e != 0) {       // release an idle worker
1910 <                    WorkQueue w; Thread p; int i;
1911 <                    if ((i = e & SMASK) < ws.length && (w = ws[i]) != null) {
1912 <                        long nc = ((long)(w.nextWait & E_MASK) |
1913 <                                   (c & (AC_MASK|TC_MASK)));
1914 <                        if (w.eventCount == (e | INT_SIGN) &&
1915 <                            U.compareAndSwapLong(this, CTL, c, nc)) {
1916 <                            w.eventCount = (e + E_SEQ) & E_MASK;
1917 <                            if ((p = w.parker) != null)
2029 <                                U.unpark(p);
1902 >            else if ((short)((u = (int)(c >>> 32)) >>> UTC_SHIFT) >= 0 &&
1903 >                     (u >> UAC_SHIFT) + pc > 1) {
1904 >                long nc = ((c - AC_UNIT) & AC_MASK) | (c & ~AC_MASK);
1905 >                if (U.compareAndSwapLong(this, CTL, c, nc))
1906 >                    return true;    // no compensation
1907 >            }
1908 >            else if ((tc = u + pc) < MAX_CAP) {
1909 >                long nc = ((c + TC_UNIT) & TC_MASK) | (c & ~TC_MASK);
1910 >                if (U.compareAndSwapLong(this, CTL, c, nc)) {
1911 >                    Throwable ex = null;
1912 >                    ForkJoinWorkerThread wt = null;
1913 >                    try {
1914 >                        ForkJoinWorkerThreadFactory fac;
1915 >                        if ((fac = factory) != null &&
1916 >                            (wt = fac.newThread(this)) != null) {
1917 >                            wt.start();
1918                              return true;
1919                          }
1920 +                    } catch (Throwable rex) {
1921 +                        ex = rex;
1922                      }
1923 <                }
2034 <                else if (tc < MAX_CAP) { // create replacement
2035 <                    long nc = ((c + TC_UNIT) & TC_MASK) | (c & ~TC_MASK);
2036 <                    if (U.compareAndSwapLong(this, CTL, c, nc)) {
2037 <                        addWorker();
2038 <                        return true;
2039 <                    }
1923 >                    deregisterWorker(wt, ex); // adjust counts etc
1924                  }
1925              }
1926          }
# Line 2051 | Line 1935 | public class ForkJoinPool extends Abstra
1935       * @return task status on exit
1936       */
1937      final int awaitJoin(WorkQueue joiner, ForkJoinTask<?> task) {
1938 <        int s;
1939 <        if ((s = task.status) >= 0) {
1938 >        int s = 0;
1939 >        if (joiner != null && task != null && (s = task.status) >= 0) {
1940              ForkJoinTask<?> prevJoin = joiner.currentJoin;
1941              joiner.currentJoin = task;
1942 <            long startTime = 0L;
1943 <            for (int k = 0;;) {
1944 <                if ((s = (joiner.isEmpty() ?           // try to help
1945 <                          tryHelpStealer(joiner, task) :
1946 <                          joiner.tryRemoveAndExec(task))) == 0 &&
1947 <                    (s = task.status) >= 0) {
1948 <                    if (k == 0) {
1949 <                        startTime = System.nanoTime();
1950 <                        tryPollForAndExec(joiner, task); // check uncommon case
1951 <                    }
1952 <                    else if ((k & (MAX_HELP - 1)) == 0 &&
1953 <                             System.nanoTime() - startTime >=
1954 <                             COMPENSATION_DELAY &&
1955 <                             tryCompensate(task, null)) {
1956 <                        if (task.trySetSignal()) {
1957 <                            synchronized (task) {
1958 <                                if (task.status >= 0) {
2075 <                                    try {                // see ForkJoinTask
2076 <                                        task.wait();     //  for explanation
2077 <                                    } catch (InterruptedException ie) {
2078 <                                    }
1942 >            do {} while ((s = task.status) >= 0 &&
1943 >                         joiner.queueSize() > 0 &&
1944 >                         joiner.tryRemoveAndExec(task)); // process local tasks
1945 >            if (s >= 0 && (s = task.status) >= 0 &&
1946 >                (s = helpSignal(task, joiner.poolIndex)) >= 0 &&
1947 >                (task instanceof CountedCompleter))
1948 >                s = helpComplete(task, LIFO_QUEUE);
1949 >            while (s >= 0 && (s = task.status) >= 0) {
1950 >                if ((joiner.queueSize() > 0 ||           // try helping
1951 >                     (s = tryHelpStealer(joiner, task)) == 0) &&
1952 >                    (s = task.status) >= 0 && tryCompensate()) {
1953 >                    if (task.trySetSignal() && (s = task.status) >= 0) {
1954 >                        synchronized (task) {
1955 >                            if (task.status >= 0) {
1956 >                                try {                // see ForkJoinTask
1957 >                                    task.wait();     //  for explanation
1958 >                                } catch (InterruptedException ie) {
1959                                  }
2080                                else
2081                                    task.notifyAll();
1960                              }
1961 +                            else
1962 +                                task.notifyAll();
1963                          }
2084                        long c;                          // re-activate
2085                        do {} while (!U.compareAndSwapLong
2086                                     (this, CTL, c = ctl, c + AC_UNIT));
1964                      }
1965 +                    long c;                          // re-activate
1966 +                    do {} while (!U.compareAndSwapLong
1967 +                                 (this, CTL, c = ctl, c + AC_UNIT));
1968                  }
2089                if (s < 0 || (s = task.status) < 0) {
2090                    joiner.currentJoin = prevJoin;
2091                    break;
2092                }
2093                else if ((k++ & (MAX_HELP - 1)) == MAX_HELP >>> 1)
2094                    Thread.yield();                     // for politeness
1969              }
1970 +            joiner.currentJoin = prevJoin;
1971          }
1972          return s;
1973      }
# Line 2104 | Line 1979 | public class ForkJoinPool extends Abstra
1979       *
1980       * @param joiner the joining worker
1981       * @param task the task
2107     * @return task status on exit
1982       */
1983 <    final int helpJoinOnce(WorkQueue joiner, ForkJoinTask<?> task) {
1983 >    final void helpJoinOnce(WorkQueue joiner, ForkJoinTask<?> task) {
1984          int s;
1985 <        while ((s = task.status) >= 0 &&
1986 <               (joiner.isEmpty() ?
1987 <                tryHelpStealer(joiner, task) :
1988 <                joiner.tryRemoveAndExec(task)) != 0)
1989 <            ;
1990 <        return s;
1985 >        if (joiner != null && task != null && (s = task.status) >= 0) {
1986 >            ForkJoinTask<?> prevJoin = joiner.currentJoin;
1987 >            joiner.currentJoin = task;
1988 >            do {} while ((s = task.status) >= 0 &&
1989 >                         joiner.queueSize() > 0 &&
1990 >                         joiner.tryRemoveAndExec(task));
1991 >            if (s >= 0 && (s = task.status) >= 0 &&
1992 >                (s = helpSignal(task, joiner.poolIndex)) >= 0 &&
1993 >                (task instanceof CountedCompleter))
1994 >                s = helpComplete(task, LIFO_QUEUE);
1995 >            if (s >= 0 && joiner.queueSize() == 0) {
1996 >                do {} while (task.status >= 0 &&
1997 >                             tryHelpStealer(joiner, task) > 0);
1998 >            }
1999 >            joiner.currentJoin = prevJoin;
2000 >        }
2001      }
2002  
2003      /**
# Line 2121 | Line 2005 | public class ForkJoinPool extends Abstra
2005       * during a random, then cyclic scan, else null.  This method must
2006       * be retried by caller if, by the time it tries to use the queue,
2007       * it is empty.
2008 +     * @param r a (random) seed for scanning
2009       */
2010 <    private WorkQueue findNonEmptyStealQueue(WorkQueue w) {
2126 <        // Similar to loop in scan(), but ignoring submissions
2127 <        int r = w.seed; r ^= r << 13; r ^= r >>> 17; w.seed = r ^= r << 5;
2010 >    private WorkQueue findNonEmptyStealQueue(int r) {
2011          int step = (r >>> 16) | 1;
2012          for (WorkQueue[] ws;;) {
2013 <            int rs = runState, m;
2013 >            int ps = plock, m;
2014              if ((ws = workQueues) == null || (m = ws.length - 1) < 1)
2015                  return null;
2016              for (int j = (m + 1) << 2; ; r += step) {
2017                  WorkQueue q = ws[((r << 1) | 1) & m];
2018 <                if (q != null && !q.isEmpty())
2018 >                if (q != null && q.queueSize() > 0)
2019                      return q;
2020                  else if (--j < 0) {
2021 <                    if (runState == rs)
2021 >                    if (plock == ps)
2022                          return null;
2023                      break;
2024                  }
# Line 2154 | Line 2037 | public class ForkJoinPool extends Abstra
2037              ForkJoinTask<?> localTask; // exhaust local queue
2038              while ((localTask = w.nextLocalTask()) != null)
2039                  localTask.doExec();
2040 <            WorkQueue q = findNonEmptyStealQueue(w);
2040 >            // Similar to loop in scan(), but ignoring submissions
2041 >            WorkQueue q = findNonEmptyStealQueue(w.nextSeed());
2042              if (q != null) {
2043                  ForkJoinTask<?> t; int b;
2044                  if (!active) {      // re-establish active count
# Line 2185 | Line 2069 | public class ForkJoinPool extends Abstra
2069      }
2070  
2071      /**
2188     * Restricted version of helpQuiescePool for non-FJ callers
2189     */
2190    static void externalHelpQuiescePool() {
2191        ForkJoinPool p; WorkQueue[] ws; WorkQueue q, sq;
2192        ForkJoinTask<?>[] a; int b;
2193        ForkJoinTask<?> t = null;
2194        int k = submitters.get().seed & SQMASK;
2195        if ((p = commonPool) != null &&
2196            (int)(p.ctl >> AC_SHIFT) < 0 &&
2197            (ws = p.workQueues) != null &&
2198            ws.length > (k &= p.submitMask) &&
2199            (q = ws[k]) != null) {
2200            while (q.top - q.base > 0) {
2201                if ((t = q.sharedPop()) != null)
2202                    break;
2203            }
2204            if (t == null && (sq = p.findNonEmptyStealQueue(q)) != null &&
2205                (b = sq.base) - sq.top < 0)
2206                t = sq.pollAt(b);
2207            if (t != null)
2208                t.doExec();
2209        }
2210    }
2211
2212    /**
2072       * Gets and removes a local or stolen task for the given worker.
2073       *
2074       * @return a task, if available
# Line 2219 | Line 2078 | public class ForkJoinPool extends Abstra
2078              WorkQueue q; int b;
2079              if ((t = w.nextLocalTask()) != null)
2080                  return t;
2081 <            if ((q = findNonEmptyStealQueue(w)) == null)
2081 >            if ((q = findNonEmptyStealQueue(w.nextSeed())) == null)
2082                  return null;
2083              if ((b = q.base) - q.top < 0 && (t = q.pollAt(b)) != null)
2084                  return t;
# Line 2227 | Line 2086 | public class ForkJoinPool extends Abstra
2086      }
2087  
2088      /**
2089 <     * Returns the approximate (non-atomic) number of idle threads per
2090 <     * active thread to offset steal queue size for method
2091 <     * ForkJoinTask.getSurplusQueuedTaskCount().
2092 <     */
2093 <    final int idlePerActive() {
2094 <        // Approximate at powers of two for small values, saturate past 4
2095 <        int p = parallelism;
2096 <        int a = p + (int)(ctl >> AC_SHIFT);
2097 <        return (a > (p >>>= 1) ? 0 :
2098 <                a > (p >>>= 1) ? 1 :
2099 <                a > (p >>>= 1) ? 2 :
2100 <                a > (p >>>= 1) ? 4 :
2101 <                8);
2102 <    }
2103 <
2104 <    /**
2105 <     * Returns approximate submission queue length for the given caller
2106 <     */
2107 <    static int getEstimatedSubmitterQueueLength() {
2108 <        ForkJoinPool p; WorkQueue[] ws; WorkQueue q;
2109 <        int k = submitters.get().seed & SQMASK;
2110 <        return ((p = commonPool) != null &&
2111 <                p.runState >= 0 &&
2112 <                (ws = p.workQueues) != null &&
2113 <                ws.length > (k &= p.submitMask) &&
2114 <                (q = ws[k]) != null) ?
2115 <            q.queueSize() : 0;
2089 >     * Returns a cheap heuristic guide for task partitioning when
2090 >     * programmers, frameworks, tools, or languages have little or no
2091 >     * idea about task granularity.  In essence by offering this
2092 >     * method, we ask users only about tradeoffs in overhead vs
2093 >     * expected throughput and its variance, rather than how finely to
2094 >     * partition tasks.
2095 >     *
2096 >     * In a steady state strict (tree-structured) computation, each
2097 >     * thread makes available for stealing enough tasks for other
2098 >     * threads to remain active. Inductively, if all threads play by
2099 >     * the same rules, each thread should make available only a
2100 >     * constant number of tasks.
2101 >     *
2102 >     * The minimum useful constant is just 1. But using a value of 1
2103 >     * would require immediate replenishment upon each steal to
2104 >     * maintain enough tasks, which is infeasible.  Further,
2105 >     * partitionings/granularities of offered tasks should minimize
2106 >     * steal rates, which in general means that threads nearer the top
2107 >     * of computation tree should generate more than those nearer the
2108 >     * bottom. In perfect steady state, each thread is at
2109 >     * approximately the same level of computation tree. However,
2110 >     * producing extra tasks amortizes the uncertainty of progress and
2111 >     * diffusion assumptions.
2112 >     *
2113 >     * So, users will want to use values larger, but not much larger
2114 >     * than 1 to both smooth over transient shortages and hedge
2115 >     * against uneven progress; as traded off against the cost of
2116 >     * extra task overhead. We leave the user to pick a threshold
2117 >     * value to compare with the results of this call to guide
2118 >     * decisions, but recommend values such as 3.
2119 >     *
2120 >     * When all threads are active, it is on average OK to estimate
2121 >     * surplus strictly locally. In steady-state, if one thread is
2122 >     * maintaining say 2 surplus tasks, then so are others. So we can
2123 >     * just use estimated queue length.  However, this strategy alone
2124 >     * leads to serious mis-estimates in some non-steady-state
2125 >     * conditions (ramp-up, ramp-down, other stalls). We can detect
2126 >     * many of these by further considering the number of "idle"
2127 >     * threads, that are known to have zero queued tasks, so
2128 >     * compensate by a factor of (#idle/#active) threads.
2129 >     *
2130 >     * Note: The approximation of #busy workers as #active workers is
2131 >     * not very good under current signalling scheme, and should be
2132 >     * improved.
2133 >     */
2134 >    static int getSurplusQueuedTaskCount() {
2135 >        Thread t; ForkJoinWorkerThread wt; ForkJoinPool pool; WorkQueue q;
2136 >        if (((t = Thread.currentThread()) instanceof ForkJoinWorkerThread)) {
2137 >            int b = (q = (wt = (ForkJoinWorkerThread)t).workQueue).base;
2138 >            int p = (pool = wt.pool).parallelism;
2139 >            int a = (int)(pool.ctl >> AC_SHIFT) + p;
2140 >            return q.top - b - (a > (p >>>= 1) ? 0 :
2141 >                                a > (p >>>= 1) ? 1 :
2142 >                                a > (p >>>= 1) ? 2 :
2143 >                                a > (p >>>= 1) ? 4 :
2144 >                                8);
2145 >        }
2146 >        return 0;
2147      }
2148  
2149      //  Termination
# Line 2273 | Line 2163 | public class ForkJoinPool extends Abstra
2163       * @return true if now terminating or terminated
2164       */
2165      private boolean tryTerminate(boolean now, boolean enable) {
2166 +        if (this == commonPool)                     // cannot shut down
2167 +            return false;
2168          for (long c;;) {
2169              if (((c = ctl) & STOP_BIT) != 0) {      // already terminating
2170                  if ((short)(c >>> TC_SHIFT) == -parallelism) {
2171 <                    synchronized(this) {
2171 >                    synchronized (this) {
2172                          notifyAll();                // signal when 0 workers
2173                      }
2174                  }
2175                  return true;
2176              }
2177 <            if (runState >= 0) {                    // not yet enabled
2177 >            if (plock >= 0) {                       // not yet enabled
2178 >                int ps;
2179                  if (!enable)
2180                      return false;
2181 <                while (!U.compareAndSwapInt(this, MAINLOCK, 0, 1))
2182 <                    tryAwaitMainLock();
2183 <                try {
2184 <                    runState |= SHUTDOWN;
2185 <                } finally {
2186 <                    if (!U.compareAndSwapInt(this, MAINLOCK, 1, 0)) {
2294 <                        mainLock = 0;
2295 <                        synchronized (this) { notifyAll(); };
2296 <                    }
2297 <                }
2181 >                if (((ps = plock) & PL_LOCK) != 0 ||
2182 >                    !U.compareAndSwapInt(this, PLOCK, ps, ps += PL_LOCK))
2183 >                    ps = acquirePlock();
2184 >                int nps = SHUTDOWN;
2185 >                if (!U.compareAndSwapInt(this, PLOCK, ps, nps))
2186 >                    releasePlock(nps);
2187              }
2188              if (!now) {                             // check if idle & no tasks
2189                  if ((int)(c >> AC_SHIFT) != -parallelism ||
# Line 2317 | Line 2206 | public class ForkJoinPool extends Abstra
2206                          int n = ws.length;
2207                          for (int i = 0; i < n; ++i) {
2208                              if ((w = ws[i]) != null) {
2209 <                                w.runState = -1;
2209 >                                w.qlock = -1;
2210                                  if (pass > 0) {
2211                                      w.cancelAll();
2212                                      if (pass > 1)
# Line 2336 | Line 2225 | public class ForkJoinPool extends Abstra
2225                              if (w.eventCount == (e | INT_SIGN) &&
2226                                  U.compareAndSwapLong(this, CTL, cc, nc)) {
2227                                  w.eventCount = (e + E_SEQ) & E_MASK;
2228 <                                w.runState = -1;
2228 >                                w.qlock = -1;
2229                                  if ((p = w.parker) != null)
2230                                      U.unpark(p);
2231                              }
# Line 2347 | Line 2236 | public class ForkJoinPool extends Abstra
2236          }
2237      }
2238  
2239 +    // external operations on common pool
2240 +
2241 +    /**
2242 +     * Returns common pool queue for a thread that has submitted at
2243 +     * least one task.
2244 +     */
2245 +    static WorkQueue commonSubmitterQueue() {
2246 +        ForkJoinPool p; WorkQueue[] ws; int m; Submitter z;
2247 +        return ((z = submitters.get()) != null &&
2248 +                (p = commonPool) != null &&
2249 +                (ws = p.workQueues) != null &&
2250 +                (m = ws.length - 1) >= 0) ?
2251 +            ws[m & z.seed & SQMASK] : null;
2252 +    }
2253 +
2254 +    /**
2255 +     * Tries to pop the given task from submitter's queue in common pool.
2256 +     */
2257 +    static boolean tryExternalUnpush(ForkJoinTask<?> t) {
2258 +        ForkJoinPool p; WorkQueue[] ws; WorkQueue q; Submitter z;
2259 +        ForkJoinTask<?>[] a;  int m, s; long j;
2260 +        if ((z = submitters.get()) != null &&
2261 +            (p = commonPool) != null &&
2262 +            (ws = p.workQueues) != null &&
2263 +            (m = ws.length - 1) >= 0 &&
2264 +            (q = ws[m & z.seed & SQMASK]) != null &&
2265 +            (s = q.top) != q.base &&
2266 +            (a = q.array) != null &&
2267 +            U.getObjectVolatile
2268 +            (a, j = (((a.length - 1) & (s - 1)) << ASHIFT) + ABASE) == t &&
2269 +            U.compareAndSwapInt(q, QLOCK, 0, 1)) {
2270 +            if (q.array == a && q.top == s && // recheck
2271 +                U.compareAndSwapObject(a, j, t, null)) {
2272 +                q.top = s - 1;
2273 +                q.qlock = 0;
2274 +                return true;
2275 +            }
2276 +            q.qlock = 0;
2277 +        }
2278 +        return false;
2279 +    }
2280 +
2281 +    /**
2282 +     * Tries to pop and run local tasks within the same computation
2283 +     * as the given root. On failure, tries to help complete from
2284 +     * other queues via helpComplete.
2285 +     */
2286 +    private void externalHelpComplete(WorkQueue q, ForkJoinTask<?> root) {
2287 +        ForkJoinTask<?>[] a; int m;
2288 +        if (q != null && (a = q.array) != null && (m = (a.length - 1)) >= 0 &&
2289 +            root != null && root.status >= 0) {
2290 +            for (;;) {
2291 +                int s; Object o; CountedCompleter<?> task = null;
2292 +                if ((s = q.top) - q.base > 0) {
2293 +                    long j = ((m & (s - 1)) << ASHIFT) + ABASE;
2294 +                    if ((o = U.getObject(a, j)) != null &&
2295 +                        (o instanceof CountedCompleter)) {
2296 +                        CountedCompleter<?> t = (CountedCompleter<?>)o, r = t;
2297 +                        do {
2298 +                            if (r == root) {
2299 +                                if (U.compareAndSwapInt(q, QLOCK, 0, 1)) {
2300 +                                    if (q.array == a && q.top == s &&
2301 +                                        U.compareAndSwapObject(a, j, t, null)) {
2302 +                                        q.top = s - 1;
2303 +                                        task = t;
2304 +                                    }
2305 +                                    q.qlock = 0;
2306 +                                }
2307 +                                break;
2308 +                            }
2309 +                        } while ((r = r.completer) != null);
2310 +                    }
2311 +                }
2312 +                if (task != null)
2313 +                    task.doExec();
2314 +                if (root.status < 0 || (int)(ctl >> AC_SHIFT) >= 0)
2315 +                    break;
2316 +                if (task == null) {
2317 +                    if (helpSignal(root, q.poolIndex) >= 0)
2318 +                        helpComplete(root, SHARED_QUEUE);
2319 +                    break;
2320 +                }
2321 +            }
2322 +        }
2323 +    }
2324 +
2325 +    /**
2326 +     * Tries to help execute or signal availability of the given task
2327 +     * from submitter's queue in common pool.
2328 +     */
2329 +    static void externalHelpJoin(ForkJoinTask<?> t) {
2330 +        // Some hard-to-avoid overlap with tryExternalUnpush
2331 +        ForkJoinPool p; WorkQueue[] ws; WorkQueue q, w; Submitter z;
2332 +        ForkJoinTask<?>[] a;  int m, s, n; long j;
2333 +        if (t != null && t.status >= 0 &&
2334 +            (z = submitters.get()) != null &&
2335 +            (p = commonPool) != null &&
2336 +            (ws = p.workQueues) != null &&
2337 +            (m = ws.length - 1) >= 0 &&
2338 +            (q = ws[m & z.seed & SQMASK]) != null &&
2339 +            (a = q.array) != null) {
2340 +            if ((s = q.top) != q.base &&
2341 +                U.getObjectVolatile
2342 +                (a, j = (((a.length - 1) & (s - 1)) << ASHIFT) + ABASE) == t &&
2343 +                U.compareAndSwapInt(q, QLOCK, 0, 1)) {
2344 +                if (q.array == a && q.top == s &&
2345 +                    U.compareAndSwapObject(a, j, t, null)) {
2346 +                    q.top = s - 1;
2347 +                    q.qlock = 0;
2348 +                    t.doExec();
2349 +                }
2350 +                else
2351 +                    q.qlock = 0;
2352 +            }
2353 +            if (t.status >= 0) {
2354 +                if (t instanceof CountedCompleter)
2355 +                    p.externalHelpComplete(q, t);
2356 +                else
2357 +                    p.helpSignal(t, q.poolIndex);
2358 +            }
2359 +        }
2360 +    }
2361 +
2362 +    /**
2363 +     * Restricted version of helpQuiescePool for external callers
2364 +     */
2365 +    static void externalHelpQuiescePool() {
2366 +        ForkJoinPool p; ForkJoinTask<?> t; WorkQueue q; int b;
2367 +        int r = ThreadLocalRandom.current().nextInt();
2368 +        if ((p = commonPool) != null &&
2369 +            (q = p.findNonEmptyStealQueue(r)) != null &&
2370 +            (b = q.base) - q.top < 0 &&
2371 +            (t = q.pollAt(b)) != null)
2372 +            t.doExec();
2373 +    }
2374 +
2375      // Exported methods
2376  
2377      // Constructors
# Line 2424 | Line 2449 | public class ForkJoinPool extends Abstra
2449          this.localMode = asyncMode ? FIFO_QUEUE : LIFO_QUEUE;
2450          long np = (long)(-parallelism); // offset ctl counts
2451          this.ctl = ((np << AC_SHIFT) & AC_MASK) | ((np << TC_SHIFT) & TC_MASK);
2452 <        // Use nearest power 2 for workQueues size. See Hackers Delight sec 3.2.
2428 <        int n = parallelism - 1;
2429 <        n |= n >>> 1; n |= n >>> 2; n |= n >>> 4; n |= n >>> 8; n |= n >>> 16;
2430 <        this.submitMask = ((n + 1) << 1) - 1;
2431 <        int pn = poolNumberGenerator.incrementAndGet();
2452 >        int pn = nextPoolId();
2453          StringBuilder sb = new StringBuilder("ForkJoinPool-");
2454          sb.append(Integer.toString(pn));
2455          sb.append("-worker-");
2456          this.workerNamePrefix = sb.toString();
2436        this.runState = 1;              // set init flag
2457      }
2458  
2459      /**
2460       * Constructor for common pool, suitable only for static initialization.
2461       * Basically the same as above, but uses smallest possible initial footprint.
2462       */
2463 <    ForkJoinPool(int parallelism, int submitMask,
2463 >    ForkJoinPool(int parallelism, long ctl,
2464                   ForkJoinWorkerThreadFactory factory,
2465                   Thread.UncaughtExceptionHandler handler) {
2466 +        this.parallelism = parallelism;
2467 +        this.ctl = ctl;
2468          this.factory = factory;
2469          this.ueh = handler;
2448        this.submitMask = submitMask;
2449        this.parallelism = parallelism;
2450        long np = (long)(-parallelism);
2451        this.ctl = ((np << AC_SHIFT) & AC_MASK) | ((np << TC_SHIFT) & TC_MASK);
2470          this.localMode = LIFO_QUEUE;
2471          this.workerNamePrefix = "ForkJoinPool.commonPool-worker-";
2454        this.runState = 1;
2472      }
2473  
2474      /**
# Line 2460 | Line 2477 | public class ForkJoinPool extends Abstra
2477       * @return the common pool instance
2478       */
2479      public static ForkJoinPool commonPool() {
2480 <        ForkJoinPool p;
2464 <        if ((p = commonPool) == null)
2465 <            throw new Error("Common Pool Unavailable");
2466 <        return p;
2480 >        return commonPool; // cannot be null (if so, a static init error)
2481      }
2482  
2483      // Execution methods
# Line 2487 | Line 2501 | public class ForkJoinPool extends Abstra
2501      public <T> T invoke(ForkJoinTask<T> task) {
2502          if (task == null)
2503              throw new NullPointerException();
2504 <        doSubmit(task);
2504 >        externalPush(task);
2505          return task.join();
2506      }
2507  
# Line 2502 | Line 2516 | public class ForkJoinPool extends Abstra
2516      public void execute(ForkJoinTask<?> task) {
2517          if (task == null)
2518              throw new NullPointerException();
2519 <        doSubmit(task);
2519 >        externalPush(task);
2520      }
2521  
2522      // AbstractExecutorService methods
# Line 2520 | Line 2534 | public class ForkJoinPool extends Abstra
2534              job = (ForkJoinTask<?>) task;
2535          else
2536              job = new ForkJoinTask.AdaptedRunnableAction(task);
2537 <        doSubmit(job);
2537 >        externalPush(job);
2538      }
2539  
2540      /**
# Line 2535 | Line 2549 | public class ForkJoinPool extends Abstra
2549      public <T> ForkJoinTask<T> submit(ForkJoinTask<T> task) {
2550          if (task == null)
2551              throw new NullPointerException();
2552 <        doSubmit(task);
2552 >        externalPush(task);
2553          return task;
2554      }
2555  
# Line 2546 | Line 2560 | public class ForkJoinPool extends Abstra
2560       */
2561      public <T> ForkJoinTask<T> submit(Callable<T> task) {
2562          ForkJoinTask<T> job = new ForkJoinTask.AdaptedCallable<T>(task);
2563 <        doSubmit(job);
2563 >        externalPush(job);
2564          return job;
2565      }
2566  
# Line 2557 | Line 2571 | public class ForkJoinPool extends Abstra
2571       */
2572      public <T> ForkJoinTask<T> submit(Runnable task, T result) {
2573          ForkJoinTask<T> job = new ForkJoinTask.AdaptedRunnable<T>(task, result);
2574 <        doSubmit(job);
2574 >        externalPush(job);
2575          return job;
2576      }
2577  
# Line 2574 | Line 2588 | public class ForkJoinPool extends Abstra
2588              job = (ForkJoinTask<?>) task;
2589          else
2590              job = new ForkJoinTask.AdaptedRunnableAction(task);
2591 <        doSubmit(job);
2591 >        externalPush(job);
2592          return job;
2593      }
2594  
# Line 2596 | Line 2610 | public class ForkJoinPool extends Abstra
2610          try {
2611              for (Callable<T> t : tasks) {
2612                  ForkJoinTask<T> f = new ForkJoinTask.AdaptedCallable<T>(t);
2613 <                doSubmit(f);
2613 >                externalPush(f);
2614                  fs.add(f);
2615              }
2616              for (ForkJoinTask<T> f : fs)
# Line 2733 | Line 2747 | public class ForkJoinPool extends Abstra
2747          if ((ws = workQueues) != null) {
2748              for (int i = 1; i < ws.length; i += 2) {
2749                  if ((w = ws[i]) != null)
2750 <                    count += w.totalSteals;
2750 >                    count += w.nsteals;
2751              }
2752          }
2753          return count;
# Line 2790 | Line 2804 | public class ForkJoinPool extends Abstra
2804          WorkQueue[] ws; WorkQueue w;
2805          if ((ws = workQueues) != null) {
2806              for (int i = 0; i < ws.length; i += 2) {
2807 <                if ((w = ws[i]) != null && !w.isEmpty())
2807 >                if ((w = ws[i]) != null && w.queueSize() != 0)
2808                      return true;
2809              }
2810          }
# Line 2869 | Line 2883 | public class ForkJoinPool extends Abstra
2883                          qs += size;
2884                      else {
2885                          qt += size;
2886 <                        st += w.totalSteals;
2886 >                        st += w.nsteals;
2887                          if (w.isApparentlyUnblocked())
2888                              ++rc;
2889                      }
# Line 2885 | Line 2899 | public class ForkJoinPool extends Abstra
2899          if ((c & STOP_BIT) != 0)
2900              level = (tc == 0) ? "Terminated" : "Terminating";
2901          else
2902 <            level = runState < 0 ? "Shutting down" : "Running";
2902 >            level = plock < 0 ? "Shutting down" : "Running";
2903          return super.toString() +
2904              "[" + level +
2905              ", parallelism = " + pc +
# Line 2914 | Line 2928 | public class ForkJoinPool extends Abstra
2928       */
2929      public void shutdown() {
2930          checkPermission();
2931 <        if (this != commonPool)
2918 <            tryTerminate(false, true);
2931 >        tryTerminate(false, true);
2932      }
2933  
2934      /**
# Line 2938 | Line 2951 | public class ForkJoinPool extends Abstra
2951       */
2952      public List<Runnable> shutdownNow() {
2953          checkPermission();
2954 <        if (this != commonPool)
2942 <            tryTerminate(true, true);
2954 >        tryTerminate(true, true);
2955          return Collections.emptyList();
2956      }
2957  
# Line 2979 | Line 2991 | public class ForkJoinPool extends Abstra
2991       * @return {@code true} if this pool has been shut down
2992       */
2993      public boolean isShutdown() {
2994 <        return runState < 0;
2994 >        return plock < 0;
2995      }
2996  
2997      /**
2998 <     * Blocks until all tasks have completed execution after a shutdown
2999 <     * request, or the timeout occurs, or the current thread is
3000 <     * interrupted, whichever happens first.
2998 >     * Blocks until all tasks have completed execution after a
2999 >     * shutdown request, or the timeout occurs, or the current thread
3000 >     * is interrupted, whichever happens first. Note that the {@link
3001 >     * #commonPool()} never terminates until program shutdown so
3002 >     * this method will always time out.
3003       *
3004       * @param timeout the maximum time to wait
3005       * @param unit the time unit of the timeout argument
# Line 3000 | Line 3014 | public class ForkJoinPool extends Abstra
3014              return true;
3015          long startTime = System.nanoTime();
3016          boolean terminated = false;
3017 <        synchronized(this) {
3017 >        synchronized (this) {
3018              for (long waitTime = nanos, millis = 0L;;) {
3019                  if (terminated = isTerminated() ||
3020                      waitTime <= 0L ||
# Line 3109 | Line 3123 | public class ForkJoinPool extends Abstra
3123      public static void managedBlock(ManagedBlocker blocker)
3124          throws InterruptedException {
3125          Thread t = Thread.currentThread();
3126 <        ForkJoinPool p = ((t instanceof ForkJoinWorkerThread) ?
3127 <                          ((ForkJoinWorkerThread)t).pool : null);
3128 <        while (!blocker.isReleasable()) {
3129 <            if (p == null || p.tryCompensate(null, blocker)) {
3130 <                try {
3131 <                    do {} while (!blocker.isReleasable() && !blocker.block());
3132 <                } finally {
3133 <                    if (p != null)
3126 >        if (t instanceof ForkJoinWorkerThread) {
3127 >            ForkJoinPool p = ((ForkJoinWorkerThread)t).pool;
3128 >            while (!blocker.isReleasable()) { // variant of helpSignal
3129 >                WorkQueue[] ws; WorkQueue q; int m, n;
3130 >                if ((ws = p.workQueues) != null && (m = ws.length - 1) >= 0) {
3131 >                    for (int i = 0; i <= m; ++i) {
3132 >                        if (blocker.isReleasable())
3133 >                            return;
3134 >                        if ((q = ws[i]) != null && (n = q.queueSize()) > 0) {
3135 >                            p.signalWork(q, n);
3136 >                            if ((int)(p.ctl >> AC_SHIFT) >= 0)
3137 >                                break;
3138 >                        }
3139 >                    }
3140 >                }
3141 >                if (p.tryCompensate()) {
3142 >                    try {
3143 >                        do {} while (!blocker.isReleasable() &&
3144 >                                     !blocker.block());
3145 >                    } finally {
3146                          p.incrementActiveCount();
3147 +                    }
3148 +                    break;
3149                  }
3122                break;
3150              }
3151          }
3152 +        else {
3153 +            do {} while (!blocker.isReleasable() &&
3154 +                         !blocker.block());
3155 +        }
3156      }
3157  
3158      // AbstractExecutorService overrides.  These rely on undocumented
# Line 3142 | Line 3173 | public class ForkJoinPool extends Abstra
3173      private static final long PARKBLOCKER;
3174      private static final int ABASE;
3175      private static final int ASHIFT;
3145    private static final long NEXTWORKERNUMBER;
3176      private static final long STEALCOUNT;
3177 <    private static final long MAINLOCK;
3177 >    private static final long PLOCK;
3178 >    private static final long INDEXSEED;
3179 >    private static final long QLOCK;
3180  
3181      static {
3182 <        poolNumberGenerator = new AtomicInteger();
3183 <        nextSubmitterSeed = new AtomicInteger(0x55555555);
3184 <        modifyThreadPermission = new RuntimePermission("modifyThread");
3185 <        defaultForkJoinWorkerThreadFactory =
3186 <            new DefaultForkJoinWorkerThreadFactory();
3187 <        submitters = new ThreadSubmitter();
3188 <        int s;
3182 >        // Establish common pool parameters
3183 >        // TBD: limit or report ignored exceptions?
3184 >
3185 >        int par = 0;
3186 >        ForkJoinWorkerThreadFactory fac = null;
3187 >        Thread.UncaughtExceptionHandler handler = null;
3188 >        try {
3189 >            String pp = System.getProperty(propPrefix + "parallelism");
3190 >            String hp = System.getProperty(propPrefix + "exceptionHandler");
3191 >            String fp = System.getProperty(propPrefix + "threadFactory");
3192 >            if (fp != null)
3193 >                fac = ((ForkJoinWorkerThreadFactory)ClassLoader.
3194 >                       getSystemClassLoader().loadClass(fp).newInstance());
3195 >            if (hp != null)
3196 >                handler = ((Thread.UncaughtExceptionHandler)ClassLoader.
3197 >                           getSystemClassLoader().loadClass(hp).newInstance());
3198 >            if (pp != null)
3199 >                par = Integer.parseInt(pp);
3200 >        } catch (Exception ignore) {
3201 >        }
3202 >
3203 >        int s; // initialize field offsets for CAS etc
3204          try {
3205              U = getUnsafe();
3206              Class<?> k = ForkJoinPool.class;
3160            Class<?> ak = ForkJoinTask[].class;
3207              CTL = U.objectFieldOffset
3208                  (k.getDeclaredField("ctl"));
3163            NEXTWORKERNUMBER = U.objectFieldOffset
3164                (k.getDeclaredField("nextWorkerNumber"));
3209              STEALCOUNT = U.objectFieldOffset
3210                  (k.getDeclaredField("stealCount"));
3211 <            MAINLOCK = U.objectFieldOffset
3212 <                (k.getDeclaredField("mainLock"));
3211 >            PLOCK = U.objectFieldOffset
3212 >                (k.getDeclaredField("plock"));
3213 >            INDEXSEED = U.objectFieldOffset
3214 >                (k.getDeclaredField("indexSeed"));
3215              Class<?> tk = Thread.class;
3216              PARKBLOCKER = U.objectFieldOffset
3217                  (tk.getDeclaredField("parkBlocker"));
3218 +            Class<?> wk = WorkQueue.class;
3219 +            QLOCK = U.objectFieldOffset
3220 +                (wk.getDeclaredField("qlock"));
3221 +            Class<?> ak = ForkJoinTask[].class;
3222              ABASE = U.arrayBaseOffset(ak);
3223              s = U.arrayIndexScale(ak);
3224              ASHIFT = 31 - Integer.numberOfLeadingZeros(s);
# Line 3177 | Line 3227 | public class ForkJoinPool extends Abstra
3227          }
3228          if ((s & (s-1)) != 0)
3229              throw new Error("data type scale not a power of two");
3230 <        try { // Establish common pool
3231 <            String pp = System.getProperty(propPrefix + "parallelism");
3232 <            String fp = System.getProperty(propPrefix + "threadFactory");
3233 <            String up = System.getProperty(propPrefix + "exceptionHandler");
3234 <            ForkJoinWorkerThreadFactory fac = (fp == null) ?
3235 <                defaultForkJoinWorkerThreadFactory :
3236 <                ((ForkJoinWorkerThreadFactory)ClassLoader.
3237 <                 getSystemClassLoader().loadClass(fp).newInstance());
3238 <            Thread.UncaughtExceptionHandler ueh = (up == null)? null :
3239 <                ((Thread.UncaughtExceptionHandler)ClassLoader.
3240 <                 getSystemClassLoader().loadClass(up).newInstance());
3241 <            int par;
3242 <            if ((pp == null || (par = Integer.parseInt(pp)) <= 0))
3243 <                par = Runtime.getRuntime().availableProcessors();
3244 <            if (par > MAX_CAP)
3245 <                par = MAX_CAP;
3246 <            commonPoolParallelism = par;
3247 <            int n = par - 1; // precompute submit mask
3248 <            n |= n >>> 1; n |= n >>> 2; n |= n >>> 4;
3249 <            n |= n >>> 8; n |= n >>> 16;
3250 <            int mask = ((n + 1) << 1) - 1;
3201 <            commonPool = new ForkJoinPool(par, mask, fac, ueh);
3202 <        } catch (Exception e) {
3203 <            throw new Error(e);
3204 <        }
3230 >
3231 >        /*
3232 >         * For extra caution, computations to set up pool state are
3233 >         * here; the constructor just assigns these values to fields.
3234 >         */
3235 >        ForkJoinWorkerThreadFactory defaultFac =
3236 >            defaultForkJoinWorkerThreadFactory =
3237 >            new DefaultForkJoinWorkerThreadFactory();
3238 >        if (fac == null)
3239 >            fac = defaultFac;
3240 >        if (par <= 0)
3241 >            par = Runtime.getRuntime().availableProcessors();
3242 >        if (par > MAX_CAP)
3243 >            par = MAX_CAP;
3244 >        long np = (long)(-par); // precompute initial ctl value
3245 >        long ct = ((np << AC_SHIFT) & AC_MASK) | ((np << TC_SHIFT) & TC_MASK);
3246 >
3247 >        commonPoolParallelism = par;
3248 >        commonPool = new ForkJoinPool(par, ct, fac, handler);
3249 >        modifyThreadPermission = new RuntimePermission("modifyThread");
3250 >        submitters = new ThreadLocal<Submitter>();
3251      }
3252  
3253      /**

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines