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

Comparing jsr166/src/jsr166e/ForkJoinPool.java (file contents):
Revision 1.3 by jsr166, Tue Aug 14 06:00:55 2012 UTC vs.
Revision 1.15 by jsr166, Sun Nov 18 06:31:13 2012 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines