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.15 by jsr166, Sun Nov 18 06:31:13 2012 UTC vs.
Revision 1.66 by jsr166, Thu Nov 5 16:22:39 2015 UTC

# Line 6 | Line 6
6  
7   package jsr166e;
8  
9 + import java.lang.Thread.UncaughtExceptionHandler;
10   import java.util.ArrayList;
11   import java.util.Arrays;
12   import java.util.Collection;
# Line 17 | Line 18 | import java.util.concurrent.ExecutorServ
18   import java.util.concurrent.Future;
19   import java.util.concurrent.RejectedExecutionException;
20   import java.util.concurrent.RunnableFuture;
20 import java.util.concurrent.ThreadLocalRandom;
21   import java.util.concurrent.TimeUnit;
22  
23   /**
# Line 38 | Line 38 | import java.util.concurrent.TimeUnit;
38   * ForkJoinPool}s may also be appropriate for use with event-style
39   * tasks that are never joined.
40   *
41 < * <p>A static {@link #commonPool} is available and appropriate for
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
# Line 50 | Line 50 | import java.util.concurrent.TimeUnit;
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
53 > * threads, even if some tasks are stalled waiting to join others.
54 > * However, no such adjustments are guaranteed in the face of blocked
55 > * I/O or other unmanaged synchronization. The nested {@link
56   * ManagedBlocker} interface enables extension of the kinds of
57   * synchronization accommodated.
58   *
# Line 63 | Line 63 | import java.util.concurrent.TimeUnit;
63   * {@link #toString} returns indications of pool state in a
64   * convenient form for informal monitoring.
65   *
66 < * <p> As is the case with other ExecutorServices, there are three
66 > * <p>As is the case with other ExecutorServices, there are three
67   * main task execution methods summarized in the following table.
68   * These are designed to be used primarily by clients not already
69   * engaged in fork/join computations in the current pool.  The main
# Line 76 | Line 76 | import java.util.concurrent.TimeUnit;
76   * there is little difference among choice of methods.
77   *
78   * <table BORDER CELLPADDING=3 CELLSPACING=1>
79 + * <caption>Summary of task execution methods</caption>
80   *  <tr>
81   *    <td></td>
82   *    <td ALIGN=CENTER> <b>Call from non-fork/join clients</b></td>
83   *    <td ALIGN=CENTER> <b>Call from within fork/join computations</b></td>
84   *  </tr>
85   *  <tr>
86 < *    <td> <b>Arrange async execution</td>
86 > *    <td> <b>Arrange async execution</b></td>
87   *    <td> {@link #execute(ForkJoinTask)}</td>
88   *    <td> {@link ForkJoinTask#fork}</td>
89   *  </tr>
90   *  <tr>
91 < *    <td> <b>Await and obtain result</td>
91 > *    <td> <b>Await and obtain result</b></td>
92   *    <td> {@link #invoke(ForkJoinTask)}</td>
93   *    <td> {@link ForkJoinTask#invoke}</td>
94   *  </tr>
95   *  <tr>
96 < *    <td> <b>Arrange exec and obtain Future</td>
96 > *    <td> <b>Arrange exec and obtain Future</b></td>
97   *    <td> {@link #submit(ForkJoinTask)}</td>
98   *    <td> {@link ForkJoinTask#fork} (ForkJoinTasks <em>are</em> Futures)</td>
99   *  </tr>
100   * </table>
101   *
102   * <p>The common pool is by default constructed with default
103 < * parameters, but these may be controlled by setting three {@link
104 < * System#getProperty properties} with prefix {@code
105 < * java.util.concurrent.ForkJoinPool.common}: {@code parallelism} --
106 < * an integer greater than zero, {@code threadFactory} -- the class
107 < * name of a {@link ForkJoinWorkerThreadFactory}, and {@code
108 < * exceptionHandler} -- the class name of a {@link
109 < * java.lang.Thread.UncaughtExceptionHandler
110 < * Thread.UncaughtExceptionHandler}. Upon any error in establishing
111 < * these settings, default parameters are used.
103 > * parameters, but these may be controlled by setting three
104 > * {@linkplain System#getProperty system properties}:
105 > * <ul>
106 > * <li>{@code java.util.concurrent.ForkJoinPool.common.parallelism}
107 > * - the parallelism level, a non-negative integer
108 > * <li>{@code java.util.concurrent.ForkJoinPool.common.threadFactory}
109 > * - the class name of a {@link ForkJoinWorkerThreadFactory}
110 > * <li>{@code java.util.concurrent.ForkJoinPool.common.exceptionHandler}
111 > * - the class name of a {@link UncaughtExceptionHandler}
112 > * </ul>
113 > * The system class loader is used to load these classes.
114 > * Upon any error in establishing these settings, default parameters
115 > * are used. It is possible to disable or limit the use of threads in
116 > * the common pool by setting the parallelism property to zero, and/or
117 > * using a factory that may return {@code null}.
118   *
119   * <p><b>Implementation notes</b>: This implementation restricts the
120   * maximum number of running threads to 32767. Attempts to create
# Line 153 | Line 160 | public class ForkJoinPool extends Abstra
160       * (http://research.sun.com/scalable/pubs/index.html) and
161       * "Idempotent work stealing" by Michael, Saraswat, and Vechev,
162       * PPoPP 2009 (http://portal.acm.org/citation.cfm?id=1504186).
163 <     * The main differences ultimately stem from GC requirements that
164 <     * we null out taken slots as soon as we can, to maintain as small
165 <     * a footprint as possible even in programs generating huge
166 <     * numbers of tasks. To accomplish this, we shift the CAS
167 <     * arbitrating pop vs poll (steal) from being on the indices
168 <     * ("base" and "top") to the slots themselves.  So, both a
169 <     * successful pop and poll mainly entail a CAS of a slot from
170 <     * non-null to null.  Because we rely on CASes of references, we
171 <     * do not need tag bits on base or top.  They are simple ints as
172 <     * used in any circular array-based queue (see for example
173 <     * ArrayDeque).  Updates to the indices must still be ordered in a
174 <     * way that guarantees that top == base means the queue is empty,
175 <     * but otherwise may err on the side of possibly making the queue
176 <     * appear nonempty when a push, pop, or poll have not fully
177 <     * committed. Note that this means that the poll operation,
178 <     * considered individually, is not wait-free. One thief cannot
179 <     * successfully continue until another in-progress one (or, if
180 <     * previously empty, a push) completes.  However, in the
181 <     * aggregate, we ensure at least probabilistic non-blockingness.
182 <     * If an attempted steal fails, a thief always chooses a different
183 <     * random victim target to try next. So, in order for one thief to
184 <     * progress, it suffices for any in-progress poll or new push on
185 <     * any empty queue to complete. (This is why we normally use
186 <     * method pollAt and its variants that try once at the apparent
187 <     * base index, else consider alternative actions, rather than
188 <     * method poll.)
163 >     * See also "Correct and Efficient Work-Stealing for Weak Memory
164 >     * Models" by Le, Pop, Cohen, and Nardelli, PPoPP 2013
165 >     * (http://www.di.ens.fr/~zappa/readings/ppopp13.pdf) for an
166 >     * analysis of memory ordering (atomic, volatile etc) issues.  The
167 >     * main differences ultimately stem from GC requirements that we
168 >     * null out taken slots as soon as we can, to maintain as small a
169 >     * footprint as possible even in programs generating huge numbers
170 >     * of tasks. To accomplish this, we shift the CAS arbitrating pop
171 >     * vs poll (steal) from being on the indices ("base" and "top") to
172 >     * the slots themselves.  So, both a successful pop and poll
173 >     * mainly entail a CAS of a slot from non-null to null.  Because
174 >     * we rely on CASes of references, we do not need tag bits on base
175 >     * or top.  They are simple ints as used in any circular
176 >     * array-based queue (see for example ArrayDeque).  Updates to the
177 >     * indices must still be ordered in a way that guarantees that top
178 >     * == base means the queue is empty, but otherwise may err on the
179 >     * side of possibly making the queue appear nonempty when a push,
180 >     * pop, or poll have not fully committed. Note that this means
181 >     * that the poll operation, considered individually, is not
182 >     * wait-free. One thief cannot successfully continue until another
183 >     * in-progress one (or, if previously empty, a push) completes.
184 >     * However, in the aggregate, we ensure at least probabilistic
185 >     * non-blockingness.  If an attempted steal fails, a thief always
186 >     * chooses a different random victim target to try next. So, in
187 >     * order for one thief to progress, it suffices for any
188 >     * in-progress poll or new push on any empty queue to
189 >     * complete. (This is why we normally use method pollAt and its
190 >     * variants that try once at the apparent base index, else
191 >     * consider alternative actions, rather than method poll.)
192       *
193       * This approach also enables support of a user mode in which local
194       * task processing is in FIFO, not LIFO order, simply by using
# Line 197 | Line 207 | public class ForkJoinPool extends Abstra
207       * for work-stealing (this would contaminate lifo/fifo
208       * processing). Instead, we randomly associate submission queues
209       * with submitting threads, using a form of hashing.  The
210 <     * ThreadLocal Submitter class contains a value initially used as
211 <     * a hash code for choosing existing queues, but may be randomly
212 <     * repositioned upon contention with other submitters.  In
213 <     * essence, submitters act like workers except that they are
214 <     * restricted to executing local tasks that they submitted (or in
215 <     * the case of CountedCompleters, others with the same root task).
216 <     * However, because most shared/external queue operations are more
217 <     * expensive than internal, and because, at steady state, external
218 <     * submitters will compete for CPU with workers, ForkJoinTask.join
219 <     * and related methods disable them from repeatedly helping to
220 <     * process tasks if all workers are active.  Insertion of tasks in
221 <     * shared mode requires a lock (mainly to protect in the case of
210 >     * Submitter probe value serves as a hash code for
211 >     * choosing existing queues, and may be randomly repositioned upon
212 >     * contention with other submitters.  In essence, submitters act
213 >     * like workers except that they are restricted to executing local
214 >     * tasks that they submitted (or in the case of CountedCompleters,
215 >     * others with the same root task).  However, because most
216 >     * shared/external queue operations are more expensive than
217 >     * internal, and because, at steady state, external submitters
218 >     * will compete for CPU with workers, ForkJoinTask.join and
219 >     * related methods disable them from repeatedly helping to process
220 >     * tasks if all workers are active.  Insertion of tasks in shared
221 >     * mode requires a lock (mainly to protect in the case of
222       * resizing) but we use only a simple spinlock (using bits in
223       * field qlock), because submitters encountering a busy queue move
224       * on to try or create other queues -- they block only when
# Line 240 | Line 250 | public class ForkJoinPool extends Abstra
250       * enable shutdown.  When used as a lock, it is normally only very
251       * briefly held, so is nearly always available after at most a
252       * brief spin, but we use a monitor-based backup strategy to
253 <     * blocking when needed.
253 >     * block when needed.
254       *
255       * Recording WorkQueues.  WorkQueues are recorded in the
256       * "workQueues" array that is created upon first use and expanded
# Line 249 | Line 259 | public class ForkJoinPool extends Abstra
259       * by a lock but the array is otherwise concurrently readable, and
260       * accessed directly.  To simplify index-based operations, the
261       * array size is always a power of two, and all readers must
262 <     * tolerate null slots. Worker queues are at odd indices Shared
262 >     * tolerate null slots. Worker queues are at odd indices. Shared
263       * (submission) queues are at even indices, up to a maximum of 64
264       * slots, to limit growth even if array needs to expand to add
265       * more workers. Grouping them together in this way simplifies and
# Line 298 | Line 308 | public class ForkJoinPool extends Abstra
308       * has not yet entered the wait queue. We solve this by requiring
309       * a full sweep of all workers (via repeated calls to method
310       * scan()) both before and after a newly waiting worker is added
311 <     * to the wait queue. During a rescan, the worker might release
312 <     * some other queued worker rather than itself, which has the same
313 <     * net effect. Because enqueued workers may actually be rescanning
314 <     * rather than waiting, we set and clear the "parker" field of
315 <     * WorkQueues to reduce unnecessary calls to unpark.  (This
316 <     * requires a secondary recheck to avoid missed signals.)  Note
317 <     * the unusual conventions about Thread.interrupts surrounding
318 <     * parking and other blocking: Because interrupts are used solely
319 <     * to alert threads to check termination, which is checked anyway
320 <     * upon blocking, we clear status (using Thread.interrupted)
321 <     * before any call to park, so that park does not immediately
312 <     * return due to status being set via some other unrelated call to
313 <     * interrupt in user code.
311 >     * to the wait queue.  Because enqueued workers may actually be
312 >     * rescanning rather than waiting, we set and clear the "parker"
313 >     * field of WorkQueues to reduce unnecessary calls to unpark.
314 >     * (This requires a secondary recheck to avoid missed signals.)
315 >     * Note the unusual conventions about Thread.interrupts
316 >     * surrounding parking and other blocking: Because interrupts are
317 >     * used solely to alert threads to check termination, which is
318 >     * checked anyway upon blocking, we clear status (using
319 >     * Thread.interrupted) before any call to park, so that park does
320 >     * not immediately return due to status being set via some other
321 >     * unrelated call to interrupt in user code.
322       *
323       * Signalling.  We create or wake up workers only when there
324       * appears to be at least one task they might be able to find and
325 <     * execute. However, many other threads may notice the same task
326 <     * and each signal to wake up a thread that might take it. So in
327 <     * general, pools will be over-signalled.  When a submission is
328 <     * added or another worker adds a task to a queue that is
329 <     * apparently empty, they signal waiting workers (or trigger
330 <     * creation of new ones if fewer than the given parallelism level
331 <     * -- see signalWork).  These primary signals are buttressed by
332 <     * signals whenever other threads scan for work or do not have a
333 <     * task to process. On most platforms, signalling (unpark)
334 <     * overhead time is noticeably long, and the time between
335 <     * signalling a thread and it actually making progress can be very
336 <     * noticeably long, so it is worth offloading these delays from
337 <     * critical paths as much as possible.
325 >     * execute.  When a submission is added or another worker adds a
326 >     * task to a queue that has fewer than two tasks, they signal
327 >     * waiting workers (or trigger creation of new ones if fewer than
328 >     * the given parallelism level -- signalWork).  These primary
329 >     * signals are buttressed by others whenever other threads remove
330 >     * a task from a queue and notice that there are other tasks there
331 >     * as well.  So in general, pools will be over-signalled. On most
332 >     * platforms, signalling (unpark) overhead time is noticeably
333 >     * long, and the time between signalling a thread and it actually
334 >     * making progress can be very noticeably long, so it is worth
335 >     * offloading these delays from critical paths as much as
336 >     * possible. Additionally, workers spin-down gradually, by staying
337 >     * alive so long as they see the ctl state changing.  Similar
338 >     * stability-sensing techniques are also used before blocking in
339 >     * awaitJoin and helpComplete.
340       *
341       * Trimming workers. To release resources after periods of lack of
342       * use, a worker starting to wait when the pool is quiescent will
# Line 394 | Line 404 | public class ForkJoinPool extends Abstra
404       * steals, rather than use per-task bookkeeping.  This sometimes
405       * requires a linear scan of workQueues array to locate stealers,
406       * but often doesn't because stealers leave hints (that may become
407 <     * stale/wrong) of where to locate them.  A stealHint is only a
408 <     * hint because a worker might have had multiple steals and the
409 <     * hint records only one of them (usually the most current).
410 <     * Hinting isolates cost to when it is needed, rather than adding
411 <     * to per-task overhead.  (2) It is "shallow", ignoring nesting
412 <     * and potentially cyclic mutual steals.  (3) It is intentionally
407 >     * stale/wrong) of where to locate them.  It is only a hint
408 >     * because a worker might have had multiple steals and the hint
409 >     * records only one of them (usually the most current).  Hinting
410 >     * isolates cost to when it is needed, rather than adding to
411 >     * per-task overhead.  (2) It is "shallow", ignoring nesting and
412 >     * potentially cyclic mutual steals.  (3) It is intentionally
413       * racy: field currentJoin is updated only while actively joining,
414       * which means that we miss links in the chain during long-lived
415       * tasks, GC stalls etc (which is OK since blocking in such cases
# Line 439 | Line 449 | public class ForkJoinPool extends Abstra
449       * Common Pool
450       * ===========
451       *
452 <     * The static commonPool always exists after static
452 >     * The static common pool always exists after static
453       * initialization.  Since it (or any other created pool) need
454       * never be used, we minimize initial construction overhead and
455       * footprint to the setup of about a dozen fields, with no nested
# Line 447 | Line 457 | public class ForkJoinPool extends Abstra
457       * fullExternalPush during the first submission to the pool.
458       *
459       * When external threads submit to the common pool, they can
460 <     * perform some subtask processing (see externalHelpJoin and
461 <     * related methods).  We do not need to record whether these
460 >     * perform subtask processing (see externalHelpJoin and related
461 >     * methods).  This caller-helps policy makes it sensible to set
462 >     * common pool parallelism level to one (or more) less than the
463 >     * total number of available cores, or even zero for pure
464 >     * caller-runs.  We do not need to record whether external
465       * submissions are to the common pool -- if not, externalHelpJoin
466       * returns quickly (at the most helping to signal some common pool
467       * workers). These submitters would otherwise be blocked waiting
# Line 517 | Line 530 | public class ForkJoinPool extends Abstra
530           * Returns a new worker thread operating in the given pool.
531           *
532           * @param pool the pool this thread works in
533 +         * @return the new worker thread
534           * @throws NullPointerException if the pool is null
535           */
536          public ForkJoinWorkerThread newThread(ForkJoinPool pool);
# Line 526 | Line 540 | public class ForkJoinPool extends Abstra
540       * Default ForkJoinWorkerThreadFactory implementation; creates a
541       * new ForkJoinWorkerThread.
542       */
543 <    static class DefaultForkJoinWorkerThreadFactory
543 >    static final class DefaultForkJoinWorkerThreadFactory
544          implements ForkJoinWorkerThreadFactory {
545 <        public ForkJoinWorkerThread newThread(ForkJoinPool pool) {
545 >        public final ForkJoinWorkerThread newThread(ForkJoinPool pool) {
546              return new ForkJoinWorkerThread(pool);
547          }
548      }
# Line 592 | Line 606 | public class ForkJoinPool extends Abstra
606       * do not want multiple WorkQueue instances or multiple queue
607       * arrays sharing cache lines. (It would be best for queue objects
608       * and their arrays to share, but there is nothing available to
609 <     * help arrange that).  Unfortunately, because they are recorded
610 <     * in a common array, WorkQueue instances are often moved to be
597 <     * adjacent by garbage collectors. To reduce impact, we use field
598 <     * padding that works OK on common platforms; this effectively
599 <     * trades off slightly slower average field access for the sake of
600 <     * avoiding really bad worst-case access. (Until better JVM
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 by workers before use. Others are
605 <     * allocated on first use.
609 >     * help arrange that). The @Contended annotation alerts JVMs to
610 >     * try to keep instances apart.
611       */
612      static final class WorkQueue {
613          /**
# Line 625 | Line 630 | public class ForkJoinPool extends Abstra
630           */
631          static final int MAXIMUM_QUEUE_CAPACITY = 1 << 26; // 64M
632  
633 <        int seed;                  // for random scanning; initialize nonzero
633 >        // Heuristic padding to ameliorate unfortunate memory placements
634 >        volatile long pad00, pad01, pad02, pad03, pad04, pad05, pad06;
635 >
636          volatile int eventCount;   // encoded inactivation count; < 0 if inactive
637          int nextWait;              // encoded record of next event waiter
638 <        final int mode;            // lifo, fifo, or shared
639 <        int nsteals;               // cumulative number of steals
640 <        int poolIndex;             // index of this queue in pool (or 0)
641 <        int stealHint;             // index of most recent known stealer
638 >        int nsteals;               // number of steals
639 >        int hint;                  // steal index hint
640 >        short poolIndex;           // index of this queue in pool
641 >        final short mode;          // 0: lifo, > 0: fifo, < 0: shared
642          volatile int qlock;        // 1: locked, -1: terminate; else 0
643          volatile int base;         // index of next slot for poll
644          int top;                   // index of next slot for push
# Line 641 | Line 648 | public class ForkJoinPool extends Abstra
648          volatile Thread parker;    // == owner during call to park; else null
649          volatile ForkJoinTask<?> currentJoin;  // task being joined in awaitJoin
650          ForkJoinTask<?> currentSteal; // current non-local task being executed
644        // Heuristic padding to ameliorate unfortunate memory placements
645        Object p00, p01, p02, p03, p04, p05, p06, p07;
646        Object p08, p09, p0a, p0b, p0c, p0d, p0e;
651  
652 <        WorkQueue(ForkJoinPool pool, ForkJoinWorkerThread owner, int mode) {
653 <            this.mode = mode;
652 >        volatile Object pad10, pad11, pad12, pad13, pad14, pad15, pad16, pad17;
653 >        volatile Object pad18, pad19, pad1a, pad1b, pad1c, pad1d;
654 >
655 >        WorkQueue(ForkJoinPool pool, ForkJoinWorkerThread owner, int mode,
656 >                  int seed) {
657              this.pool = pool;
658              this.owner = owner;
659 +            this.mode = (short)mode;
660 +            this.hint = seed; // store initial seed for runWorker
661              // Place indices in the center of array (that is not yet allocated)
662              base = top = INITIAL_QUEUE_CAPACITY >>> 1;
663          }
664  
665          /**
666 <         * Pushes a task. Call only by owner in unshared queues.
667 <         * Cases needing resizing or rejection are relayed to fullPush
668 <         * (that also handles shared queues).
666 >         * Returns the approximate number of tasks in the queue.
667 >         */
668 >        final int queueSize() {
669 >            int n = base - top;       // non-owner callers must read base first
670 >            return (n >= 0) ? 0 : -n; // ignore transient negative
671 >        }
672 >
673 >        /**
674 >         * Provides a more accurate estimate of whether this queue has
675 >         * any tasks than does queueSize, by checking whether a
676 >         * near-empty queue has at least one unclaimed task.
677 >         */
678 >        final boolean isEmpty() {
679 >            ForkJoinTask<?>[] a; int m, s;
680 >            int n = base - (s = top);
681 >            return (n >= 0 ||
682 >                    (n == -1 &&
683 >                     ((a = array) == null ||
684 >                      (m = a.length - 1) < 0 ||
685 >                      U.getObject
686 >                      (a, (long)((m & (s - 1)) << ASHIFT) + ABASE) == null)));
687 >        }
688 >
689 >        /**
690 >         * Pushes a task. Call only by owner in unshared queues.  (The
691 >         * shared-queue version is embedded in method externalPush.)
692           *
693           * @param task the task. Caller must ensure non-null.
694 <         * @throw RejectedExecutionException if array cannot be resized
694 >         * @throws RejectedExecutionException if array cannot be resized
695           */
696          final void push(ForkJoinTask<?> task) {
697 <            ForkJoinPool p; ForkJoinTask<?>[] a;
697 >            ForkJoinTask<?>[] a; ForkJoinPool p;
698              int s = top, n;
699 <            if ((a = array) != null && a.length > (n = s + 1 - base)) {
700 <                U.putOrderedObject
701 <                    (a, (((a.length - 1) & s) << ASHIFT) + ABASE, task);
702 <                top = s + 1;
703 <                if (n <= 1 && (p = pool) != null)
704 <                    p.signalWork(this, 1);
699 >            if ((a = array) != null) {    // ignore if queue removed
700 >                int m = a.length - 1;
701 >                U.putOrderedObject(a, ((m & s) << ASHIFT) + ABASE, task);
702 >                if ((n = (top = s + 1) - base) <= 2)
703 >                    (p = pool).signalWork(p.workQueues, this);
704 >                else if (n >= m)
705 >                    growArray();
706              }
674            else
675                fullPush(task, true);
707          }
708  
709          /**
710 <         * Pushes a task if lock is free and array is either big
711 <         * enough or can be resized to be big enough. Note: a
712 <         * specialization of a common fast path of this method is in
713 <         * ForkJoinPool.externalPush. When called from a FJWT queue,
714 <         * this can fail only if the pool has been shut down or
715 <         * an out of memory error.
716 <         *
717 <         * @param task the task. Caller must ensure non-null.
718 <         * @param owned if true, throw RJE on failure
719 <         */
720 <        final boolean fullPush(ForkJoinTask<?> task, boolean owned) {
721 <            ForkJoinPool p; ForkJoinTask<?>[] a;
722 <            if (owned) {
723 <                if (qlock < 0) // must be shutting down
724 <                    throw new RejectedExecutionException();
710 >         * Initializes or doubles the capacity of array. Call either
711 >         * by owner or with lock held -- it is OK for base, but not
712 >         * top, to move while resizings are in progress.
713 >         */
714 >        final ForkJoinTask<?>[] growArray() {
715 >            ForkJoinTask<?>[] oldA = array;
716 >            int size = oldA != null ? oldA.length << 1 : INITIAL_QUEUE_CAPACITY;
717 >            if (size > MAXIMUM_QUEUE_CAPACITY)
718 >                throw new RejectedExecutionException("Queue capacity exceeded");
719 >            int oldMask, t, b;
720 >            ForkJoinTask<?>[] a = array = new ForkJoinTask<?>[size];
721 >            if (oldA != null && (oldMask = oldA.length - 1) >= 0 &&
722 >                (t = top) - (b = base) > 0) {
723 >                int mask = size - 1;
724 >                do {
725 >                    ForkJoinTask<?> x;
726 >                    int oldj = ((b & oldMask) << ASHIFT) + ABASE;
727 >                    int j    = ((b &    mask) << ASHIFT) + ABASE;
728 >                    x = (ForkJoinTask<?>)U.getObjectVolatile(oldA, oldj);
729 >                    if (x != null &&
730 >                        U.compareAndSwapObject(oldA, oldj, x, null))
731 >                        U.putObjectVolatile(a, j, x);
732 >                } while (++b != t);
733              }
734 <            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 <                    }
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 <            if ((p = pool) != null)
731 <                p.signalWork(this, 1);
732 <            return true;
734 >            return a;
735          }
736  
737          /**
# Line 762 | Line 764 | public class ForkJoinPool extends Abstra
764              if ((a = array) != null) {
765                  int j = (((a.length - 1) & b) << ASHIFT) + ABASE;
766                  if ((t = (ForkJoinTask<?>)U.getObjectVolatile(a, j)) != null &&
767 <                    base == b &&
768 <                    U.compareAndSwapObject(a, j, t, null)) {
767 <                    base = b + 1;
767 >                    base == b && U.compareAndSwapObject(a, j, t, null)) {
768 >                    U.putOrderedInt(this, QBASE, b + 1);
769                      return t;
770                  }
771              }
# Line 780 | Line 781 | public class ForkJoinPool extends Abstra
781                  int j = (((a.length - 1) & b) << ASHIFT) + ABASE;
782                  t = (ForkJoinTask<?>)U.getObjectVolatile(a, j);
783                  if (t != null) {
784 <                    if (base == b &&
785 <                        U.compareAndSwapObject(a, j, t, null)) {
785 <                        base = b + 1;
784 >                    if (U.compareAndSwapObject(a, j, t, null)) {
785 >                        U.putOrderedInt(this, QBASE, b + 1);
786                          return t;
787                      }
788                  }
# Line 839 | Line 839 | public class ForkJoinPool extends Abstra
839                  ForkJoinTask.cancelIgnoringExceptions(t);
840          }
841  
842 <        /**
843 <         * Computes next value for random probes.  Scans don't require
844 <         * a very high quality generator, but also not a crummy one.
845 <         * Marsaglia xor-shift is cheap and works well enough.  Note:
846 <         * This is manually inlined in its usages in ForkJoinPool to
847 <         * avoid writes inside busy scan loops.
848 <         */
849 <        final int nextSeed() {
850 <            int r = seed;
851 <            r ^= r << 13;
852 <            r ^= r >>> 17;
853 <            return seed = r ^= r << 5;
854 <        }
842 >        // Specialized execution methods
843  
844          /**
845 <         * 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.
845 >         * Polls and runs tasks until empty.
846           */
847 <        final int queueSize() {
848 <            ForkJoinTask<?>[] a; int k, s, n;
849 <            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;
847 >        final void pollAndExecAll() {
848 >            for (ForkJoinTask<?> t; (t = poll()) != null;)
849 >                t.doExec();
850          }
851  
871        // Specialized execution methods
872
852          /**
853 <         * Pops and runs tasks until empty.
853 >         * Executes a top-level task and any local tasks remaining
854 >         * after execution.
855           */
856 <        private void popAndExecAll() {
857 <            // A bit faster than repeated pop calls
858 <            ForkJoinTask<?>[] a; int m, s; long j; ForkJoinTask<?> t;
859 <            while ((a = array) != null && (m = a.length - 1) >= 0 &&
860 <                   (s = top - 1) - base >= 0 &&
861 <                   (t = ((ForkJoinTask<?>)
862 <                         U.getObject(a, j = ((m & s) << ASHIFT) + ABASE)))
863 <                   != null) {
864 <                if (U.compareAndSwapObject(a, j, t, null)) {
865 <                    top = s;
866 <                    t.doExec();
856 >        final void runTask(ForkJoinTask<?> task) {
857 >            if ((currentSteal = task) != null) {
858 >                task.doExec();
859 >                ForkJoinTask<?>[] a = array;
860 >                int md = mode;
861 >                ++nsteals;
862 >                currentSteal = null;
863 >                if (md != 0)
864 >                    pollAndExecAll();
865 >                else if (a != null) {
866 >                    int s, m = a.length - 1;
867 >                    while ((s = top - 1) - base >= 0) {
868 >                        long i = ((m & s) << ASHIFT) + ABASE;
869 >                        ForkJoinTask<?> t = (ForkJoinTask<?>)U.getObject(a, i);
870 >                        if (t == null)
871 >                            break;
872 >                        if (U.compareAndSwapObject(a, i, t, null)) {
873 >                            top = s;
874 >                            t.doExec();
875 >                        }
876 >                    }
877                  }
878              }
879          }
880  
881          /**
892         * Polls and runs tasks until empty.
893         */
894        private void pollAndExecAll() {
895            for (ForkJoinTask<?> t; (t = poll()) != null;)
896                t.doExec();
897        }
898
899        /**
882           * If present, removes from queue and executes the given task,
883           * or any other cancelled task. Returns (true) on any CAS
884           * or consistency check failure so caller can retry.
885           *
886 <         * @return false if no progress can be made, else true;
886 >         * @return false if no progress can be made, else true
887           */
888          final boolean tryRemoveAndExec(ForkJoinTask<?> task) {
889 <            boolean stat = true, removed = false, empty = true;
889 >            boolean stat;
890              ForkJoinTask<?>[] a; int m, s, b, n;
891 <            if ((a = array) != null && (m = a.length - 1) >= 0 &&
891 >            if (task != null && (a = array) != null && (m = a.length - 1) >= 0 &&
892                  (n = (s = top) - (b = base)) > 0) {
893 +                boolean removed = false, empty = true;
894 +                stat = true;
895                  for (ForkJoinTask<?> t;;) {           // traverse from s to b
896 <                    int j = ((--s & m) << ASHIFT) + ABASE;
897 <                    t = (ForkJoinTask<?>)U.getObjectVolatile(a, j);
896 >                    long j = ((--s & m) << ASHIFT) + ABASE;
897 >                    t = (ForkJoinTask<?>)U.getObject(a, j);
898                      if (t == null)                    // inconsistent length
899                          break;
900                      else if (t == task) {
# Line 938 | Line 922 | public class ForkJoinPool extends Abstra
922                          break;
923                      }
924                  }
925 +                if (removed)
926 +                    task.doExec();
927              }
928 <            if (removed)
929 <                task.doExec();
928 >            else
929 >                stat = false;
930              return stat;
931          }
932  
933          /**
934 <         * Polls for and executes the given task or any other task in
935 <         * its CountedCompleter computation
934 >         * Tries to poll for and execute the given task or any other
935 >         * task in its CountedCompleter computation.
936           */
937 <        final boolean pollAndExecCC(ForkJoinTask<?> root) {
938 <            ForkJoinTask<?>[] a; int b; Object o;
939 <            outer: while ((b = base) - top < 0 && (a = array) != null) {
937 >        final boolean pollAndExecCC(CountedCompleter<?> root) {
938 >            ForkJoinTask<?>[] a; int b; Object o; CountedCompleter<?> t, r;
939 >            if ((b = base) - top < 0 && (a = array) != null) {
940                  long j = (((a.length - 1) & b) << ASHIFT) + ABASE;
941 <                if ((o = U.getObject(a, j)) == null ||
942 <                    !(o instanceof CountedCompleter))
943 <                    break;
944 <                for (CountedCompleter<?> t = (CountedCompleter<?>)o, r = t;;) {
945 <                    if (r == root) {
946 <                        if (base == b &&
947 <                            U.compareAndSwapObject(a, j, t, null)) {
948 <                            base = b + 1;
949 <                            t.doExec();
941 >                if ((o = U.getObjectVolatile(a, j)) == null)
942 >                    return true; // retry
943 >                if (o instanceof CountedCompleter) {
944 >                    for (t = (CountedCompleter<?>)o, r = t;;) {
945 >                        if (r == root) {
946 >                            if (base == b &&
947 >                                U.compareAndSwapObject(a, j, t, null)) {
948 >                                U.putOrderedInt(this, QBASE, b + 1);
949 >                                t.doExec();
950 >                            }
951                              return true;
952                          }
953 <                        else
954 <                            break; // restart
953 >                        else if ((r = r.completer) == null)
954 >                            break; // not part of root computation
955                      }
969                    if ((r = r.completer) == null)
970                        break outer; // not part of root computation
956                  }
957              }
958              return false;
959          }
960  
961          /**
962 <         * Executes a top-level task and any local tasks remaining
963 <         * after execution.
962 >         * Tries to pop and execute the given task or any other task
963 >         * in its CountedCompleter computation.
964           */
965 <        final void runTask(ForkJoinTask<?> t) {
966 <            if (t != null) {
967 <                (currentSteal = t).doExec();
968 <                currentSteal = null;
969 <                if (++nsteals < 0) {     // spill on overflow
970 <                    ForkJoinPool p;
971 <                    if ((p = pool) != null)
972 <                        p.collectStealCount(this);
973 <                }
974 <                if (top != base) {       // process remaining local tasks
975 <                    if (mode == 0)
976 <                        popAndExecAll();
977 <                    else
978 <                        pollAndExecAll();
965 >        final boolean externalPopAndExecCC(CountedCompleter<?> root) {
966 >            ForkJoinTask<?>[] a; int s; Object o; CountedCompleter<?> t, r;
967 >            if (base - (s = top) < 0 && (a = array) != null) {
968 >                long j = (((a.length - 1) & (s - 1)) << ASHIFT) + ABASE;
969 >                if ((o = U.getObject(a, j)) instanceof CountedCompleter) {
970 >                    for (t = (CountedCompleter<?>)o, r = t;;) {
971 >                        if (r == root) {
972 >                            if (U.compareAndSwapInt(this, QLOCK, 0, 1)) {
973 >                                if (top == s && array == a &&
974 >                                    U.compareAndSwapObject(a, j, t, null)) {
975 >                                    top = s - 1;
976 >                                    qlock = 0;
977 >                                    t.doExec();
978 >                                }
979 >                                else
980 >                                    qlock = 0;
981 >                            }
982 >                            return true;
983 >                        }
984 >                        else if ((r = r.completer) == null)
985 >                            break;
986 >                    }
987                  }
988              }
989 +            return false;
990          }
991  
992          /**
993 <         * Executes a non-top-level (stolen) task.
993 >         * Internal version
994           */
995 <        final void runSubtask(ForkJoinTask<?> t) {
996 <            if (t != null) {
997 <                ForkJoinTask<?> ps = currentSteal;
998 <                (currentSteal = t).doExec();
999 <                currentSteal = ps;
995 >        final boolean internalPopAndExecCC(CountedCompleter<?> root) {
996 >            ForkJoinTask<?>[] a; int s; Object o; CountedCompleter<?> t, r;
997 >            if (base - (s = top) < 0 && (a = array) != null) {
998 >                long j = (((a.length - 1) & (s - 1)) << ASHIFT) + ABASE;
999 >                if ((o = U.getObject(a, j)) instanceof CountedCompleter) {
1000 >                    for (t = (CountedCompleter<?>)o, r = t;;) {
1001 >                        if (r == root) {
1002 >                            if (U.compareAndSwapObject(a, j, t, null)) {
1003 >                                top = s - 1;
1004 >                                t.doExec();
1005 >                            }
1006 >                            return true;
1007 >                        }
1008 >                        else if ((r = r.completer) == null)
1009 >                            break;
1010 >                    }
1011 >                }
1012              }
1013 +            return false;
1014          }
1015  
1016          /**
# Line 1018 | Line 1025 | public class ForkJoinPool extends Abstra
1025                      s != Thread.State.TIMED_WAITING);
1026          }
1027  
1021        /**
1022         * If this owned and is not already interrupted, try to
1023         * interrupt and/or unpark, ignoring exceptions.
1024         */
1025        final void interruptOwner() {
1026            Thread wt, p;
1027            if ((wt = owner) != null && !wt.isInterrupted()) {
1028                try {
1029                    wt.interrupt();
1030                } catch (SecurityException ignore) {
1031                }
1032            }
1033            if ((p = parker) != null)
1034                U.unpark(p);
1035        }
1036
1028          // Unsafe mechanics
1029          private static final sun.misc.Unsafe U;
1030 +        private static final long QBASE;
1031          private static final long QLOCK;
1032          private static final int ABASE;
1033          private static final int ASHIFT;
1034          static {
1043            int s;
1035              try {
1036                  U = getUnsafe();
1037                  Class<?> k = WorkQueue.class;
1038                  Class<?> ak = ForkJoinTask[].class;
1039 +                QBASE = U.objectFieldOffset
1040 +                    (k.getDeclaredField("base"));
1041                  QLOCK = U.objectFieldOffset
1042                      (k.getDeclaredField("qlock"));
1043                  ABASE = U.arrayBaseOffset(ak);
1044 <                s = U.arrayIndexScale(ak);
1044 >                int scale = U.arrayIndexScale(ak);
1045 >                if ((scale & (scale - 1)) != 0)
1046 >                    throw new Error("data type scale not a power of two");
1047 >                ASHIFT = 31 - Integer.numberOfLeadingZeros(scale);
1048              } catch (Exception e) {
1049                  throw new Error(e);
1050              }
1055            if ((s & (s-1)) != 0)
1056                throw new Error("data type scale not a power of two");
1057            ASHIFT = 31 - Integer.numberOfLeadingZeros(s);
1051          }
1052      }
1053  
1054 +    // static fields (initialized in static initializer below)
1055 +
1056      /**
1057 <     * Per-thread records for threads that submit to pools. Currently
1058 <     * holds only pseudo-random seed / index that is used to choose
1059 <     * submission queues in method externalPush. In the future, this may
1060 <     * also incorporate a means to implement different task rejection
1061 <     * and resubmission policies.
1067 <     *
1068 <     * Seeds for submitters and workers/workQueues work in basically
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. Seeds are then
1073 <     * randomly modified upon collisions using xorshifts, which
1074 <     * requires a non-zero seed.
1057 >     * Per-thread submission bookkeeping. Shared across all pools
1058 >     * to reduce ThreadLocal pollution and because random motion
1059 >     * to avoid contention in one pool is likely to hold for others.
1060 >     * Lazily initialized on first submission (but null-checked
1061 >     * in other contexts to avoid unnecessary initialization).
1062       */
1063 <    static final class Submitter {
1077 <        int seed;
1078 <        Submitter(int s) { seed = s; }
1079 <    }
1080 <
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)
1063 >    static final ThreadLocal<Submitter> submitters;
1064  
1065      /**
1066       * Creates a new ForkJoinWorkerThread. This factory is used unless
# Line 1092 | Line 1070 | public class ForkJoinPool extends Abstra
1070          defaultForkJoinWorkerThreadFactory;
1071  
1072      /**
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    static final ForkJoinPool commonPool;
1101
1102    /**
1073       * Permission required for callers of methods that may start or
1074       * kill threads.
1075       */
1076      private static final RuntimePermission modifyThreadPermission;
1077  
1078      /**
1079 <     * Per-thread submission bookkeeping. Shared across all pools
1080 <     * to reduce ThreadLocal pollution and because random motion
1081 <     * to avoid contention in one pool is likely to hold for others.
1082 <     * Lazily initialized on first submission (but null-checked
1113 <     * in other contexts to avoid unnecessary initialization).
1079 >     * Common (static) pool. Non-null for public use unless a static
1080 >     * construction exception, but internal usages null-check on use
1081 >     * to paranoically avoid potential initialization circularities
1082 >     * as well as to simplify generated code.
1083       */
1084 <    static final ThreadLocal<Submitter> submitters;
1084 >    static final ForkJoinPool common;
1085  
1086      /**
1087 <     * Common pool parallelism. Must equal commonPool.parallelism.
1087 >     * Common pool parallelism. To allow simpler use and management
1088 >     * when common pool threads are disabled, we allow the underlying
1089 >     * common.parallelism field to be zero, but in that case still report
1090 >     * parallelism as 1 to reflect resulting caller-runs mechanics.
1091       */
1092 <    static final int commonPoolParallelism;
1092 >    static final int commonParallelism;
1093  
1094      /**
1095       * Sequence number for creating workerNamePrefix.
# Line 1125 | Line 1097 | public class ForkJoinPool extends Abstra
1097      private static int poolNumberSequence;
1098  
1099      /**
1100 <     * Return the next sequence number. We don't expect this to
1101 <     * ever contend so use simple builtin sync.
1100 >     * Returns the next sequence number. We don't expect this to
1101 >     * ever contend, so use simple builtin sync.
1102       */
1103      private static final synchronized int nextPoolId() {
1104          return ++poolNumberSequence;
# Line 1150 | Line 1122 | public class ForkJoinPool extends Abstra
1122      private static final long FAST_IDLE_TIMEOUT =  200L * 1000L * 1000L;
1123  
1124      /**
1125 +     * Tolerance for idle timeouts, to cope with timer undershoots
1126 +     */
1127 +    private static final long TIMEOUT_SLOP = 2000000L;
1128 +
1129 +    /**
1130       * The maximum stolen->joining link depth allowed in method
1131       * tryHelpStealer.  Must be a power of two.  Depths for legitimate
1132       * chains are unbounded, but we use a fixed constant to avoid
# Line 1165 | Line 1142 | public class ForkJoinPool extends Abstra
1142       */
1143      private static final int SEED_INCREMENT = 0x61c88647;
1144  
1145 <    /**
1145 >    /*
1146       * Bits and masks for control variables
1147       *
1148       * Field ctl is a long packed with:
# Line 1249 | Line 1226 | public class ForkJoinPool extends Abstra
1226      static final int FIFO_QUEUE          =  1;
1227      static final int SHARED_QUEUE        = -1;
1228  
1229 <    // Instance fields
1229 >    // Heuristic padding to ameliorate unfortunate memory placements
1230 >    volatile long pad00, pad01, pad02, pad03, pad04, pad05, pad06;
1231  
1232 <    /*
1255 <     * Field layout order in this class tends to matter more than one
1256 <     * would like. Runtime layout order is only loosely related to
1257 <     * declaration order and may differ across JVMs, but the following
1258 <     * empirically works OK on current JVMs.
1259 <     */
1232 >    // Instance fields
1233      volatile long stealCount;                  // collects worker counts
1234      volatile long ctl;                         // main pool control
1262    final int parallelism;                     // parallelism level
1263    final int localMode;                       // per-worker scheduling mode
1264    volatile int indexSeed;                    // worker/submitter index seed
1235      volatile int plock;                        // shutdown status and seqLock
1236 +    volatile int indexSeed;                    // worker/submitter index seed
1237 +    final short parallelism;                   // parallelism level
1238 +    final short mode;                          // LIFO/FIFO
1239      WorkQueue[] workQueues;                    // main registry
1240 <    final ForkJoinWorkerThreadFactory factory; // factory for new workers
1241 <    final Thread.UncaughtExceptionHandler ueh; // per-worker UEH
1240 >    final ForkJoinWorkerThreadFactory factory;
1241 >    final UncaughtExceptionHandler ueh;        // per-worker UEH
1242      final String workerNamePrefix;             // to create worker name string
1243  
1244 <    /*
1244 >    volatile Object pad10, pad11, pad12, pad13, pad14, pad15, pad16, pad17;
1245 >    volatile Object pad18, pad19, pad1a, pad1b;
1246 >
1247 >    /**
1248       * Acquires the plock lock to protect worker array and related
1249       * updates. This method is called only if an initial CAS on plock
1250 <     * fails. This acts as a spinLock for normal cases, but falls back
1250 >     * fails. This acts as a spinlock for normal cases, but falls back
1251       * to builtin monitor to block when (rarely) needed. This would be
1252       * a terrible idea for a highly contended lock, but works fine as
1253 <     * a more conservative alternative to a pure spinlock.  See
1278 <     * internal ConcurrentHashMap documentation for further
1279 <     * explanation of nearly the same construction.
1253 >     * a more conservative alternative to a pure spinlock.
1254       */
1255      private int acquirePlock() {
1256 <        int spins = PL_SPINS, r = 0, ps, nps;
1256 >        int spins = PL_SPINS, ps, nps;
1257          for (;;) {
1258              if (((ps = plock) & PL_LOCK) == 0 &&
1259                  U.compareAndSwapInt(this, PLOCK, ps, nps = ps + PL_LOCK))
1260                  return nps;
1287            else if (r == 0)
1288                r = ThreadLocalRandom.current().nextInt(); // randomize spins
1261              else if (spins >= 0) {
1262 <                r ^= r << 1; r ^= r >>> 3; r ^= r << 10; // xorshift
1291 <                if (r >= 0)
1262 >                if (ThreadLocalRandom.current().nextInt() >= 0)
1263                      --spins;
1264              }
1265              else if (U.compareAndSwapInt(this, PLOCK, ps, ps | PL_SIGNAL)) {
# Line 1319 | Line 1290 | public class ForkJoinPool extends Abstra
1290          synchronized (this) { notifyAll(); }
1291      }
1292  
1293 +    /**
1294 +     * Tries to create and start one worker if fewer than target
1295 +     * parallelism level exist. Adjusts counts etc on failure.
1296 +     */
1297 +    private void tryAddWorker() {
1298 +        long c; int u, e;
1299 +        while ((u = (int)((c = ctl) >>> 32)) < 0 &&
1300 +               (u & SHORT_SIGN) != 0 && (e = (int)c) >= 0) {
1301 +            long nc = ((long)(((u + UTC_UNIT) & UTC_MASK) |
1302 +                              ((u + UAC_UNIT) & UAC_MASK)) << 32) | (long)e;
1303 +            if (U.compareAndSwapLong(this, CTL, c, nc)) {
1304 +                ForkJoinWorkerThreadFactory fac;
1305 +                Throwable ex = null;
1306 +                ForkJoinWorkerThread wt = null;
1307 +                try {
1308 +                    if ((fac = factory) != null &&
1309 +                        (wt = fac.newThread(this)) != null) {
1310 +                        wt.start();
1311 +                        break;
1312 +                    }
1313 +                } catch (Throwable rex) {
1314 +                    ex = rex;
1315 +                }
1316 +                deregisterWorker(wt, ex);
1317 +                break;
1318 +            }
1319 +        }
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
1327 <     * to packing entries in front of the workQueues array, we treat
1328 <     * the array as a simple power-of-two hash table using per-thread
1329 <     * seed as hash, expanding as needed.
1330 <     *
1331 <     * @param w the worker's queue
1332 <     */
1333 <    final void registerWorker(WorkQueue w) {
1334 <        int s, ps; // generate a rarely colliding candidate index seed
1335 <        do {} while (!U.compareAndSwapInt(this, INDEXSEED,
1336 <                                          s = indexSeed, s += SEED_INCREMENT) ||
1325 >     * Callback from ForkJoinWorkerThread to establish and record its
1326 >     * WorkQueue. To avoid scanning bias due to packing entries in
1327 >     * front of the workQueues array, we treat the array as a simple
1328 >     * power-of-two hash table using per-thread seed as hash,
1329 >     * expanding as needed.
1330 >     *
1331 >     * @param wt the worker thread
1332 >     * @return the worker's queue
1333 >     */
1334 >    final WorkQueue registerWorker(ForkJoinWorkerThread wt) {
1335 >        UncaughtExceptionHandler handler; WorkQueue[] ws; int s, ps;
1336 >        wt.setDaemon(true);
1337 >        if ((handler = ueh) != null)
1338 >            wt.setUncaughtExceptionHandler(handler);
1339 >        do {} while (!U.compareAndSwapInt(this, INDEXSEED, s = indexSeed,
1340 >                                          s += SEED_INCREMENT) ||
1341                       s == 0); // skip 0
1342 +        WorkQueue w = new WorkQueue(this, wt, mode, s);
1343          if (((ps = plock) & PL_LOCK) != 0 ||
1344              !U.compareAndSwapInt(this, PLOCK, ps, ps += PL_LOCK))
1345              ps = acquirePlock();
1346          int nps = (ps & SHUTDOWN) | ((ps + PL_LOCK) & ~SHUTDOWN);
1347          try {
1348 <            WorkQueue[] ws;
1344 <            if (w != null && (ws = workQueues) != null) {
1345 <                w.seed = s;
1348 >            if ((ws = workQueues) != null) {    // skip if shutting down
1349                  int n = ws.length, m = n - 1;
1350 <                int r = (s << 1) | 1;               // use odd-numbered indices
1351 <                if (ws[r &= m] != null) {           // collision
1352 <                    int probes = 0;                 // step by approx half size
1350 >                int r = (s << 1) | 1;           // use odd-numbered indices
1351 >                if (ws[r &= m] != null) {       // collision
1352 >                    int probes = 0;             // step by approx half size
1353                      int step = (n <= 4) ? 2 : ((n >>> 1) & EVENMASK) + 2;
1354                      while (ws[r = (r + step) & m] != null) {
1355                          if (++probes >= n) {
# Line 1356 | Line 1359 | public class ForkJoinPool extends Abstra
1359                          }
1360                      }
1361                  }
1362 <                w.eventCount = w.poolIndex = r;     // establish before recording
1362 >                w.poolIndex = (short)r;
1363 >                w.eventCount = r; // volatile write orders
1364                  ws[r] = w;
1365              }
1366          } finally {
1367              if (!U.compareAndSwapInt(this, PLOCK, ps, nps))
1368                  releasePlock(nps);
1369          }
1370 +        wt.setName(workerNamePrefix.concat(Integer.toString(w.poolIndex >>> 1)));
1371 +        return w;
1372      }
1373  
1374      /**
# Line 1371 | Line 1377 | public class ForkJoinPool extends Abstra
1377       * array, and adjusts counts. If pool is shutting down, tries to
1378       * complete termination.
1379       *
1380 <     * @param wt the worker thread or null if construction failed
1380 >     * @param wt the worker thread, or null if construction failed
1381       * @param ex the exception causing failure, or null if none
1382       */
1383      final void deregisterWorker(ForkJoinWorkerThread wt, Throwable ex) {
1384          WorkQueue w = null;
1385          if (wt != null && (w = wt.workQueue) != null) {
1386 <            int ps;
1381 <            collectStealCount(w);
1386 >            int ps; long sc;
1387              w.qlock = -1;                // ensure set
1388 +            do {} while (!U.compareAndSwapLong(this, STEALCOUNT,
1389 +                                               sc = stealCount,
1390 +                                               sc + w.nsteals));
1391              if (((ps = plock) & PL_LOCK) != 0 ||
1392                  !U.compareAndSwapInt(this, PLOCK, ps, ps += PL_LOCK))
1393                  ps = acquirePlock();
# Line 1395 | Line 1403 | public class ForkJoinPool extends Abstra
1403              }
1404          }
1405  
1406 <        long c;                             // adjust ctl counts
1406 >        long c;                          // adjust ctl counts
1407          do {} while (!U.compareAndSwapLong
1408                       (this, CTL, c = ctl, (((c - AC_UNIT) & AC_MASK) |
1409                                             ((c - TC_UNIT) & TC_MASK) |
1410                                             (c & ~(AC_MASK|TC_MASK)))));
1411  
1412 <        if (!tryTerminate(false, false) && w != null) {
1413 <            w.cancelAll();                  // cancel remaining tasks
1414 <            if (w.array != null)            // suppress signal if never ran
1415 <                signalWork(null, 1);        // wake up or create replacement
1416 <            if (ex == null)                 // help clean refs on way out
1417 <                ForkJoinTask.helpExpungeStaleExceptions();
1412 >        if (!tryTerminate(false, false) && w != null && w.array != null) {
1413 >            w.cancelAll();               // cancel remaining tasks
1414 >            WorkQueue[] ws; WorkQueue v; Thread p; int u, i, e;
1415 >            while ((u = (int)((c = ctl) >>> 32)) < 0 && (e = (int)c) >= 0) {
1416 >                if (e > 0) {             // activate or create replacement
1417 >                    if ((ws = workQueues) == null ||
1418 >                        (i = e & SMASK) >= ws.length ||
1419 >                        (v = ws[i]) == null)
1420 >                        break;
1421 >                    long nc = (((long)(v.nextWait & E_MASK)) |
1422 >                               ((long)(u + UAC_UNIT) << 32));
1423 >                    if (v.eventCount != (e | INT_SIGN))
1424 >                        break;
1425 >                    if (U.compareAndSwapLong(this, CTL, c, nc)) {
1426 >                        v.eventCount = (e + E_SEQ) & E_MASK;
1427 >                        if ((p = v.parker) != null)
1428 >                            U.unpark(p);
1429 >                        break;
1430 >                    }
1431 >                }
1432 >                else {
1433 >                    if ((short)u < 0)
1434 >                        tryAddWorker();
1435 >                    break;
1436 >                }
1437 >            }
1438          }
1439 <
1440 <        if (ex != null)                     // rethrow
1439 >        if (ex == null)                     // help clean refs on way out
1440 >            ForkJoinTask.helpExpungeStaleExceptions();
1441 >        else                                // rethrow
1442              ForkJoinTask.rethrow(ex);
1443      }
1444  
1445 +    // Submissions
1446 +
1447      /**
1448 <     * Collect worker steal count into total. Called on termination
1449 <     * and upon int overflow of local count. (There is a possible race
1450 <     * in the latter case vs any caller of getStealCount, which can
1451 <     * make its results less accurate than usual.)
1452 <     */
1453 <    final void collectStealCount(WorkQueue w) {
1454 <        if (w != null) {
1455 <            long sc;
1456 <            int ns = w.nsteals;
1457 <            w.nsteals = 0; // handle overflow
1458 <            long steals = (ns >= 0) ? ns : 1L + (long)(Integer.MAX_VALUE);
1459 <            do {} while (!U.compareAndSwapLong(this, STEALCOUNT,
1460 <                                               sc = stealCount, sc + steals));
1461 <        }
1448 >     * Per-thread records for threads that submit to pools. Currently
1449 >     * holds only pseudo-random seed / index that is used to choose
1450 >     * submission queues in method externalPush. In the future, this may
1451 >     * also incorporate a means to implement different task rejection
1452 >     * and resubmission policies.
1453 >     *
1454 >     * Seeds for submitters and workers/workQueues work in basically
1455 >     * the same way but are initialized and updated using slightly
1456 >     * different mechanics. Both are initialized using the same
1457 >     * approach as in class ThreadLocal, where successive values are
1458 >     * unlikely to collide with previous values. Seeds are then
1459 >     * randomly modified upon collisions using xorshifts, which
1460 >     * requires a non-zero seed.
1461 >     */
1462 >    static final class Submitter {
1463 >        int seed;
1464 >        Submitter(int s) { seed = s; }
1465      }
1466  
1433    // Submissions
1434
1467      /**
1468       * Unless shutting down, adds the given task to a submission queue
1469       * at submitter's current queue index (modulo submission
# Line 1441 | Line 1473 | public class ForkJoinPool extends Abstra
1473       * @param task the task. Caller must ensure non-null.
1474       */
1475      final void externalPush(ForkJoinTask<?> task) {
1476 <        WorkQueue[] ws; WorkQueue q; Submitter z; int m; ForkJoinTask<?>[] a;
1477 <        if ((z = submitters.get()) != null && plock > 0 &&
1478 <            (ws = workQueues) != null && (m = (ws.length - 1)) >= 0 &&
1479 <            (q = ws[m & z.seed & SQMASK]) != null &&
1476 >        Submitter z = submitters.get();
1477 >        WorkQueue q; int r, m, s, n, am; ForkJoinTask<?>[] a;
1478 >        int ps = plock;
1479 >        WorkQueue[] ws = workQueues;
1480 >        if (z != null && ps > 0 && ws != null && (m = (ws.length - 1)) >= 0 &&
1481 >            (q = ws[m & (r = z.seed) & SQMASK]) != null && r != 0 &&
1482              U.compareAndSwapInt(q, QLOCK, 0, 1)) { // lock
1483 <            int s = q.top, n;
1484 <            if ((a = q.array) != null && a.length > (n = s + 1 - q.base)) {
1485 <                U.putObject(a, (long)(((a.length - 1) & s) << ASHIFT) + ABASE,
1486 <                            task);
1483 >            if ((a = q.array) != null &&
1484 >                (am = a.length - 1) > (n = (s = q.top) - q.base)) {
1485 >                int j = ((am & s) << ASHIFT) + ABASE;
1486 >                U.putOrderedObject(a, j, task);
1487                  q.top = s + 1;                     // push on to deque
1488                  q.qlock = 0;
1489                  if (n <= 1)
1490 <                    signalWork(q, 1);
1490 >                    signalWork(ws, q);
1491                  return;
1492              }
1493              q.qlock = 0;
# Line 1464 | Line 1498 | public class ForkJoinPool extends Abstra
1498      /**
1499       * Full version of externalPush. This method is called, among
1500       * other times, upon the first submission of the first task to the
1501 <     * pool, so must perform secondary initialization: creating
1468 <     * workQueue array and setting plock to a valid value. It also
1501 >     * pool, so must perform secondary initialization.  It also
1502       * detects first submission by an external thread by looking up
1503       * its ThreadLocal, and creates a new shared queue if the one at
1504 <     * index if empty or contended. The lock bodies must be
1504 >     * index if empty or contended. The plock lock body must be
1505       * exception-free (so no try/finally) so we optimistically
1506 <     * allocate new queues/arrays outside the locks and throw them
1507 <     * away if (very rarely) not needed. Note that the plock seq value
1508 <     * can eventually wrap around zero, but if so harmlessly fails to
1509 <     * reinitialize.
1506 >     * allocate new queues outside the lock and throw them away if
1507 >     * (very rarely) not needed.
1508 >     *
1509 >     * Secondary initialization occurs when plock is zero, to create
1510 >     * workQueue array and set plock to a valid value.  This lock body
1511 >     * must also be exception-free. Because the plock seq value can
1512 >     * eventually wrap around zero, this method harmlessly fails to
1513 >     * reinitialize if workQueues exists, while still advancing plock.
1514       */
1515      private void fullExternalPush(ForkJoinTask<?> task) {
1516 <        for (Submitter z = null;;) {
1517 <            WorkQueue[] ws; WorkQueue q; int ps, m, r, s;
1516 >        int r = 0; // random index seed
1517 >        for (Submitter z = submitters.get();;) {
1518 >            WorkQueue[] ws; WorkQueue q; int ps, m, k;
1519 >            if (z == null) {
1520 >                if (U.compareAndSwapInt(this, INDEXSEED, r = indexSeed,
1521 >                                        r += SEED_INCREMENT) && r != 0)
1522 >                    submitters.set(z = new Submitter(r));
1523 >            }
1524 >            else if (r == 0) {                  // move to a different index
1525 >                r = z.seed;
1526 >                r ^= r << 13;                   // same xorshift as WorkQueues
1527 >                r ^= r >>> 17;
1528 >                z.seed = r ^= (r << 5);
1529 >            }
1530              if ((ps = plock) < 0)
1531                  throw new RejectedExecutionException();
1532 <            else if ((ws = workQueues) == null || (m = ws.length - 1) < 0) {
1533 <                int n = parallelism - 1; n |= n >>> 1; n |= n >>> 2;
1534 <                n |= n >>> 4; n |= n >>> 8; n |= n >>> 16;
1535 <                WorkQueue[] nws = new WorkQueue[(n + 1) << 1]; // power of two
1536 <                if ((ps & PL_LOCK) != 0 ||
1532 >            else if (ps == 0 || (ws = workQueues) == null ||
1533 >                     (m = ws.length - 1) < 0) { // initialize workQueues
1534 >                int p = parallelism;            // find power of two table size
1535 >                int n = (p > 1) ? p - 1 : 1;    // ensure at least 2 slots
1536 >                n |= n >>> 1;
1537 >                n |= n >>> 2;
1538 >                n |= n >>> 4;
1539 >                n |= n >>> 8;
1540 >                n |= n >>> 16;
1541 >                n = (n + 1) << 1;
1542 >                WorkQueue[] nws = ((ws = workQueues) == null || ws.length == 0 ?
1543 >                                   new WorkQueue[n] : null);
1544 >                if (((ps = plock) & PL_LOCK) != 0 ||
1545                      !U.compareAndSwapInt(this, PLOCK, ps, ps += PL_LOCK))
1546                      ps = acquirePlock();
1547 <                if ((ws = workQueues) == null)
1547 >                if (((ws = workQueues) == null || ws.length == 0) && nws != null)
1548                      workQueues = nws;
1549                  int nps = (ps & SHUTDOWN) | ((ps + PL_LOCK) & ~SHUTDOWN);
1550                  if (!U.compareAndSwapInt(this, PLOCK, ps, nps))
1551                      releasePlock(nps);
1552              }
1553 <            else if (z == null && (z = submitters.get()) == null) {
1554 <                if (U.compareAndSwapInt(this, INDEXSEED,
1555 <                                        s = indexSeed, s += SEED_INCREMENT) &&
1556 <                    s != 0) // skip 0
1557 <                    submitters.set(z = new Submitter(s));
1553 >            else if ((q = ws[k = r & m & SQMASK]) != null) {
1554 >                if (q.qlock == 0 && U.compareAndSwapInt(q, QLOCK, 0, 1)) {
1555 >                    ForkJoinTask<?>[] a = q.array;
1556 >                    int s = q.top;
1557 >                    boolean submitted = false;
1558 >                    try {                      // locked version of push
1559 >                        if ((a != null && a.length > s + 1 - q.base) ||
1560 >                            (a = q.growArray()) != null) {   // must presize
1561 >                            int j = (((a.length - 1) & s) << ASHIFT) + ABASE;
1562 >                            U.putOrderedObject(a, j, task);
1563 >                            q.top = s + 1;
1564 >                            submitted = true;
1565 >                        }
1566 >                    } finally {
1567 >                        q.qlock = 0;  // unlock
1568 >                    }
1569 >                    if (submitted) {
1570 >                        signalWork(ws, q);
1571 >                        return;
1572 >                    }
1573 >                }
1574 >                r = 0; // move on failure
1575              }
1576 <            else {
1577 <                int k = (r = z.seed) & m & SQMASK;
1578 <                if ((q = ws[k]) == null && (ps & PL_LOCK) == 0) {
1579 <                    (q = new WorkQueue(this, null, SHARED_QUEUE)).poolIndex = k;
1580 <                    if (((ps = plock) & PL_LOCK) != 0 ||
1581 <                        !U.compareAndSwapInt(this, PLOCK, ps, ps += PL_LOCK))
1582 <                        ps = acquirePlock();
1583 <                    WorkQueue w = null;
1584 <                    if ((ws = workQueues) != null && k < ws.length &&
1585 <                        (w = ws[k]) == null)
1586 <                        ws[k] = q;
1513 <                    else
1514 <                        q = w;
1515 <                    int nps = (ps & SHUTDOWN) | ((ps + PL_LOCK) & ~SHUTDOWN);
1516 <                    if (!U.compareAndSwapInt(this, PLOCK, ps, nps))
1517 <                        releasePlock(nps);
1518 <                }
1519 <                if (q != null && q.qlock == 0 && q.fullPush(task, false))
1520 <                    return;
1521 <                r ^= r << 13;                // same xorshift as WorkQueues
1522 <                r ^= r >>> 17;
1523 <                z.seed = r ^= r << 5;        // move to a different index
1576 >            else if (((ps = plock) & PL_LOCK) == 0) { // create new queue
1577 >                q = new WorkQueue(this, null, SHARED_QUEUE, r);
1578 >                q.poolIndex = (short)k;
1579 >                if (((ps = plock) & PL_LOCK) != 0 ||
1580 >                    !U.compareAndSwapInt(this, PLOCK, ps, ps += PL_LOCK))
1581 >                    ps = acquirePlock();
1582 >                if ((ws = workQueues) != null && k < ws.length && ws[k] == null)
1583 >                    ws[k] = q;
1584 >                int nps = (ps & SHUTDOWN) | ((ps + PL_LOCK) & ~SHUTDOWN);
1585 >                if (!U.compareAndSwapInt(this, PLOCK, ps, nps))
1586 >                    releasePlock(nps);
1587              }
1588 +            else
1589 +                r = 0;
1590          }
1591      }
1592  
# Line 1532 | Line 1597 | public class ForkJoinPool extends Abstra
1597       */
1598      final void incrementActiveCount() {
1599          long c;
1600 <        do {} while (!U.compareAndSwapLong(this, CTL, c = ctl, c + AC_UNIT));
1600 >        do {} while (!U.compareAndSwapLong
1601 >                     (this, CTL, c = ctl, ((c & ~AC_MASK) |
1602 >                                           ((c & AC_MASK) + AC_UNIT))));
1603      }
1604  
1605      /**
1606 <     * 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.
1606 >     * Tries to create or activate a worker if too few are active.
1607       *
1608 <     * @param q if non-null, the queue holding tasks to be signalled
1609 <     * @param signals the target number of signals.
1608 >     * @param ws the worker array to use to find signallees
1609 >     * @param q if non-null, the queue holding tasks to be processed
1610       */
1611 <    final void signalWork(WorkQueue q, int signals) {
1612 <        long c; int e, u, i; WorkQueue[] ws; WorkQueue w; Thread p;
1613 <        while ((u = (int)((c = ctl) >>> 32)) < 0) {
1614 <            if ((e = (int)c) > 0) {
1615 <                if ((ws = workQueues) != null && ws.length > (i = e & SMASK) &&
1616 <                    (w = ws[i]) != null && w.eventCount == (e | INT_SIGN)) {
1617 <                    long nc = (((long)(w.nextWait & E_MASK)) |
1618 <                               ((long)(u + UAC_UNIT) << 32));
1619 <                    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);
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;
1611 >    final void signalWork(WorkQueue[] ws, WorkQueue q) {
1612 >        for (;;) {
1613 >            long c; int e, u, i; WorkQueue w; Thread p;
1614 >            if ((u = (int)((c = ctl) >>> 32)) >= 0)
1615 >                break;
1616 >            if ((e = (int)c) <= 0) {
1617 >                if ((short)u < 0)
1618 >                    tryAddWorker();
1619 >                break;
1620              }
1621 <            else if (e == 0 && (u & SHORT_SIGN) != 0) {
1622 <                long nc = (long)(((u + UTC_UNIT) & UTC_MASK) |
1623 <                                 ((u + UAC_UNIT) & UAC_MASK)) << 32;
1624 <                if (U.compareAndSwapLong(this, CTL, c, nc)) {
1625 <                    ForkJoinWorkerThread wt = null;
1626 <                    Throwable ex = null;
1627 <                    boolean started = false;
1628 <                    try {
1629 <                        ForkJoinWorkerThreadFactory fac;
1630 <                        if ((fac = factory) != null &&
1631 <                            (wt = fac.newThread(this)) != null) {
1632 <                            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 <                }
1621 >            if (ws == null || ws.length <= (i = e & SMASK) ||
1622 >                (w = ws[i]) == null)
1623 >                break;
1624 >            long nc = (((long)(w.nextWait & E_MASK)) |
1625 >                       ((long)(u + UAC_UNIT)) << 32);
1626 >            int ne = (e + E_SEQ) & E_MASK;
1627 >            if (w.eventCount == (e | INT_SIGN) &&
1628 >                U.compareAndSwapLong(this, CTL, c, nc)) {
1629 >                w.eventCount = ne;
1630 >                if ((p = w.parker) != null)
1631 >                    U.unpark(p);
1632 >                break;
1633              }
1634 <            else
1634 >            if (q != null && q.base >= q.top)
1635                  break;
1636          }
1637      }
# Line 1600 | Line 1642 | public class ForkJoinPool extends Abstra
1642       * Top-level runloop for workers, called by ForkJoinWorkerThread.run.
1643       */
1644      final void runWorker(WorkQueue w) {
1645 <        // initialize queue array in this thread
1646 <        w.array = new ForkJoinTask<?>[WorkQueue.INITIAL_QUEUE_CAPACITY];
1647 <        do { w.runTask(scan(w)); } while (w.qlock >= 0);
1645 >        w.growArray(); // allocate queue
1646 >        for (int r = w.hint; scan(w, r) == 0; ) {
1647 >            r ^= r << 13; r ^= r >>> 17; r ^= r << 5; // xorshift
1648 >        }
1649      }
1650  
1651      /**
1652 <     * Scans for and, if found, returns one task, else possibly
1652 >     * Scans for and, if found, runs one task, else possibly
1653       * inactivates the worker. This method operates on single reads of
1654       * volatile state and is designed to be re-invoked continuously,
1655       * in part because it returns upon detecting inconsistencies,
1656       * contention, or state changes that indicate possible success on
1657       * re-invocation.
1658       *
1659 <     * The scan searches for tasks across a random permutation of
1660 <     * queues (starting at a random index and stepping by a random
1661 <     * relative prime, checking each at least once).  The scan
1662 <     * terminates upon either finding a non-empty queue, or completing
1663 <     * the sweep. If the worker is not inactivated, it takes and
1664 <     * returns a task from this queue. Otherwise, if not activated, it
1665 <     * signals workers (that may include itself) and returns so caller
1666 <     * can retry. Also returns for trtry if the worker array may have
1667 <     * 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 <     *
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 enqueued and none of the above apply, possibly
1636 <     * (with 1/2 probability) park awaiting signal, else lingering to
1637 <     * help scan and signal.
1659 >     * The scan searches for tasks across queues starting at a random
1660 >     * index, checking each at least twice.  The scan terminates upon
1661 >     * either finding a non-empty queue, or completing the sweep. If
1662 >     * the worker is not inactivated, it takes and runs a task from
1663 >     * this queue. Otherwise, if not activated, it tries to activate
1664 >     * itself or some other worker by signalling. On failure to find a
1665 >     * task, returns (for retry) if pool state may have changed during
1666 >     * an empty scan, or tries to inactivate if active, else possibly
1667 >     * blocks or terminates via method awaitWork.
1668       *
1669       * @param w the worker (via its WorkQueue)
1670 <     * @return a task or null if none found
1670 >     * @param r a random seed
1671 >     * @return worker qlock status if would have waited, else 0
1672       */
1673 <    private final ForkJoinTask<?> scan(WorkQueue w) {
1674 <        WorkQueue[] ws; WorkQueue q;           // first update random seed
1675 <        int r = w.seed; r ^= r << 13; r ^= r >>> 17; w.seed = r ^= r << 5;
1676 <        int ps = plock, m;                     // volatile read order matters
1677 <        if ((ws = workQueues) != null && (m = ws.length - 1) > 0) {
1678 <            int ec = w.eventCount;             // ec is negative if inactive
1679 <            int step = (r >>> 16) | 1;         // relatively prime
1680 <            for (int j = (m + 1) << 2;  ; --j, r += step) {
1681 <                ForkJoinTask<?> t; ForkJoinTask<?>[] a; int b, n;
1682 <                if ((q = ws[r & m]) != null && (b = q.base) - q.top < 0 &&
1683 <                    (a = q.array) != null) {   // probably nonempty
1684 <                    int i = (((a.length - 1) & b) << ASHIFT) + ABASE;
1685 <                    t = (ForkJoinTask<?>)U.getObjectVolatile(a, i);
1686 <                    if (q.base == b && ec >= 0 && t != null &&
1687 <                        U.compareAndSwapObject(a, i, t, null)) {
1688 <                        if ((n = q.top - (q.base = b + 1)) > 0)
1689 <                            signalWork(q, n);
1690 <                        return t;              // taken
1691 <                    }
1692 <                    if (j < m || (ec < 0 && (ec = w.eventCount) < 0)) {
1693 <                        if ((n = q.queueSize() - 1) > 0)
1694 <                            signalWork(q, n);
1695 <                        break;                 // let caller retry after signal
1696 <                    }
1697 <                }
1698 <                else if (j < 0) {              // end of scan
1699 <                    long c = ctl; int e;
1700 <                    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)));
1673 >    private final int scan(WorkQueue w, int r) {
1674 >        WorkQueue[] ws; int m;
1675 >        long c = ctl;                            // for consistency check
1676 >        if ((ws = workQueues) != null && (m = ws.length - 1) >= 0 && w != null) {
1677 >            for (int j = m + m + 1, ec = w.eventCount;;) {
1678 >                WorkQueue q; int b, e; ForkJoinTask<?>[] a; ForkJoinTask<?> t;
1679 >                if ((q = ws[(r - j) & m]) != null &&
1680 >                    (b = q.base) - q.top < 0 && (a = q.array) != null) {
1681 >                    long i = (((a.length - 1) & b) << ASHIFT) + ABASE;
1682 >                    if ((t = ((ForkJoinTask<?>)
1683 >                              U.getObjectVolatile(a, i))) != null) {
1684 >                        if (ec < 0)
1685 >                            helpRelease(c, ws, w, q, b);
1686 >                        else if (q.base == b &&
1687 >                                 U.compareAndSwapObject(a, i, t, null)) {
1688 >                            U.putOrderedInt(q, QBASE, b + 1);
1689 >                            if ((b + 1) - q.top < 0)
1690 >                                signalWork(ws, q);
1691 >                            w.runTask(t);
1692 >                        }
1693 >                    }
1694 >                    break;
1695 >                }
1696 >                else if (--j < 0) {
1697 >                    if ((ec | (e = (int)c)) < 0) // inactive or terminating
1698 >                        return awaitWork(w, c, ec);
1699 >                    else if (ctl == c) {         // try to inactivate and enqueue
1700 >                        long nc = (long)ec | ((c - AC_UNIT) & (AC_MASK|TC_MASK));
1701                          w.nextWait = e;
1702 <                        w.eventCount = ec | INT_SIGN; // mark as inactive
1703 <                        if (ctl != c ||
1704 <                            !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);
1702 >                        w.eventCount = ec | INT_SIGN;
1703 >                        if (!U.compareAndSwapLong(this, CTL, c, nc))
1704 >                            w.eventCount = ec;   // back out
1705                      }
1706                      break;
1707                  }
1708              }
1709          }
1710 <        return null;
1710 >        return 0;
1711      }
1712  
1713      /**
1714 <     * If inactivating worker w has caused the pool to become
1715 <     * quiescent, checks for pool termination, and, so long as this is
1716 <     * not the only worker, waits for event for up to a given
1717 <     * duration.  On timeout, if ctl has not changed, terminates the
1718 <     * worker, which will in turn wake up another worker to possibly
1719 <     * repeat this process.
1714 >     * A continuation of scan(), possibly blocking or terminating
1715 >     * worker w. Returns without blocking if pool state has apparently
1716 >     * changed since last invocation.  Also, if inactivating w has
1717 >     * caused the pool to become quiescent, checks for pool
1718 >     * termination, and, so long as this is not the only worker, waits
1719 >     * for event for up to a given duration.  On timeout, if ctl has
1720 >     * not changed, terminates the worker, which will in turn wake up
1721 >     * another worker to possibly repeat this process.
1722       *
1723       * @param w the calling worker
1724 <     * @param currentCtl the ctl value triggering possible quiescence
1725 <     * @param prevCtl the ctl value to restore if thread is terminated
1724 >     * @param c the ctl value on entry to scan
1725 >     * @param ec the worker's eventCount on entry to scan
1726       */
1727 <    private void idleAwaitWork(WorkQueue w, long currentCtl, long prevCtl) {
1728 <        if (w.eventCount < 0 &&
1729 <            (this == commonPool || !tryTerminate(false, false)) &&
1730 <            (int)prevCtl != 0) {
1731 <            int dc = -(short)(currentCtl >>> TC_SHIFT);
1732 <            long parkTime = dc < 0 ? FAST_IDLE_TIMEOUT: (dc + 1) * IDLE_TIMEOUT;
1733 <            long deadline = System.nanoTime() + parkTime - 100000L; // 1ms slop
1734 <            Thread wt = Thread.currentThread();
1735 <            while (ctl == currentCtl) {
1736 <                Thread.interrupted();  // timed variant of version in scan()
1737 <                U.putObject(wt, PARKBLOCKER, this);
1738 <                w.parker = wt;
1739 <                if (ctl == currentCtl)
1740 <                    U.park(false, parkTime);
1741 <                w.parker = null;
1742 <                U.putObject(wt, PARKBLOCKER, null);
1743 <                if (ctl != currentCtl)
1744 <                    break;
1745 <                if (deadline - System.nanoTime() <= 0L &&
1746 <                    U.compareAndSwapLong(this, CTL, currentCtl, prevCtl)) {
1747 <                    w.eventCount = (w.eventCount + E_SEQ) | E_MASK;
1748 <                    w.qlock = -1;   // shrink
1749 <                    break;
1727 >    private final int awaitWork(WorkQueue w, long c, int ec) {
1728 >        int stat, ns; long parkTime, deadline;
1729 >        if ((stat = w.qlock) >= 0 && w.eventCount == ec && ctl == c &&
1730 >            !Thread.interrupted()) {
1731 >            int e = (int)c;
1732 >            int u = (int)(c >>> 32);
1733 >            int d = (u >> UAC_SHIFT) + parallelism; // active count
1734 >
1735 >            if (e < 0 || (d <= 0 && tryTerminate(false, false)))
1736 >                stat = w.qlock = -1;          // pool is terminating
1737 >            else if ((ns = w.nsteals) != 0) { // collect steals and retry
1738 >                long sc;
1739 >                w.nsteals = 0;
1740 >                do {} while (!U.compareAndSwapLong(this, STEALCOUNT,
1741 >                                                   sc = stealCount, sc + ns));
1742 >            }
1743 >            else {
1744 >                long pc = ((d > 0 || ec != (e | INT_SIGN)) ? 0L :
1745 >                           ((long)(w.nextWait & E_MASK)) | // ctl to restore
1746 >                           ((long)(u + UAC_UNIT)) << 32);
1747 >                if (pc != 0L) {               // timed wait if last waiter
1748 >                    int dc = -(short)(c >>> TC_SHIFT);
1749 >                    parkTime = (dc < 0 ? FAST_IDLE_TIMEOUT:
1750 >                                (dc + 1) * IDLE_TIMEOUT);
1751 >                    deadline = System.nanoTime() + parkTime - TIMEOUT_SLOP;
1752 >                }
1753 >                else
1754 >                    parkTime = deadline = 0L;
1755 >                if (w.eventCount == ec && ctl == c) {
1756 >                    Thread wt = Thread.currentThread();
1757 >                    U.putObject(wt, PARKBLOCKER, this);
1758 >                    w.parker = wt;            // emulate LockSupport.park
1759 >                    if (w.eventCount == ec && ctl == c)
1760 >                        U.park(false, parkTime);  // must recheck before park
1761 >                    w.parker = null;
1762 >                    U.putObject(wt, PARKBLOCKER, null);
1763 >                    if (parkTime != 0L && ctl == c &&
1764 >                        deadline - System.nanoTime() <= 0L &&
1765 >                        U.compareAndSwapLong(this, CTL, c, pc))
1766 >                        stat = w.qlock = -1;  // shrink pool
1767                  }
1768              }
1769          }
1770 +        return stat;
1771      }
1772  
1773      /**
1774 <     * Scans through queues looking for work while joining a task;
1775 <     * if any are present, signals.
1776 <     *
1777 <     * @param task to return early if done
1778 <     * @param origin an index to start scan
1779 <     */
1780 <    final int helpSignal(ForkJoinTask<?> task, int origin) {
1781 <        WorkQueue[] ws; WorkQueue q; int m, n, s;
1782 <        if (task != null && (ws = workQueues) != null &&
1783 <            (m = ws.length - 1) >= 0) {
1784 <            for (int i = 0; i <= m; ++i) {
1785 <                if ((s = task.status) < 0)
1786 <                    return s;
1787 <                if ((q = ws[(i + origin) & m]) != null &&
1788 <                    (n = q.queueSize()) > 0) {
1789 <                    signalWork(q, n);
1790 <                    if ((int)(ctl >> AC_SHIFT) >= 0)
1791 <                        break;
1792 <                }
1774 >     * Possibly releases (signals) a worker. Called only from scan()
1775 >     * when a worker with apparently inactive status finds a non-empty
1776 >     * queue. This requires revalidating all of the associated state
1777 >     * from caller.
1778 >     */
1779 >    private final void helpRelease(long c, WorkQueue[] ws, WorkQueue w,
1780 >                                   WorkQueue q, int b) {
1781 >        WorkQueue v; int e, i; Thread p;
1782 >        if (w != null && w.eventCount < 0 && (e = (int)c) > 0 &&
1783 >            ws != null && ws.length > (i = e & SMASK) &&
1784 >            (v = ws[i]) != null && ctl == c) {
1785 >            long nc = (((long)(v.nextWait & E_MASK)) |
1786 >                       ((long)((int)(c >>> 32) + UAC_UNIT)) << 32);
1787 >            int ne = (e + E_SEQ) & E_MASK;
1788 >            if (q != null && q.base == b && w.eventCount < 0 &&
1789 >                v.eventCount == (e | INT_SIGN) &&
1790 >                U.compareAndSwapLong(this, CTL, c, nc)) {
1791 >                v.eventCount = ne;
1792 >                if ((p = v.parker) != null)
1793 >                    U.unpark(p);
1794              }
1795          }
1763        return 0;
1796      }
1797  
1798      /**
# Line 1783 | Line 1815 | public class ForkJoinPool extends Abstra
1815       */
1816      private int tryHelpStealer(WorkQueue joiner, ForkJoinTask<?> task) {
1817          int stat = 0, steps = 0;                    // bound to avoid cycles
1818 <        if (joiner != null && task != null) {       // hoist null checks
1818 >        if (task != null && joiner != null &&
1819 >            joiner.base - joiner.top >= 0) {        // hoist checks
1820              restart: for (;;) {
1821                  ForkJoinTask<?> subtask = task;     // current target
1822                  for (WorkQueue j = joiner, v;;) {   // v is stealer of subtask
# Line 1794 | Line 1827 | public class ForkJoinPool extends Abstra
1827                      }
1828                      if ((ws = workQueues) == null || (m = ws.length - 1) <= 0)
1829                          break restart;              // shutting down
1830 <                    if ((v = ws[h = (j.stealHint | 1) & m]) == null ||
1830 >                    if ((v = ws[h = (j.hint | 1) & m]) == null ||
1831                          v.currentSteal != subtask) {
1832                          for (int origin = h;;) {    // find stealer
1833                              if (((h = (h + 2) & m) & 15) == 1 &&
# Line 1802 | Line 1835 | public class ForkJoinPool extends Abstra
1835                                  continue restart;   // occasional staleness check
1836                              if ((v = ws[h]) != null &&
1837                                  v.currentSteal == subtask) {
1838 <                                j.stealHint = h;    // save hint
1838 >                                j.hint = h;        // save hint
1839                                  break;
1840                              }
1841                              if (h == origin)
# Line 1810 | Line 1843 | public class ForkJoinPool extends Abstra
1843                          }
1844                      }
1845                      for (;;) { // help stealer or descend to its stealer
1846 <                        ForkJoinTask[] a;  int b;
1846 >                        ForkJoinTask<?>[] a; int b;
1847                          if (subtask.status < 0)     // surround probes with
1848                              continue restart;       //   consistency checks
1849                          if ((b = v.base) - v.top < 0 && (a = v.array) != null) {
# Line 1821 | Line 1854 | public class ForkJoinPool extends Abstra
1854                                  v.currentSteal != subtask)
1855                                  continue restart;   // stale
1856                              stat = 1;               // apparent progress
1857 <                            if (t != null && v.base == b &&
1858 <                                U.compareAndSwapObject(a, i, t, null)) {
1859 <                                v.base = b + 1;     // help stealer
1860 <                                joiner.runSubtask(t);
1857 >                            if (v.base == b) {
1858 >                                if (t == null)
1859 >                                    break restart;
1860 >                                if (U.compareAndSwapObject(a, i, t, null)) {
1861 >                                    U.putOrderedInt(v, QBASE, b + 1);
1862 >                                    ForkJoinTask<?> ps = joiner.currentSteal;
1863 >                                    int jt = joiner.top;
1864 >                                    do {
1865 >                                        joiner.currentSteal = t;
1866 >                                        t.doExec(); // clear local tasks too
1867 >                                    } while (task.status >= 0 &&
1868 >                                             joiner.top != jt &&
1869 >                                             (t = joiner.pop()) != null);
1870 >                                    joiner.currentSteal = ps;
1871 >                                    break restart;
1872 >                                }
1873                              }
1829                            else if (v.base == b && ++steps == MAX_HELP)
1830                                break restart;      // v apparently stalled
1874                          }
1875                          else {                      // empty -- try to descend
1876                              ForkJoinTask<?> next = v.currentJoin;
# Line 1851 | Line 1894 | public class ForkJoinPool extends Abstra
1894  
1895      /**
1896       * Analog of tryHelpStealer for CountedCompleters. Tries to steal
1897 <     * and run tasks within the target's computation
1897 >     * and run tasks within the target's computation.
1898       *
1899       * @param task the task to join
1857     * @param mode if shared, exit upon completing any task
1858     * if all workers are active
1859     *
1900       */
1901 <    private int helpComplete(ForkJoinTask<?> task, int mode) {
1902 <        WorkQueue[] ws; WorkQueue q; int m, n, s;
1903 <        if (task != null && (ws = workQueues) != null &&
1904 <            (m = ws.length - 1) >= 0) {
1905 <            for (int j = 1, origin = j;;) {
1901 >    private int helpComplete(WorkQueue joiner, CountedCompleter<?> task) {
1902 >        WorkQueue[] ws; int m;
1903 >        int s = 0;
1904 >        if ((ws = workQueues) != null && (m = ws.length - 1) >= 0 &&
1905 >            joiner != null && task != null) {
1906 >            int j = joiner.poolIndex;
1907 >            int scans = m + m + 1;
1908 >            long c = 0L;              // for stability check
1909 >            for (int k = scans; ; j += 2) {
1910 >                WorkQueue q;
1911                  if ((s = task.status) < 0)
1912 <                    return s;
1913 <                if ((q = ws[j & m]) != null && q.pollAndExecCC(task)) {
1914 <                    origin = j;
1915 <                    if (mode == SHARED_QUEUE && (int)(ctl >> AC_SHIFT) >= 0)
1912 >                    break;
1913 >                else if (joiner.internalPopAndExecCC(task))
1914 >                    k = scans;
1915 >                else if ((s = task.status) < 0)
1916 >                    break;
1917 >                else if ((q = ws[j & m]) != null && q.pollAndExecCC(task))
1918 >                    k = scans;
1919 >                else if (--k < 0) {
1920 >                    if (c == (c = ctl))
1921                          break;
1922 +                    k = scans;
1923                  }
1873                else if ((j = (j + 2) & m) == origin)
1874                    break;
1924              }
1925          }
1926 <        return 0;
1926 >        return s;
1927      }
1928  
1929      /**
# Line 1883 | Line 1932 | public class ForkJoinPool extends Abstra
1932       * for blocking. Fails on contention or termination. Otherwise,
1933       * adds a new thread if no idle workers are available and pool
1934       * may become starved.
1935 +     *
1936 +     * @param c the assumed ctl value
1937       */
1938 <    final boolean tryCompensate() {
1939 <        int pc = parallelism, e, u, i, tc; long c;
1940 <        WorkQueue[] ws; WorkQueue w; Thread p;
1941 <        if ((e = (int)(c = ctl)) >= 0 && (ws = workQueues) != null) {
1942 <            if (e != 0 && (i = e & SMASK) < ws.length &&
1943 <                (w = ws[i]) != null && w.eventCount == (e | INT_SIGN)) {
1938 >    final boolean tryCompensate(long c) {
1939 >        WorkQueue[] ws = workQueues;
1940 >        int pc = parallelism, e = (int)c, m, tc;
1941 >        if (ws != null && (m = ws.length - 1) >= 0 && e >= 0 && ctl == c) {
1942 >            WorkQueue w = ws[e & m];
1943 >            if (e != 0 && w != null) {
1944 >                Thread p;
1945                  long nc = ((long)(w.nextWait & E_MASK) |
1946                             (c & (AC_MASK|TC_MASK)));
1947 <                if (U.compareAndSwapLong(this, CTL, c, nc)) {
1948 <                    w.eventCount = (e + E_SEQ) & E_MASK;
1947 >                int ne = (e + E_SEQ) & E_MASK;
1948 >                if (w.eventCount == (e | INT_SIGN) &&
1949 >                    U.compareAndSwapLong(this, CTL, c, nc)) {
1950 >                    w.eventCount = ne;
1951                      if ((p = w.parker) != null)
1952                          U.unpark(p);
1953                      return true;   // replace with idle worker
1954                  }
1955              }
1956 <            else if ((short)((u = (int)(c >>> 32)) >>> UTC_SHIFT) >= 0 &&
1957 <                     (u >> UAC_SHIFT) + pc > 1) {
1956 >            else if ((tc = (short)(c >>> TC_SHIFT)) >= 0 &&
1957 >                     (int)(c >> AC_SHIFT) + pc > 1) {
1958                  long nc = ((c - AC_UNIT) & AC_MASK) | (c & ~AC_MASK);
1959                  if (U.compareAndSwapLong(this, CTL, c, nc))
1960 <                    return true;    // no compensation
1960 >                    return true;   // no compensation
1961              }
1962 <            else if ((tc = u + pc) < MAX_CAP) {
1962 >            else if (tc + pc < MAX_CAP) {
1963                  long nc = ((c + TC_UNIT) & TC_MASK) | (c & ~TC_MASK);
1964                  if (U.compareAndSwapLong(this, CTL, c, nc)) {
1965 +                    ForkJoinWorkerThreadFactory fac;
1966                      Throwable ex = null;
1967                      ForkJoinWorkerThread wt = null;
1968                      try {
1914                        ForkJoinWorkerThreadFactory fac;
1969                          if ((fac = factory) != null &&
1970                              (wt = fac.newThread(this)) != null) {
1971                              wt.start();
# Line 1920 | Line 1974 | public class ForkJoinPool extends Abstra
1974                      } catch (Throwable rex) {
1975                          ex = rex;
1976                      }
1977 <                    deregisterWorker(wt, ex); // adjust counts etc
1977 >                    deregisterWorker(wt, ex); // clean up and return false
1978                  }
1979              }
1980          }
# Line 1936 | Line 1990 | public class ForkJoinPool extends Abstra
1990       */
1991      final int awaitJoin(WorkQueue joiner, ForkJoinTask<?> task) {
1992          int s = 0;
1993 <        if (joiner != null && task != null && (s = task.status) >= 0) {
1993 >        if (task != null && (s = task.status) >= 0 && joiner != null) {
1994              ForkJoinTask<?> prevJoin = joiner.currentJoin;
1995              joiner.currentJoin = task;
1996 <            do {} while ((s = task.status) >= 0 &&
1997 <                         joiner.queueSize() > 0 &&
1998 <                         joiner.tryRemoveAndExec(task)); // process local tasks
1999 <            if (s >= 0 && (s = task.status) >= 0 &&
2000 <                (s = helpSignal(task, joiner.poolIndex)) >= 0 &&
1947 <                (task instanceof CountedCompleter))
1948 <                s = helpComplete(task, LIFO_QUEUE);
1996 >            do {} while (joiner.tryRemoveAndExec(task) && // process local tasks
1997 >                         (s = task.status) >= 0);
1998 >            if (s >= 0 && (task instanceof CountedCompleter))
1999 >                s = helpComplete(joiner, (CountedCompleter<?>)task);
2000 >            long cc = 0;        // for stability checks
2001              while (s >= 0 && (s = task.status) >= 0) {
2002 <                if ((joiner.queueSize() > 0 ||           // try helping
2003 <                     (s = tryHelpStealer(joiner, task)) == 0) &&
2004 <                    (s = task.status) >= 0 && tryCompensate()) {
2005 <                    if (task.trySetSignal() && (s = task.status) >= 0) {
2006 <                        synchronized (task) {
2007 <                            if (task.status >= 0) {
2008 <                                try {                // see ForkJoinTask
2009 <                                    task.wait();     //  for explanation
2010 <                                } catch (InterruptedException ie) {
2002 >                if ((s = tryHelpStealer(joiner, task)) == 0 &&
2003 >                    (s = task.status) >= 0) {
2004 >                    if (!tryCompensate(cc))
2005 >                        cc = ctl;
2006 >                    else {
2007 >                        if (task.trySetSignal() && (s = task.status) >= 0) {
2008 >                            synchronized (task) {
2009 >                                if (task.status >= 0) {
2010 >                                    try {                // see ForkJoinTask
2011 >                                        task.wait();     //  for explanation
2012 >                                    } catch (InterruptedException ie) {
2013 >                                    }
2014                                  }
2015 +                                else
2016 +                                    task.notifyAll();
2017                              }
1961                            else
1962                                task.notifyAll();
2018                          }
2019 +                        long c; // reactivate
2020 +                        do {} while (!U.compareAndSwapLong
2021 +                                     (this, CTL, c = ctl,
2022 +                                      ((c & ~AC_MASK) |
2023 +                                       ((c & AC_MASK) + AC_UNIT))));
2024                      }
1965                    long c;                          // re-activate
1966                    do {} while (!U.compareAndSwapLong
1967                                 (this, CTL, c = ctl, c + AC_UNIT));
2025                  }
2026              }
2027              joiner.currentJoin = prevJoin;
# Line 1985 | Line 2042 | public class ForkJoinPool extends Abstra
2042          if (joiner != null && task != null && (s = task.status) >= 0) {
2043              ForkJoinTask<?> prevJoin = joiner.currentJoin;
2044              joiner.currentJoin = task;
2045 <            do {} while ((s = task.status) >= 0 &&
2046 <                         joiner.queueSize() > 0 &&
2047 <                         joiner.tryRemoveAndExec(task));
2048 <            if (s >= 0 && (s = task.status) >= 0 &&
2049 <                (s = helpSignal(task, joiner.poolIndex)) >= 0 &&
1993 <                (task instanceof CountedCompleter))
1994 <                s = helpComplete(task, LIFO_QUEUE);
1995 <            if (s >= 0 && joiner.queueSize() == 0) {
2045 >            do {} while (joiner.tryRemoveAndExec(task) && // process local tasks
2046 >                         (s = task.status) >= 0);
2047 >            if (s >= 0) {
2048 >                if (task instanceof CountedCompleter)
2049 >                    helpComplete(joiner, (CountedCompleter<?>)task);
2050                  do {} while (task.status >= 0 &&
2051                               tryHelpStealer(joiner, task) > 0);
2052              }
# Line 2002 | Line 2056 | public class ForkJoinPool extends Abstra
2056  
2057      /**
2058       * Returns a (probably) non-empty steal queue, if one is found
2059 <     * during a random, then cyclic scan, else null.  This method must
2060 <     * be retried by caller if, by the time it tries to use the queue,
2061 <     * it is empty.
2062 <     * @param r a (random) seed for scanning
2063 <     */
2064 <    private WorkQueue findNonEmptyStealQueue(int r) {
2065 <        int step = (r >>> 16) | 1;
2066 <        for (WorkQueue[] ws;;) {
2067 <            int ps = plock, m;
2068 <            if ((ws = workQueues) == null || (m = ws.length - 1) < 1)
2069 <                return null;
2070 <            for (int j = (m + 1) << 2; ; r += step) {
2017 <                WorkQueue q = ws[((r << 1) | 1) & m];
2018 <                if (q != null && q.queueSize() > 0)
2019 <                    return q;
2020 <                else if (--j < 0) {
2021 <                    if (plock == ps)
2022 <                        return null;
2023 <                    break;
2059 >     * during a scan, else null.  This method must be retried by
2060 >     * caller if, by the time it tries to use the queue, it is empty.
2061 >     */
2062 >    private WorkQueue findNonEmptyStealQueue() {
2063 >        int r = ThreadLocalRandom.current().nextInt();
2064 >        for (;;) {
2065 >            int ps = plock, m; WorkQueue[] ws; WorkQueue q;
2066 >            if ((ws = workQueues) != null && (m = ws.length - 1) >= 0) {
2067 >                for (int j = (m + 1) << 2; j >= 0; --j) {
2068 >                    if ((q = ws[(((r - j) << 1) | 1) & m]) != null &&
2069 >                        q.base - q.top < 0)
2070 >                        return q;
2071                  }
2072              }
2073 +            if (plock == ps)
2074 +                return null;
2075          }
2076      }
2077  
# Line 2033 | Line 2082 | public class ForkJoinPool extends Abstra
2082       * find tasks either.
2083       */
2084      final void helpQuiescePool(WorkQueue w) {
2085 +        ForkJoinTask<?> ps = w.currentSteal;
2086          for (boolean active = true;;) {
2087 <            ForkJoinTask<?> localTask; // exhaust local queue
2088 <            while ((localTask = w.nextLocalTask()) != null)
2089 <                localTask.doExec();
2090 <            // Similar to loop in scan(), but ignoring submissions
2041 <            WorkQueue q = findNonEmptyStealQueue(w.nextSeed());
2042 <            if (q != null) {
2043 <                ForkJoinTask<?> t; int b;
2087 >            long c; WorkQueue q; ForkJoinTask<?> t; int b;
2088 >            while ((t = w.nextLocalTask()) != null)
2089 >                t.doExec();
2090 >            if ((q = findNonEmptyStealQueue()) != null) {
2091                  if (!active) {      // re-establish active count
2045                    long c;
2092                      active = true;
2093                      do {} while (!U.compareAndSwapLong
2094 <                                 (this, CTL, c = ctl, c + AC_UNIT));
2094 >                                 (this, CTL, c = ctl,
2095 >                                  ((c & ~AC_MASK) |
2096 >                                   ((c & AC_MASK) + AC_UNIT))));
2097 >                }
2098 >                if ((b = q.base) - q.top < 0 && (t = q.pollAt(b)) != null) {
2099 >                    (w.currentSteal = t).doExec();
2100 >                    w.currentSteal = ps;
2101                  }
2050                if ((b = q.base) - q.top < 0 && (t = q.pollAt(b)) != null)
2051                    w.runSubtask(t);
2102              }
2103 <            else {
2104 <                long c;
2105 <                if (active) {       // decrement active count without queuing
2103 >            else if (active) {      // decrement active count without queuing
2104 >                long nc = ((c = ctl) & ~AC_MASK) | ((c & AC_MASK) - AC_UNIT);
2105 >                if ((int)(nc >> AC_SHIFT) + parallelism == 0)
2106 >                    break;          // bypass decrement-then-increment
2107 >                if (U.compareAndSwapLong(this, CTL, c, nc))
2108                      active = false;
2057                    do {} while (!U.compareAndSwapLong
2058                                 (this, CTL, c = ctl, c -= AC_UNIT));
2059                }
2060                else
2061                    c = ctl;        // re-increment on exit
2062                if ((int)(c >> AC_SHIFT) + parallelism == 0) {
2063                    do {} while (!U.compareAndSwapLong
2064                                 (this, CTL, c = ctl, c + AC_UNIT));
2065                    break;
2066                }
2109              }
2110 +            else if ((int)((c = ctl) >> AC_SHIFT) + parallelism <= 0 &&
2111 +                     U.compareAndSwapLong
2112 +                     (this, CTL, c, ((c & ~AC_MASK) |
2113 +                                     ((c & AC_MASK) + AC_UNIT))))
2114 +                break;
2115          }
2116      }
2117  
# Line 2078 | Line 2125 | public class ForkJoinPool extends Abstra
2125              WorkQueue q; int b;
2126              if ((t = w.nextLocalTask()) != null)
2127                  return t;
2128 <            if ((q = findNonEmptyStealQueue(w.nextSeed())) == null)
2128 >            if ((q = findNonEmptyStealQueue()) == null)
2129                  return null;
2130              if ((b = q.base) - q.top < 0 && (t = q.pollAt(b)) != null)
2131                  return t;
# Line 2110 | Line 2157 | public class ForkJoinPool extends Abstra
2157       * producing extra tasks amortizes the uncertainty of progress and
2158       * diffusion assumptions.
2159       *
2160 <     * So, users will want to use values larger, but not much larger
2160 >     * So, users will want to use values larger (but not much larger)
2161       * than 1 to both smooth over transient shortages and hedge
2162       * against uneven progress; as traded off against the cost of
2163       * extra task overhead. We leave the user to pick a threshold
# Line 2134 | Line 2181 | public class ForkJoinPool extends Abstra
2181      static int getSurplusQueuedTaskCount() {
2182          Thread t; ForkJoinWorkerThread wt; ForkJoinPool pool; WorkQueue q;
2183          if (((t = Thread.currentThread()) instanceof ForkJoinWorkerThread)) {
2184 <            int b = (q = (wt = (ForkJoinWorkerThread)t).workQueue).base;
2185 <            int p = (pool = wt.pool).parallelism;
2184 >            int p = (pool = (wt = (ForkJoinWorkerThread)t).pool).parallelism;
2185 >            int n = (q = wt.workQueue).top - q.base;
2186              int a = (int)(pool.ctl >> AC_SHIFT) + p;
2187 <            return q.top - b - (a > (p >>>= 1) ? 0 :
2188 <                                a > (p >>>= 1) ? 1 :
2189 <                                a > (p >>>= 1) ? 2 :
2190 <                                a > (p >>>= 1) ? 4 :
2191 <                                8);
2187 >            return n - (a > (p >>>= 1) ? 0 :
2188 >                        a > (p >>>= 1) ? 1 :
2189 >                        a > (p >>>= 1) ? 2 :
2190 >                        a > (p >>>= 1) ? 4 :
2191 >                        8);
2192          }
2193          return 0;
2194      }
# Line 2163 | Line 2210 | public class ForkJoinPool extends Abstra
2210       * @return true if now terminating or terminated
2211       */
2212      private boolean tryTerminate(boolean now, boolean enable) {
2213 <        if (this == commonPool)                     // cannot shut down
2213 >        int ps;
2214 >        if (this == common)                        // cannot shut down
2215              return false;
2216 +        if ((ps = plock) >= 0) {                   // enable by setting plock
2217 +            if (!enable)
2218 +                return false;
2219 +            if ((ps & PL_LOCK) != 0 ||
2220 +                !U.compareAndSwapInt(this, PLOCK, ps, ps += PL_LOCK))
2221 +                ps = acquirePlock();
2222 +            int nps = ((ps + PL_LOCK) & ~SHUTDOWN) | SHUTDOWN;
2223 +            if (!U.compareAndSwapInt(this, PLOCK, ps, nps))
2224 +                releasePlock(nps);
2225 +        }
2226          for (long c;;) {
2227 <            if (((c = ctl) & STOP_BIT) != 0) {      // already terminating
2228 <                if ((short)(c >>> TC_SHIFT) == -parallelism) {
2227 >            if (((c = ctl) & STOP_BIT) != 0) {     // already terminating
2228 >                if ((short)(c >>> TC_SHIFT) + parallelism <= 0) {
2229                      synchronized (this) {
2230 <                        notifyAll();                // signal when 0 workers
2230 >                        notifyAll();               // signal when 0 workers
2231                      }
2232                  }
2233                  return true;
2234              }
2235 <            if (plock >= 0) {                       // not yet enabled
2236 <                int ps;
2237 <                if (!enable)
2180 <                    return false;
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 ||
2190 <                    hasQueuedSubmissions())
2235 >            if (!now) {                            // check if idle & no tasks
2236 >                WorkQueue[] ws; WorkQueue w;
2237 >                if ((int)(c >> AC_SHIFT) + parallelism > 0)
2238                      return false;
2239 <                // Check for unqueued inactive workers. One pass suffices.
2240 <                WorkQueue[] ws = workQueues; WorkQueue w;
2241 <                if (ws != null) {
2242 <                    for (int i = 1; i < ws.length; i += 2) {
2243 <                        if ((w = ws[i]) != null && w.eventCount >= 0)
2239 >                if ((ws = workQueues) != null) {
2240 >                    for (int i = 0; i < ws.length; ++i) {
2241 >                        if ((w = ws[i]) != null &&
2242 >                            (!w.isEmpty() ||
2243 >                             ((i & 1) != 0 && w.eventCount >= 0))) {
2244 >                            signalWork(ws, w);
2245                              return false;
2246 +                        }
2247                      }
2248                  }
2249              }
2250              if (U.compareAndSwapLong(this, CTL, c, c | STOP_BIT)) {
2251                  for (int pass = 0; pass < 3; ++pass) {
2252 <                    WorkQueue[] ws = workQueues;
2253 <                    if (ws != null) {
2205 <                        WorkQueue w;
2252 >                    WorkQueue[] ws; WorkQueue w; Thread wt;
2253 >                    if ((ws = workQueues) != null) {
2254                          int n = ws.length;
2255                          for (int i = 0; i < n; ++i) {
2256                              if ((w = ws[i]) != null) {
2257                                  w.qlock = -1;
2258                                  if (pass > 0) {
2259                                      w.cancelAll();
2260 <                                    if (pass > 1)
2261 <                                        w.interruptOwner();
2260 >                                    if (pass > 1 && (wt = w.owner) != null) {
2261 >                                        if (!wt.isInterrupted()) {
2262 >                                            try {
2263 >                                                wt.interrupt();
2264 >                                            } catch (Throwable ignore) {
2265 >                                            }
2266 >                                        }
2267 >                                        U.unpark(wt);
2268 >                                    }
2269                                  }
2270                              }
2271                          }
2272                          // Wake up workers parked on event queue
2273                          int i, e; long cc; Thread p;
2274                          while ((e = (int)(cc = ctl) & E_MASK) != 0 &&
2275 <                               (i = e & SMASK) < n &&
2275 >                               (i = e & SMASK) < n && i >= 0 &&
2276                                 (w = ws[i]) != null) {
2277                              long nc = ((long)(w.nextWait & E_MASK) |
2278                                         ((cc + AC_UNIT) & AC_MASK) |
# Line 2243 | Line 2298 | public class ForkJoinPool extends Abstra
2298       * least one task.
2299       */
2300      static WorkQueue commonSubmitterQueue() {
2301 <        ForkJoinPool p; WorkQueue[] ws; int m; Submitter z;
2301 >        Submitter z; ForkJoinPool p; WorkQueue[] ws; int m, r;
2302          return ((z = submitters.get()) != null &&
2303 <                (p = commonPool) != null &&
2303 >                (p = common) != null &&
2304                  (ws = p.workQueues) != null &&
2305                  (m = ws.length - 1) >= 0) ?
2306              ws[m & z.seed & SQMASK] : null;
# Line 2254 | Line 2309 | public class ForkJoinPool extends Abstra
2309      /**
2310       * Tries to pop the given task from submitter's queue in common pool.
2311       */
2312 <    static boolean tryExternalUnpush(ForkJoinTask<?> t) {
2313 <        ForkJoinPool p; WorkQueue[] ws; WorkQueue q; Submitter z;
2314 <        ForkJoinTask<?>[] a;  int m, s; long j;
2315 <        if ((z = submitters.get()) != null &&
2316 <            (p = commonPool) != null &&
2317 <            (ws = p.workQueues) != null &&
2318 <            (m = ws.length - 1) >= 0 &&
2319 <            (q = ws[m & z.seed & SQMASK]) != null &&
2320 <            (s = q.top) != q.base &&
2321 <            (a = q.array) != null &&
2322 <            U.getObjectVolatile
2323 <            (a, j = (((a.length - 1) & (s - 1)) << ASHIFT) + ABASE) == t &&
2324 <            U.compareAndSwapInt(q, QLOCK, 0, 1)) {
2325 <            if (q.array == a && q.top == s && // recheck
2326 <                U.compareAndSwapObject(a, j, t, null)) {
2327 <                q.top = s - 1;
2328 <                q.qlock = 0;
2329 <                return true;
2330 <            }
2331 <            q.qlock = 0;
2332 <        }
2333 <        return false;
2334 <    }
2335 <
2336 <    /**
2337 <     * Tries to pop and run local tasks within the same computation
2338 <     * as the given root. On failure, tries to help complete from
2339 <     * other queues via helpComplete.
2340 <     */
2341 <    private void externalHelpComplete(WorkQueue q, ForkJoinTask<?> root) {
2342 <        ForkJoinTask<?>[] a; int m;
2343 <        if (q != null && (a = q.array) != null && (m = (a.length - 1)) >= 0 &&
2344 <            root != null && root.status >= 0) {
2345 <            for (;;) {
2346 <                int s; Object o; CountedCompleter<?> task = null;
2347 <                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)
2312 >    final boolean tryExternalUnpush(ForkJoinTask<?> task) {
2313 >        WorkQueue joiner; ForkJoinTask<?>[] a; int m, s;
2314 >        Submitter z = submitters.get();
2315 >        WorkQueue[] ws = workQueues;
2316 >        boolean popped = false;
2317 >        if (z != null && ws != null && (m = ws.length - 1) >= 0 &&
2318 >            (joiner = ws[z.seed & m & SQMASK]) != null &&
2319 >            joiner.base != (s = joiner.top) &&
2320 >            (a = joiner.array) != null) {
2321 >            long j = (((a.length - 1) & (s - 1)) << ASHIFT) + ABASE;
2322 >            if (U.getObject(a, j) == task &&
2323 >                U.compareAndSwapInt(joiner, QLOCK, 0, 1)) {
2324 >                if (joiner.top == s && joiner.array == a &&
2325 >                    U.compareAndSwapObject(a, j, task, null)) {
2326 >                    joiner.top = s - 1;
2327 >                    popped = true;
2328 >                }
2329 >                joiner.qlock = 0;
2330 >            }
2331 >        }
2332 >        return popped;
2333 >    }
2334 >
2335 >    final int externalHelpComplete(CountedCompleter<?> task) {
2336 >        WorkQueue joiner; int m, j;
2337 >        Submitter z = submitters.get();
2338 >        WorkQueue[] ws = workQueues;
2339 >        int s = 0;
2340 >        if (z != null && ws != null && (m = ws.length - 1) >= 0 &&
2341 >            (joiner = ws[(j = z.seed) & m & SQMASK]) != null && task != null) {
2342 >            int scans = m + m + 1;
2343 >            long c = 0L;             // for stability check
2344 >            j |= 1;                  // poll odd queues
2345 >            for (int k = scans; ; j += 2) {
2346 >                WorkQueue q;
2347 >                if ((s = task.status) < 0)
2348                      break;
2349 <                if (task == null) {
2350 <                    if (helpSignal(root, q.poolIndex) >= 0)
2351 <                        helpComplete(root, SHARED_QUEUE);
2349 >                else if (joiner.externalPopAndExecCC(task))
2350 >                    k = scans;
2351 >                else if ((s = task.status) < 0)
2352                      break;
2353 +                else if ((q = ws[j & m]) != null && q.pollAndExecCC(task))
2354 +                    k = scans;
2355 +                else if (--k < 0) {
2356 +                    if (c == (c = ctl))
2357 +                        break;
2358 +                    k = scans;
2359                  }
2360              }
2361          }
2362 <    }
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();
2362 >        return s;
2363      }
2364  
2365      // Exported methods
# Line 2388 | Line 2378 | public class ForkJoinPool extends Abstra
2378       *         java.lang.RuntimePermission}{@code ("modifyThread")}
2379       */
2380      public ForkJoinPool() {
2381 <        this(Runtime.getRuntime().availableProcessors(),
2381 >        this(Math.min(MAX_CAP, Runtime.getRuntime().availableProcessors()),
2382               defaultForkJoinWorkerThreadFactory, null, false);
2383      }
2384  
# Line 2436 | Line 2426 | public class ForkJoinPool extends Abstra
2426       */
2427      public ForkJoinPool(int parallelism,
2428                          ForkJoinWorkerThreadFactory factory,
2429 <                        Thread.UncaughtExceptionHandler handler,
2429 >                        UncaughtExceptionHandler handler,
2430                          boolean asyncMode) {
2431 +        this(checkParallelism(parallelism),
2432 +             checkFactory(factory),
2433 +             handler,
2434 +             (asyncMode ? FIFO_QUEUE : LIFO_QUEUE),
2435 +             "ForkJoinPool-" + nextPoolId() + "-worker-");
2436          checkPermission();
2437 <        if (factory == null)
2438 <            throw new NullPointerException();
2437 >    }
2438 >
2439 >    private static int checkParallelism(int parallelism) {
2440          if (parallelism <= 0 || parallelism > MAX_CAP)
2441              throw new IllegalArgumentException();
2442 <        this.parallelism = parallelism;
2443 <        this.factory = factory;
2444 <        this.ueh = handler;
2445 <        this.localMode = asyncMode ? FIFO_QUEUE : LIFO_QUEUE;
2446 <        long np = (long)(-parallelism); // offset ctl counts
2447 <        this.ctl = ((np << AC_SHIFT) & AC_MASK) | ((np << TC_SHIFT) & TC_MASK);
2448 <        int pn = nextPoolId();
2449 <        StringBuilder sb = new StringBuilder("ForkJoinPool-");
2454 <        sb.append(Integer.toString(pn));
2455 <        sb.append("-worker-");
2456 <        this.workerNamePrefix = sb.toString();
2442 >        return parallelism;
2443 >    }
2444 >
2445 >    private static ForkJoinWorkerThreadFactory checkFactory
2446 >        (ForkJoinWorkerThreadFactory factory) {
2447 >        if (factory == null)
2448 >            throw new NullPointerException();
2449 >        return factory;
2450      }
2451  
2452      /**
2453 <     * Constructor for common pool, suitable only for static initialization.
2454 <     * Basically the same as above, but uses smallest possible initial footprint.
2455 <     */
2456 <    ForkJoinPool(int parallelism, long ctl,
2457 <                 ForkJoinWorkerThreadFactory factory,
2458 <                 Thread.UncaughtExceptionHandler handler) {
2459 <        this.parallelism = parallelism;
2460 <        this.ctl = ctl;
2453 >     * Creates a {@code ForkJoinPool} with the given parameters, without
2454 >     * any security checks or parameter validation.  Invoked directly by
2455 >     * makeCommonPool.
2456 >     */
2457 >    private ForkJoinPool(int parallelism,
2458 >                         ForkJoinWorkerThreadFactory factory,
2459 >                         UncaughtExceptionHandler handler,
2460 >                         int mode,
2461 >                         String workerNamePrefix) {
2462 >        this.workerNamePrefix = workerNamePrefix;
2463          this.factory = factory;
2464          this.ueh = handler;
2465 <        this.localMode = LIFO_QUEUE;
2466 <        this.workerNamePrefix = "ForkJoinPool.commonPool-worker-";
2465 >        this.mode = (short)mode;
2466 >        this.parallelism = (short)parallelism;
2467 >        long np = (long)(-parallelism); // offset ctl counts
2468 >        this.ctl = ((np << AC_SHIFT) & AC_MASK) | ((np << TC_SHIFT) & TC_MASK);
2469      }
2470  
2471      /**
2472 <     * Returns the common pool instance.
2472 >     * Returns the common pool instance. This pool is statically
2473 >     * constructed; its run state is unaffected by attempts to {@link
2474 >     * #shutdown} or {@link #shutdownNow}. However this pool and any
2475 >     * ongoing processing are automatically terminated upon program
2476 >     * {@link System#exit}.  Any program that relies on asynchronous
2477 >     * task processing to complete before program termination should
2478 >     * invoke {@code commonPool().}{@link #awaitQuiescence awaitQuiescence},
2479 >     * before exit.
2480       *
2481       * @return the common pool instance
2482 +     * @since 1.8
2483       */
2484      public static ForkJoinPool commonPool() {
2485 <        return commonPool; // cannot be null (if so, a static init error)
2485 >        // assert common != null : "static init error";
2486 >        return common;
2487      }
2488  
2489      // Execution methods
# Line 2493 | Line 2499 | public class ForkJoinPool extends Abstra
2499       * minimally only the latter.
2500       *
2501       * @param task the task
2502 +     * @param <T> the type of the task's result
2503       * @return the task's result
2504       * @throws NullPointerException if the task is null
2505       * @throws RejectedExecutionException if the task cannot be
# Line 2533 | Line 2540 | public class ForkJoinPool extends Abstra
2540          if (task instanceof ForkJoinTask<?>) // avoid re-wrap
2541              job = (ForkJoinTask<?>) task;
2542          else
2543 <            job = new ForkJoinTask.AdaptedRunnableAction(task);
2543 >            job = new ForkJoinTask.RunnableExecuteAction(task);
2544          externalPush(job);
2545      }
2546  
# Line 2541 | Line 2548 | public class ForkJoinPool extends Abstra
2548       * Submits a ForkJoinTask for execution.
2549       *
2550       * @param task the task to submit
2551 +     * @param <T> the type of the task's result
2552       * @return the task
2553       * @throws NullPointerException if the task is null
2554       * @throws RejectedExecutionException if the task cannot be
# Line 2600 | Line 2608 | public class ForkJoinPool extends Abstra
2608          // In previous versions of this class, this method constructed
2609          // a task to run ForkJoinTask.invokeAll, but now external
2610          // invocation of multiple tasks is at least as efficient.
2611 <        List<ForkJoinTask<T>> fs = new ArrayList<ForkJoinTask<T>>(tasks.size());
2604 <        // Workaround needed because method wasn't declared with
2605 <        // wildcards in return type but should have been.
2606 <        @SuppressWarnings({"unchecked", "rawtypes"})
2607 <            List<Future<T>> futures = (List<Future<T>>) (List) fs;
2611 >        ArrayList<Future<T>> futures = new ArrayList<Future<T>>(tasks.size());
2612  
2613          boolean done = false;
2614          try {
2615              for (Callable<T> t : tasks) {
2616                  ForkJoinTask<T> f = new ForkJoinTask.AdaptedCallable<T>(t);
2617 +                futures.add(f);
2618                  externalPush(f);
2614                fs.add(f);
2619              }
2620 <            for (ForkJoinTask<T> f : fs)
2621 <                f.quietlyJoin();
2620 >            for (int i = 0, size = futures.size(); i < size; i++)
2621 >                ((ForkJoinTask<?>)futures.get(i)).quietlyJoin();
2622              done = true;
2623              return futures;
2624          } finally {
2625              if (!done)
2626 <                for (ForkJoinTask<T> f : fs)
2627 <                    f.cancel(false);
2626 >                for (int i = 0, size = futures.size(); i < size; i++)
2627 >                    futures.get(i).cancel(false);
2628          }
2629      }
2630  
# Line 2639 | Line 2643 | public class ForkJoinPool extends Abstra
2643       *
2644       * @return the handler, or {@code null} if none
2645       */
2646 <    public Thread.UncaughtExceptionHandler getUncaughtExceptionHandler() {
2646 >    public UncaughtExceptionHandler getUncaughtExceptionHandler() {
2647          return ueh;
2648      }
2649  
# Line 2649 | Line 2653 | public class ForkJoinPool extends Abstra
2653       * @return the targeted parallelism level of this pool
2654       */
2655      public int getParallelism() {
2656 <        return parallelism;
2656 >        int par;
2657 >        return ((par = parallelism) > 0) ? par : 1;
2658      }
2659  
2660      /**
2661       * Returns the targeted parallelism level of the common pool.
2662       *
2663       * @return the targeted parallelism level of the common pool
2664 +     * @since 1.8
2665       */
2666      public static int getCommonPoolParallelism() {
2667 <        return commonPoolParallelism;
2667 >        return commonParallelism;
2668      }
2669  
2670      /**
# Line 2680 | Line 2686 | public class ForkJoinPool extends Abstra
2686       * @return {@code true} if this pool uses async mode
2687       */
2688      public boolean getAsyncMode() {
2689 <        return localMode != 0;
2689 >        return mode == FIFO_QUEUE;
2690      }
2691  
2692      /**
# Line 2727 | Line 2733 | public class ForkJoinPool extends Abstra
2733       * @return {@code true} if all threads are currently idle
2734       */
2735      public boolean isQuiescent() {
2736 <        return (int)(ctl >> AC_SHIFT) + parallelism == 0;
2736 >        return parallelism + (int)(ctl >> AC_SHIFT) <= 0;
2737      }
2738  
2739      /**
# Line 2804 | Line 2810 | public class ForkJoinPool extends Abstra
2810          WorkQueue[] ws; WorkQueue w;
2811          if ((ws = workQueues) != null) {
2812              for (int i = 0; i < ws.length; i += 2) {
2813 <                if ((w = ws[i]) != null && w.queueSize() != 0)
2813 >                if ((w = ws[i]) != null && !w.isEmpty())
2814                      return true;
2815              }
2816          }
# Line 2916 | Line 2922 | public class ForkJoinPool extends Abstra
2922       * Possibly initiates an orderly shutdown in which previously
2923       * submitted tasks are executed, but no new tasks will be
2924       * accepted. Invocation has no effect on execution state if this
2925 <     * is the {@link #commonPool}, and no additional effect if
2925 >     * is the {@link #commonPool()}, and no additional effect if
2926       * already shut down.  Tasks that are in the process of being
2927       * submitted concurrently during the course of this method may or
2928       * may not be rejected.
# Line 2934 | Line 2940 | public class ForkJoinPool extends Abstra
2940      /**
2941       * Possibly attempts to cancel and/or stop all tasks, and reject
2942       * all subsequently submitted tasks.  Invocation has no effect on
2943 <     * execution state if this is the {@link #commonPool}, and no
2943 >     * execution state if this is the {@link #commonPool()}, and no
2944       * additional effect if already shut down. Otherwise, tasks that
2945       * are in the process of being submitted or executed concurrently
2946       * during the course of this method may or may not be
# Line 2963 | Line 2969 | public class ForkJoinPool extends Abstra
2969      public boolean isTerminated() {
2970          long c = ctl;
2971          return ((c & STOP_BIT) != 0L &&
2972 <                (short)(c >>> TC_SHIFT) == -parallelism);
2972 >                (short)(c >>> TC_SHIFT) + parallelism <= 0);
2973      }
2974  
2975      /**
# Line 2971 | Line 2977 | public class ForkJoinPool extends Abstra
2977       * commenced but not yet completed.  This method may be useful for
2978       * debugging. A return of {@code true} reported a sufficient
2979       * period after shutdown may indicate that submitted tasks have
2980 <     * ignored or suppressed interruption, or are waiting for IO,
2980 >     * ignored or suppressed interruption, or are waiting for I/O,
2981       * causing this executor not to properly terminate. (See the
2982       * advisory notes for class {@link ForkJoinTask} stating that
2983       * tasks should not normally entail blocking operations.  But if
# Line 2982 | Line 2988 | public class ForkJoinPool extends Abstra
2988      public boolean isTerminating() {
2989          long c = ctl;
2990          return ((c & STOP_BIT) != 0L &&
2991 <                (short)(c >>> TC_SHIFT) != -parallelism);
2991 >                (short)(c >>> TC_SHIFT) + parallelism > 0);
2992      }
2993  
2994      /**
# Line 2997 | Line 3003 | public class ForkJoinPool extends Abstra
3003      /**
3004       * Blocks until all tasks have completed execution after a
3005       * shutdown request, or the timeout occurs, or the current thread
3006 <     * is interrupted, whichever happens first. Note that the {@link
3007 <     * #commonPool()} never terminates until program shutdown so
3008 <     * this method will always time out.
3006 >     * is interrupted, whichever happens first. Because the {@link
3007 >     * #commonPool()} never terminates until program shutdown, when
3008 >     * applied to the common pool, this method is equivalent to {@link
3009 >     * #awaitQuiescence(long, TimeUnit)} but always returns {@code false}.
3010       *
3011       * @param timeout the maximum time to wait
3012       * @param unit the time unit of the timeout argument
# Line 3009 | Line 3016 | public class ForkJoinPool extends Abstra
3016       */
3017      public boolean awaitTermination(long timeout, TimeUnit unit)
3018          throws InterruptedException {
3019 +        if (Thread.interrupted())
3020 +            throw new InterruptedException();
3021 +        if (this == common) {
3022 +            awaitQuiescence(timeout, unit);
3023 +            return false;
3024 +        }
3025          long nanos = unit.toNanos(timeout);
3026          if (isTerminated())
3027              return true;
3028 <        long startTime = System.nanoTime();
3029 <        boolean terminated = false;
3028 >        if (nanos <= 0L)
3029 >            return false;
3030 >        long deadline = System.nanoTime() + nanos;
3031          synchronized (this) {
3032 <            for (long waitTime = nanos, millis = 0L;;) {
3033 <                if (terminated = isTerminated() ||
3034 <                    waitTime <= 0L ||
3035 <                    (millis = unit.toMillis(waitTime)) <= 0L)
3032 >            for (;;) {
3033 >                if (isTerminated())
3034 >                    return true;
3035 >                if (nanos <= 0L)
3036 >                    return false;
3037 >                long millis = TimeUnit.NANOSECONDS.toMillis(nanos);
3038 >                wait(millis > 0L ? millis : 1L);
3039 >                nanos = deadline - System.nanoTime();
3040 >            }
3041 >        }
3042 >    }
3043 >
3044 >    /**
3045 >     * If called by a ForkJoinTask operating in this pool, equivalent
3046 >     * in effect to {@link ForkJoinTask#helpQuiesce}. Otherwise,
3047 >     * waits and/or attempts to assist performing tasks until this
3048 >     * pool {@link #isQuiescent} or the indicated timeout elapses.
3049 >     *
3050 >     * @param timeout the maximum time to wait
3051 >     * @param unit the time unit of the timeout argument
3052 >     * @return {@code true} if quiescent; {@code false} if the
3053 >     * timeout elapsed.
3054 >     */
3055 >    public boolean awaitQuiescence(long timeout, TimeUnit unit) {
3056 >        long nanos = unit.toNanos(timeout);
3057 >        ForkJoinWorkerThread wt;
3058 >        Thread thread = Thread.currentThread();
3059 >        if ((thread instanceof ForkJoinWorkerThread) &&
3060 >            (wt = (ForkJoinWorkerThread)thread).pool == this) {
3061 >            helpQuiescePool(wt.workQueue);
3062 >            return true;
3063 >        }
3064 >        long startTime = System.nanoTime();
3065 >        WorkQueue[] ws;
3066 >        int r = 0, m;
3067 >        boolean found = true;
3068 >        while (!isQuiescent() && (ws = workQueues) != null &&
3069 >               (m = ws.length - 1) >= 0) {
3070 >            if (!found) {
3071 >                if ((System.nanoTime() - startTime) > nanos)
3072 >                    return false;
3073 >                Thread.yield(); // cannot block
3074 >            }
3075 >            found = false;
3076 >            for (int j = (m + 1) << 2; j >= 0; --j) {
3077 >                ForkJoinTask<?> t; WorkQueue q; int b;
3078 >                if ((q = ws[r++ & m]) != null && (b = q.base) - q.top < 0) {
3079 >                    found = true;
3080 >                    if ((t = q.pollAt(b)) != null)
3081 >                        t.doExec();
3082                      break;
3083 <                wait(millis);
3024 <                waitTime = nanos - (System.nanoTime() - startTime);
3083 >                }
3084              }
3085          }
3086 <        return terminated;
3086 >        return true;
3087 >    }
3088 >
3089 >    /**
3090 >     * Waits and/or attempts to assist performing tasks indefinitely
3091 >     * until the {@link #commonPool()} {@link #isQuiescent}.
3092 >     */
3093 >    static void quiesceCommonPool() {
3094 >        common.awaitQuiescence(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
3095      }
3096  
3097      /**
# Line 3036 | Line 3103 | public class ForkJoinPool extends Abstra
3103       * not necessary. Method {@code block} blocks the current thread
3104       * if necessary (perhaps internally invoking {@code isReleasable}
3105       * before actually blocking). These actions are performed by any
3106 <     * thread invoking {@link ForkJoinPool#managedBlock}.  The
3107 <     * unusual methods in this API accommodate synchronizers that may,
3108 <     * but don't usually, block for long periods. Similarly, they
3106 >     * thread invoking {@link ForkJoinPool#managedBlock(ManagedBlocker)}.
3107 >     * The unusual methods in this API accommodate synchronizers that
3108 >     * may, but don't usually, block for long periods. Similarly, they
3109       * allow more efficient internal handling of cases in which
3110       * additional workers may be, but usually are not, needed to
3111       * ensure sufficient parallelism.  Toward this end,
# Line 3096 | Line 3163 | public class ForkJoinPool extends Abstra
3163  
3164          /**
3165           * Returns {@code true} if blocking is unnecessary.
3166 +         * @return {@code true} if blocking is unnecessary
3167           */
3168          boolean isReleasable();
3169      }
# Line 3125 | Line 3193 | public class ForkJoinPool extends Abstra
3193          Thread t = Thread.currentThread();
3194          if (t instanceof ForkJoinWorkerThread) {
3195              ForkJoinPool p = ((ForkJoinWorkerThread)t).pool;
3196 <            while (!blocker.isReleasable()) { // variant of helpSignal
3197 <                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()) {
3196 >            while (!blocker.isReleasable()) {
3197 >                if (p.tryCompensate(p.ctl)) {
3198                      try {
3199                          do {} while (!blocker.isReleasable() &&
3200                                       !blocker.block());
# Line 3176 | Line 3232 | public class ForkJoinPool extends Abstra
3232      private static final long STEALCOUNT;
3233      private static final long PLOCK;
3234      private static final long INDEXSEED;
3235 +    private static final long QBASE;
3236      private static final long QLOCK;
3237  
3238      static {
3239 <        // 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
3239 >        // initialize field offsets for CAS etc
3240          try {
3241              U = getUnsafe();
3242              Class<?> k = ForkJoinPool.class;
# Line 3216 | Line 3252 | public class ForkJoinPool extends Abstra
3252              PARKBLOCKER = U.objectFieldOffset
3253                  (tk.getDeclaredField("parkBlocker"));
3254              Class<?> wk = WorkQueue.class;
3255 +            QBASE = U.objectFieldOffset
3256 +                (wk.getDeclaredField("base"));
3257              QLOCK = U.objectFieldOffset
3258                  (wk.getDeclaredField("qlock"));
3259              Class<?> ak = ForkJoinTask[].class;
3260              ABASE = U.arrayBaseOffset(ak);
3261 <            s = U.arrayIndexScale(ak);
3262 <            ASHIFT = 31 - Integer.numberOfLeadingZeros(s);
3261 >            int scale = U.arrayIndexScale(ak);
3262 >            if ((scale & (scale - 1)) != 0)
3263 >                throw new Error("data type scale not a power of two");
3264 >            ASHIFT = 31 - Integer.numberOfLeadingZeros(scale);
3265          } catch (Exception e) {
3266              throw new Error(e);
3267          }
3228        if ((s & (s-1)) != 0)
3229            throw new Error("data type scale not a power of two");
3268  
3269 <        /*
3270 <         * 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 =
3269 >        submitters = new ThreadLocal<Submitter>();
3270 >        defaultForkJoinWorkerThreadFactory =
3271              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);
3272          modifyThreadPermission = new RuntimePermission("modifyThread");
3273 <        submitters = new ThreadLocal<Submitter>();
3273 >
3274 >        common = java.security.AccessController.doPrivileged
3275 >            (new java.security.PrivilegedAction<ForkJoinPool>() {
3276 >                public ForkJoinPool run() { return makeCommonPool(); }});
3277 >        int par = common.parallelism; // report 1 even if threads disabled
3278 >        commonParallelism = par > 0 ? par : 1;
3279 >    }
3280 >
3281 >    /**
3282 >     * Creates and returns the common pool, respecting user settings
3283 >     * specified via system properties.
3284 >     */
3285 >    private static ForkJoinPool makeCommonPool() {
3286 >        int parallelism = -1;
3287 >        ForkJoinWorkerThreadFactory factory
3288 >            = defaultForkJoinWorkerThreadFactory;
3289 >        UncaughtExceptionHandler handler = null;
3290 >        try {  // ignore exceptions in accessing/parsing properties
3291 >            String pp = System.getProperty
3292 >                ("java.util.concurrent.ForkJoinPool.common.parallelism");
3293 >            String fp = System.getProperty
3294 >                ("java.util.concurrent.ForkJoinPool.common.threadFactory");
3295 >            String hp = System.getProperty
3296 >                ("java.util.concurrent.ForkJoinPool.common.exceptionHandler");
3297 >            if (pp != null)
3298 >                parallelism = Integer.parseInt(pp);
3299 >            if (fp != null)
3300 >                factory = ((ForkJoinWorkerThreadFactory)ClassLoader.
3301 >                           getSystemClassLoader().loadClass(fp).newInstance());
3302 >            if (hp != null)
3303 >                handler = ((UncaughtExceptionHandler)ClassLoader.
3304 >                           getSystemClassLoader().loadClass(hp).newInstance());
3305 >        } catch (Exception ignore) {
3306 >        }
3307 >
3308 >        if (parallelism < 0 && // default 1 less than #cores
3309 >            (parallelism = Runtime.getRuntime().availableProcessors() - 1) < 0)
3310 >            parallelism = 0;
3311 >        if (parallelism > MAX_CAP)
3312 >            parallelism = MAX_CAP;
3313 >        return new ForkJoinPool(parallelism, factory, handler, LIFO_QUEUE,
3314 >                                "ForkJoinPool.commonPool-worker-");
3315      }
3316  
3317      /**
# Line 3260 | Line 3324 | public class ForkJoinPool extends Abstra
3324      private static sun.misc.Unsafe getUnsafe() {
3325          try {
3326              return sun.misc.Unsafe.getUnsafe();
3327 <        } catch (SecurityException se) {
3328 <            try {
3329 <                return java.security.AccessController.doPrivileged
3330 <                    (new java.security
3331 <                     .PrivilegedExceptionAction<sun.misc.Unsafe>() {
3332 <                        public sun.misc.Unsafe run() throws Exception {
3333 <                            java.lang.reflect.Field f = sun.misc
3334 <                                .Unsafe.class.getDeclaredField("theUnsafe");
3335 <                            f.setAccessible(true);
3336 <                            return (sun.misc.Unsafe) f.get(null);
3337 <                        }});
3338 <            } catch (java.security.PrivilegedActionException e) {
3339 <                throw new RuntimeException("Could not initialize intrinsics",
3340 <                                           e.getCause());
3341 <            }
3327 >        } catch (SecurityException tryReflectionInstead) {}
3328 >        try {
3329 >            return java.security.AccessController.doPrivileged
3330 >            (new java.security.PrivilegedExceptionAction<sun.misc.Unsafe>() {
3331 >                public sun.misc.Unsafe run() throws Exception {
3332 >                    Class<sun.misc.Unsafe> k = sun.misc.Unsafe.class;
3333 >                    for (java.lang.reflect.Field f : k.getDeclaredFields()) {
3334 >                        f.setAccessible(true);
3335 >                        Object x = f.get(null);
3336 >                        if (k.isInstance(x))
3337 >                            return k.cast(x);
3338 >                    }
3339 >                    throw new NoSuchFieldError("the Unsafe");
3340 >                }});
3341 >        } catch (java.security.PrivilegedActionException e) {
3342 >            throw new RuntimeException("Could not initialize intrinsics",
3343 >                                       e.getCause());
3344          }
3345      }
3280
3346   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines