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

Comparing jsr166/src/jsr166y/ForkJoinPool.java (file contents):
Revision 1.139 by dl, Wed Oct 31 12:49:24 2012 UTC vs.
Revision 1.140 by dl, Wed Nov 14 17:20:37 2012 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines