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

Comparing jsr166/src/jsr166e/ForkJoinPool.java (file contents):
Revision 1.9 by dl, Tue Oct 30 14:23:03 2012 UTC vs.
Revision 1.60 by jsr166, Wed Jun 19 16:36:45 2013 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;
13   import java.util.Collections;
14   import java.util.List;
14 import java.util.Random;
15   import java.util.concurrent.AbstractExecutorService;
16   import java.util.concurrent.Callable;
17   import java.util.concurrent.ExecutorService;
# Line 20 | Line 20 | import java.util.concurrent.RejectedExec
20   import java.util.concurrent.RunnableFuture;
21   import java.util.concurrent.ThreadLocalRandom;
22   import java.util.concurrent.TimeUnit;
23 import java.util.concurrent.atomic.AtomicInteger;
24 import java.util.concurrent.atomic.AtomicLong;
25 import java.util.concurrent.locks.AbstractQueuedSynchronizer;
26 import java.util.concurrent.locks.Condition;
23  
24   /**
25   * An {@link ExecutorService} for running {@link ForkJoinTask}s.
# Line 43 | Line 39 | import java.util.concurrent.locks.Condit
39   * ForkJoinPool}s may also be appropriate for use with event-style
40   * tasks that are never joined.
41   *
42 < * <p>A static {@link #commonPool} is available and appropriate for
42 > * <p>A static {@link #commonPool()} is available and appropriate for
43   * most applications. The common pool is used by any ForkJoinTask that
44   * is not explicitly submitted to a specified pool. Using the common
45   * pool normally reduces resource usage (its threads are slowly
46   * reclaimed during periods of non-use, and reinstated upon subsequent
47 < * use).  The common pool is by default constructed with default
52 < * parameters, but these may be controlled by setting any or all of
53 < * the three properties {@code
54 < * java.util.concurrent.ForkJoinPool.common.{parallelism,
55 < * threadFactory, exceptionHandler}}.
47 > * use).
48   *
49   * <p>For applications that require separate or custom pools, a {@code
50   * ForkJoinPool} may be constructed with a given target parallelism
51   * level; by default, equal to the number of available processors. The
52   * pool attempts to maintain enough active (or available) threads by
53   * dynamically adding, suspending, or resuming internal worker
54 < * threads, even if some tasks are stalled waiting to join
55 < * others. However, no such adjustments are guaranteed in the face of
56 < * blocked IO or other unmanaged synchronization. The nested {@link
54 > * threads, even if some tasks are stalled waiting to join others.
55 > * However, no such adjustments are guaranteed in the face of blocked
56 > * I/O or other unmanaged synchronization. The nested {@link
57   * ManagedBlocker} interface enables extension of the kinds of
58   * synchronization accommodated.
59   *
# Line 72 | Line 64 | import java.util.concurrent.locks.Condit
64   * {@link #toString} returns indications of pool state in a
65   * convenient form for informal monitoring.
66   *
67 < * <p> As is the case with other ExecutorServices, there are three
67 > * <p>As is the case with other ExecutorServices, there are three
68   * main task execution methods summarized in the following table.
69   * These are designed to be used primarily by clients not already
70   * engaged in fork/join computations in the current pool.  The main
# Line 85 | Line 77 | import java.util.concurrent.locks.Condit
77   * there is little difference among choice of methods.
78   *
79   * <table BORDER CELLPADDING=3 CELLSPACING=1>
80 + * <caption>Summary of task execution methods</caption>
81   *  <tr>
82   *    <td></td>
83   *    <td ALIGN=CENTER> <b>Call from non-fork/join clients</b></td>
84   *    <td ALIGN=CENTER> <b>Call from within fork/join computations</b></td>
85   *  </tr>
86   *  <tr>
87 < *    <td> <b>Arrange async execution</td>
87 > *    <td> <b>Arrange async execution</b></td>
88   *    <td> {@link #execute(ForkJoinTask)}</td>
89   *    <td> {@link ForkJoinTask#fork}</td>
90   *  </tr>
91   *  <tr>
92 < *    <td> <b>Await and obtain result</td>
92 > *    <td> <b>Await and obtain result</b></td>
93   *    <td> {@link #invoke(ForkJoinTask)}</td>
94   *    <td> {@link ForkJoinTask#invoke}</td>
95   *  </tr>
96   *  <tr>
97 < *    <td> <b>Arrange exec and obtain Future</td>
97 > *    <td> <b>Arrange exec and obtain Future</b></td>
98   *    <td> {@link #submit(ForkJoinTask)}</td>
99   *    <td> {@link ForkJoinTask#fork} (ForkJoinTasks <em>are</em> Futures)</td>
100   *  </tr>
101   * </table>
102   *
103 + * <p>The common pool is by default constructed with default
104 + * parameters, but these may be controlled by setting three
105 + * {@linkplain System#getProperty system properties}:
106 + * <ul>
107 + * <li>{@code java.util.concurrent.ForkJoinPool.common.parallelism}
108 + * - the parallelism level, a non-negative integer
109 + * <li>{@code java.util.concurrent.ForkJoinPool.common.threadFactory}
110 + * - the class name of a {@link ForkJoinWorkerThreadFactory}
111 + * <li>{@code java.util.concurrent.ForkJoinPool.common.exceptionHandler}
112 + * - the class name of a {@link UncaughtExceptionHandler}
113 + * </ul>
114 + * The system class loader is used to load these classes.
115 + * Upon any error in establishing these settings, default parameters
116 + * are used. It is possible to disable or limit the use of threads in
117 + * the common pool by setting the parallelism property to zero, and/or
118 + * using a factory that may return {@code null}.
119 + *
120   * <p><b>Implementation notes</b>: This implementation restricts the
121   * maximum number of running threads to 32767. Attempts to create
122   * pools with greater than the maximum number result in
# Line 151 | Line 161 | public class ForkJoinPool extends Abstra
161       * (http://research.sun.com/scalable/pubs/index.html) and
162       * "Idempotent work stealing" by Michael, Saraswat, and Vechev,
163       * PPoPP 2009 (http://portal.acm.org/citation.cfm?id=1504186).
164 <     * The main differences ultimately stem from GC requirements that
165 <     * we null out taken slots as soon as we can, to maintain as small
166 <     * a footprint as possible even in programs generating huge
167 <     * numbers of tasks. To accomplish this, we shift the CAS
168 <     * arbitrating pop vs poll (steal) from being on the indices
169 <     * ("base" and "top") to the slots themselves.  So, both a
170 <     * successful pop and poll mainly entail a CAS of a slot from
171 <     * non-null to null.  Because we rely on CASes of references, we
172 <     * do not need tag bits on base or top.  They are simple ints as
173 <     * used in any circular array-based queue (see for example
174 <     * ArrayDeque).  Updates to the indices must still be ordered in a
175 <     * way that guarantees that top == base means the queue is empty,
176 <     * but otherwise may err on the side of possibly making the queue
177 <     * appear nonempty when a push, pop, or poll have not fully
178 <     * committed. Note that this means that the poll operation,
179 <     * considered individually, is not wait-free. One thief cannot
180 <     * successfully continue until another in-progress one (or, if
181 <     * previously empty, a push) completes.  However, in the
182 <     * aggregate, we ensure at least probabilistic non-blockingness.
183 <     * If an attempted steal fails, a thief always chooses a different
184 <     * random victim target to try next. So, in order for one thief to
185 <     * progress, it suffices for any in-progress poll or new push on
186 <     * any empty queue to complete. (This is why we normally use
187 <     * method pollAt and its variants that try once at the apparent
188 <     * base index, else consider alternative actions, rather than
189 <     * method poll.)
164 >     * See also "Correct and Efficient Work-Stealing for Weak Memory
165 >     * Models" by Le, Pop, Cohen, and Nardelli, PPoPP 2013
166 >     * (http://www.di.ens.fr/~zappa/readings/ppopp13.pdf) for an
167 >     * analysis of memory ordering (atomic, volatile etc) issues.  The
168 >     * main differences ultimately stem from GC requirements that we
169 >     * null out taken slots as soon as we can, to maintain as small a
170 >     * footprint as possible even in programs generating huge numbers
171 >     * of tasks. To accomplish this, we shift the CAS arbitrating pop
172 >     * vs poll (steal) from being on the indices ("base" and "top") to
173 >     * the slots themselves.  So, both a successful pop and poll
174 >     * mainly entail a CAS of a slot from non-null to null.  Because
175 >     * we rely on CASes of references, we do not need tag bits on base
176 >     * or top.  They are simple ints as used in any circular
177 >     * array-based queue (see for example ArrayDeque).  Updates to the
178 >     * indices must still be ordered in a way that guarantees that top
179 >     * == base means the queue is empty, but otherwise may err on the
180 >     * side of possibly making the queue appear nonempty when a push,
181 >     * pop, or poll have not fully committed. Note that this means
182 >     * that the poll operation, considered individually, is not
183 >     * wait-free. One thief cannot successfully continue until another
184 >     * in-progress one (or, if previously empty, a push) completes.
185 >     * However, in the aggregate, we ensure at least probabilistic
186 >     * non-blockingness.  If an attempted steal fails, a thief always
187 >     * chooses a different random victim target to try next. So, in
188 >     * order for one thief to progress, it suffices for any
189 >     * in-progress poll or new push on any empty queue to
190 >     * complete. (This is why we normally use method pollAt and its
191 >     * variants that try once at the apparent base index, else
192 >     * consider alternative actions, rather than method poll.)
193       *
194       * This approach also enables support of a user mode in which local
195       * task processing is in FIFO, not LIFO order, simply by using
# Line 193 | Line 206 | public class ForkJoinPool extends Abstra
206       * WorkQueues are also used in a similar way for tasks submitted
207       * to the pool. We cannot mix these tasks in the same queues used
208       * for work-stealing (this would contaminate lifo/fifo
209 <     * processing). Instead, we loosely associate submission queues
209 >     * processing). Instead, we randomly associate submission queues
210       * with submitting threads, using a form of hashing.  The
211 <     * ThreadLocal Submitter class contains a value initially used as
212 <     * a hash code for choosing existing queues, but may be randomly
213 <     * repositioned upon contention with other submitters.  In
214 <     * essence, submitters act like workers except that they never
215 <     * take tasks, and they are multiplexed on to a finite number of
216 <     * shared work queues. However, classes are set up so that future
217 <     * extensions could allow submitters to optionally help perform
218 <     * tasks as well. Insertion of tasks in shared mode requires a
219 <     * lock (mainly to protect in the case of resizing) but we use
220 <     * only a simple spinlock (using bits in field runState), because
221 <     * submitters encountering a busy queue move on to try or create
222 <     * other queues -- they block only when creating and registering
223 <     * new queues.
211 >     * Submitter probe value serves as a hash code for
212 >     * choosing existing queues, and may be randomly repositioned upon
213 >     * contention with other submitters.  In essence, submitters act
214 >     * like workers except that they are restricted to executing local
215 >     * tasks that they submitted (or in the case of CountedCompleters,
216 >     * others with the same root task).  However, because most
217 >     * shared/external queue operations are more expensive than
218 >     * internal, and because, at steady state, external submitters
219 >     * will compete for CPU with workers, ForkJoinTask.join and
220 >     * related methods disable them from repeatedly helping to process
221 >     * tasks if all workers are active.  Insertion of tasks in shared
222 >     * mode requires a lock (mainly to protect in the case of
223 >     * resizing) but we use only a simple spinlock (using bits in
224 >     * field qlock), because submitters encountering a busy queue move
225 >     * on to try or create other queues -- they block only when
226 >     * creating and registering new queues.
227       *
228       * Management
229       * ==========
# Line 229 | Line 245 | public class ForkJoinPool extends Abstra
245       * and their negations (used for thresholding) to fit into 16bit
246       * fields.
247       *
248 <     * Field "runState" contains 32 bits needed to register and
249 <     * deregister WorkQueues, as well as to enable shutdown. It is
250 <     * only modified under a lock (normally briefly held, but
251 <     * occasionally protecting allocations and resizings) but even
252 <     * when locked remains available to check consistency.
248 >     * Field "plock" is a form of sequence lock with a saturating
249 >     * shutdown bit (similarly for per-queue "qlocks"), mainly
250 >     * protecting updates to the workQueues array, as well as to
251 >     * enable shutdown.  When used as a lock, it is normally only very
252 >     * briefly held, so is nearly always available after at most a
253 >     * brief spin, but we use a monitor-based backup strategy to
254 >     * block when needed.
255       *
256       * Recording WorkQueues.  WorkQueues are recorded in the
257       * "workQueues" array that is created upon first use and expanded
# Line 242 | Line 260 | public class ForkJoinPool extends Abstra
260       * by a lock but the array is otherwise concurrently readable, and
261       * accessed directly.  To simplify index-based operations, the
262       * array size is always a power of two, and all readers must
263 <     * tolerate null slots. Shared (submission) queues are at even
264 <     * indices, worker queues at odd indices. Grouping them together
265 <     * in this way simplifies and speeds up task scanning.
263 >     * tolerate null slots. Worker queues are at odd indices. Shared
264 >     * (submission) queues are at even indices, up to a maximum of 64
265 >     * slots, to limit growth even if array needs to expand to add
266 >     * more workers. Grouping them together in this way simplifies and
267 >     * speeds up task scanning.
268       *
269       * All worker thread creation is on-demand, triggered by task
270       * submissions, replacement of terminated workers, and/or
# Line 289 | Line 309 | public class ForkJoinPool extends Abstra
309       * has not yet entered the wait queue. We solve this by requiring
310       * a full sweep of all workers (via repeated calls to method
311       * scan()) both before and after a newly waiting worker is added
312 <     * to the wait queue. During a rescan, the worker might release
313 <     * some other queued worker rather than itself, which has the same
314 <     * net effect. Because enqueued workers may actually be rescanning
315 <     * rather than waiting, we set and clear the "parker" field of
316 <     * WorkQueues to reduce unnecessary calls to unpark.  (This
317 <     * requires a secondary recheck to avoid missed signals.)  Note
318 <     * the unusual conventions about Thread.interrupts surrounding
319 <     * parking and other blocking: Because interrupts are used solely
320 <     * to alert threads to check termination, which is checked anyway
321 <     * upon blocking, we clear status (using Thread.interrupted)
322 <     * before any call to park, so that park does not immediately
303 <     * return due to status being set via some other unrelated call to
304 <     * interrupt in user code.
312 >     * to the wait queue.  Because enqueued workers may actually be
313 >     * rescanning rather than waiting, we set and clear the "parker"
314 >     * field of WorkQueues to reduce unnecessary calls to unpark.
315 >     * (This requires a secondary recheck to avoid missed signals.)
316 >     * Note the unusual conventions about Thread.interrupts
317 >     * surrounding parking and other blocking: Because interrupts are
318 >     * used solely to alert threads to check termination, which is
319 >     * checked anyway upon blocking, we clear status (using
320 >     * Thread.interrupted) before any call to park, so that park does
321 >     * not immediately return due to status being set via some other
322 >     * unrelated call to interrupt in user code.
323       *
324       * Signalling.  We create or wake up workers only when there
325       * appears to be at least one task they might be able to find and
326       * execute.  When a submission is added or another worker adds a
327 <     * task to a queue that previously had fewer than two tasks, they
328 <     * signal waiting workers (or trigger creation of new ones if
329 <     * fewer than the given parallelism level -- see signalWork).
330 <     * These primary signals are buttressed by signals during rescans;
331 <     * together these cover the signals needed in cases when more
332 <     * tasks are pushed but untaken, and improve performance compared
333 <     * to having one thread wake up all workers.
327 >     * task to a queue that has fewer than two tasks, they signal
328 >     * waiting workers (or trigger creation of new ones if fewer than
329 >     * the given parallelism level -- signalWork).  These primary
330 >     * signals are buttressed by others whenever other threads remove
331 >     * a task from a queue and notice that there are other tasks there
332 >     * as well.  So in general, pools will be over-signalled. On most
333 >     * platforms, signalling (unpark) overhead time is noticeably
334 >     * long, and the time between signalling a thread and it actually
335 >     * making progress can be very noticeably long, so it is worth
336 >     * offloading these delays from critical paths as much as
337 >     * possible. Additionally, workers spin-down gradually, by staying
338 >     * alive so long as they see the ctl state changing.  Similar
339 >     * stability-sensing techniques are also used before blocking in
340 >     * awaitJoin and helpComplete.
341       *
342       * Trimming workers. To release resources after periods of lack of
343       * use, a worker starting to wait when the pool is quiescent will
# Line 323 | Line 348 | public class ForkJoinPool extends Abstra
348       * periods of non-use.
349       *
350       * Shutdown and Termination. A call to shutdownNow atomically sets
351 <     * a runState bit and then (non-atomically) sets each worker's
352 <     * runState status, cancels all unprocessed tasks, and wakes up
351 >     * a plock bit and then (non-atomically) sets each worker's
352 >     * qlock status, cancels all unprocessed tasks, and wakes up
353       * all waiting workers.  Detecting whether termination should
354       * commence after a non-abrupt shutdown() call requires more work
355       * and bookkeeping. We need consensus about quiescence (i.e., that
# Line 352 | Line 377 | public class ForkJoinPool extends Abstra
377       *      method tryCompensate() may create or re-activate a spare
378       *      thread to compensate for blocked joiners until they unblock.
379       *
380 <     * A third form (implemented in tryRemoveAndExec and
381 <     * tryPollForAndExec) amounts to helping a hypothetical
382 <     * compensator: If we can readily tell that a possible action of a
383 <     * compensator is to steal and execute the task being joined, the
384 <     * joining thread can do so directly, without the need for a
385 <     * compensation thread (although at the expense of larger run-time
386 <     * stacks, but the tradeoff is typically worthwhile).
380 >     * A third form (implemented in tryRemoveAndExec) amounts to
381 >     * helping a hypothetical compensator: If we can readily tell that
382 >     * a possible action of a compensator is to steal and execute the
383 >     * task being joined, the joining thread can do so directly,
384 >     * without the need for a compensation thread (although at the
385 >     * expense of larger run-time stacks, but the tradeoff is
386 >     * typically worthwhile).
387       *
388       * The ManagedBlocker extension API can't use helping so relies
389       * only on compensation in method awaitBlocker.
# Line 380 | Line 405 | public class ForkJoinPool extends Abstra
405       * steals, rather than use per-task bookkeeping.  This sometimes
406       * requires a linear scan of workQueues array to locate stealers,
407       * but often doesn't because stealers leave hints (that may become
408 <     * stale/wrong) of where to locate them.  A stealHint is only a
409 <     * hint because a worker might have had multiple steals and the
410 <     * hint records only one of them (usually the most current).
411 <     * Hinting isolates cost to when it is needed, rather than adding
412 <     * to per-task overhead.  (2) It is "shallow", ignoring nesting
413 <     * and potentially cyclic mutual steals.  (3) It is intentionally
408 >     * stale/wrong) of where to locate them.  It is only a hint
409 >     * because a worker might have had multiple steals and the hint
410 >     * records only one of them (usually the most current).  Hinting
411 >     * isolates cost to when it is needed, rather than adding to
412 >     * per-task overhead.  (2) It is "shallow", ignoring nesting and
413 >     * potentially cyclic mutual steals.  (3) It is intentionally
414       * racy: field currentJoin is updated only while actively joining,
415       * which means that we miss links in the chain during long-lived
416       * tasks, GC stalls etc (which is OK since blocking in such cases
# Line 393 | Line 418 | public class ForkJoinPool extends Abstra
418       * to find work (see MAX_HELP) and fall back to suspending the
419       * worker and if necessary replacing it with another.
420       *
421 +     * Helping actions for CountedCompleters are much simpler: Method
422 +     * helpComplete can take and execute any task with the same root
423 +     * as the task being waited on. However, this still entails some
424 +     * traversal of completer chains, so is less efficient than using
425 +     * CountedCompleters without explicit joins.
426 +     *
427       * It is impossible to keep exactly the target parallelism number
428       * of threads running at any given time.  Determining the
429       * existence of conservatively safe helping targets, the
# Line 414 | Line 445 | public class ForkJoinPool extends Abstra
445       * intractable) game with an opponent that may choose the worst
446       * (for us) active thread to stall at any time.  We take several
447       * precautions to bound losses (and thus bound gains), mainly in
448 <     * methods tryCompensate and awaitJoin: (1) We only try
449 <     * compensation after attempting enough helping steps (measured
450 <     * via counting and timing) that we have already consumed the
451 <     * estimated cost of creating and activating a new thread.  (2) We
452 <     * allow up to 50% of threads to be blocked before initially
453 <     * adding any others, and unless completely saturated, check that
454 <     * some work is available for a new worker before adding. Also, we
455 <     * create up to only 50% more threads until entering a mode that
456 <     * only adds a thread if all others are possibly blocked.  All
457 <     * together, this means that we might be half as fast to react,
458 <     * and create half as many threads as possible in the ideal case,
459 <     * but present vastly fewer anomalies in all other cases compared
460 <     * to both more aggressive and more conservative alternatives.
461 <     *
462 <     * Style notes: There is a lot of representation-level coupling
463 <     * among classes ForkJoinPool, ForkJoinWorkerThread, and
464 <     * ForkJoinTask.  The fields of WorkQueue maintain data structures
465 <     * managed by ForkJoinPool, so are directly accessed.  There is
466 <     * little point trying to reduce this, since any associated future
467 <     * changes in representations will need to be accompanied by
468 <     * algorithmic changes anyway. Several methods intrinsically
469 <     * sprawl because they must accumulate sets of consistent reads of
470 <     * volatiles held in local variables.  Methods signalWork() and
471 <     * scan() are the main bottlenecks, so are especially heavily
448 >     * methods tryCompensate and awaitJoin.
449 >     *
450 >     * Common Pool
451 >     * ===========
452 >     *
453 >     * The static common pool always exists after static
454 >     * initialization.  Since it (or any other created pool) need
455 >     * never be used, we minimize initial construction overhead and
456 >     * footprint to the setup of about a dozen fields, with no nested
457 >     * allocation. Most bootstrapping occurs within method
458 >     * fullExternalPush during the first submission to the pool.
459 >     *
460 >     * When external threads submit to the common pool, they can
461 >     * perform subtask processing (see externalHelpJoin and related
462 >     * methods).  This caller-helps policy makes it sensible to set
463 >     * common pool parallelism level to one (or more) less than the
464 >     * total number of available cores, or even zero for pure
465 >     * caller-runs.  We do not need to record whether external
466 >     * submissions are to the common pool -- if not, externalHelpJoin
467 >     * returns quickly (at the most helping to signal some common pool
468 >     * workers). These submitters would otherwise be blocked waiting
469 >     * for completion, so the extra effort (with liberally sprinkled
470 >     * task status checks) in inapplicable cases amounts to an odd
471 >     * form of limited spin-wait before blocking in ForkJoinTask.join.
472 >     *
473 >     * Style notes
474 >     * ===========
475 >     *
476 >     * There is a lot of representation-level coupling among classes
477 >     * ForkJoinPool, ForkJoinWorkerThread, and ForkJoinTask.  The
478 >     * fields of WorkQueue maintain data structures managed by
479 >     * ForkJoinPool, so are directly accessed.  There is little point
480 >     * trying to reduce this, since any associated future changes in
481 >     * representations will need to be accompanied by algorithmic
482 >     * changes anyway. Several methods intrinsically sprawl because
483 >     * they must accumulate sets of consistent reads of volatiles held
484 >     * in local variables.  Methods signalWork() and scan() are the
485 >     * main bottlenecks, so are especially heavily
486       * micro-optimized/mangled.  There are lots of inline assignments
487       * (of form "while ((local = field) != 0)") which are usually the
488       * simplest way to ensure the required read orderings (which are
# Line 445 | Line 490 | public class ForkJoinPool extends Abstra
490       * declarations of these locals at the heads of methods or blocks.
491       * There are several occurrences of the unusual "do {} while
492       * (!cas...)"  which is the simplest way to force an update of a
493 <     * CAS'ed variable. There are also other coding oddities that help
493 >     * CAS'ed variable. There are also other coding oddities (including
494 >     * several unnecessary-looking hoisted null checks) that help
495       * some methods perform reasonably even when interpreted (not
496       * compiled).
497       *
# Line 486 | Line 532 | public class ForkJoinPool extends Abstra
532           *
533           * @param pool the pool this thread works in
534           * @throws NullPointerException if the pool is null
535 +         * @return the new worker thread
536           */
537          public ForkJoinWorkerThread newThread(ForkJoinPool pool);
538      }
# Line 494 | Line 541 | public class ForkJoinPool extends Abstra
541       * Default ForkJoinWorkerThreadFactory implementation; creates a
542       * new ForkJoinWorkerThread.
543       */
544 <    static class DefaultForkJoinWorkerThreadFactory
544 >    static final class DefaultForkJoinWorkerThreadFactory
545          implements ForkJoinWorkerThreadFactory {
546 <        public ForkJoinWorkerThread newThread(ForkJoinPool pool) {
546 >        public final ForkJoinWorkerThread newThread(ForkJoinPool pool) {
547              return new ForkJoinWorkerThread(pool);
548          }
549      }
# Line 508 | Line 555 | public class ForkJoinPool extends Abstra
555       * actually do anything beyond having a unique identity.
556       */
557      static final class EmptyTask extends ForkJoinTask<Void> {
558 +        private static final long serialVersionUID = -7721805057305804111L;
559          EmptyTask() { status = ForkJoinTask.NORMAL; } // force done
560          public final Void getRawResult() { return null; }
561          public final void setRawResult(Void x) {}
# Line 528 | Line 576 | public class ForkJoinPool extends Abstra
576       *
577       * Field "top" is the index (mod array.length) of the next queue
578       * slot to push to or pop from. It is written only by owner thread
579 <     * for push, or under lock for trySharedPush, and accessed by
580 <     * other threads only after reading (volatile) base.  Both top and
581 <     * base are allowed to wrap around on overflow, but (top - base)
582 <     * (or more commonly -(base - top) to force volatile read of base
583 <     * before top) still estimates size.
579 >     * for push, or under lock for external/shared push, and accessed
580 >     * by other threads only after reading (volatile) base.  Both top
581 >     * and base are allowed to wrap around on overflow, but (top -
582 >     * base) (or more commonly -(base - top) to force volatile read of
583 >     * base before top) still estimates size. The lock ("qlock") is
584 >     * forced to -1 on termination, causing all further lock attempts
585 >     * to fail. (Note: we don't need CAS for termination state because
586 >     * upon pool shutdown, all shared-queues will stop being used
587 >     * anyway.)  Nearly all lock bodies are set up so that exceptions
588 >     * within lock bodies are "impossible" (modulo JVM errors that
589 >     * would cause failure anyway.)
590       *
591       * The array slots are read and written using the emulation of
592       * volatiles/atomics provided by Unsafe. Insertions must in
593       * general use putOrderedObject as a form of releasing store to
594       * ensure that all writes to the task object are ordered before
595 <     * its publication in the queue. (Although we can avoid one case
596 <     * of this when locked in trySharedPush.) All removals entail a
597 <     * CAS to null.  The array is always a power of two. To ensure
598 <     * safety of Unsafe array operations, all accesses perform
545 <     * explicit null checks and implicit bounds checks via
546 <     * power-of-two masking.
595 >     * its publication in the queue.  All removals entail a CAS to
596 >     * null.  The array is always a power of two. To ensure safety of
597 >     * Unsafe array operations, all accesses perform explicit null
598 >     * checks and implicit bounds checks via power-of-two masking.
599       *
600       * In addition to basic queuing support, this class contains
601       * fields described elsewhere to control execution. It turns out
602 <     * to work better memory-layout-wise to include them in this
603 <     * class rather than a separate class.
602 >     * to work better memory-layout-wise to include them in this class
603 >     * rather than a separate class.
604       *
605       * Performance on most platforms is very sensitive to placement of
606       * instances of both WorkQueues and their arrays -- we absolutely
607       * do not want multiple WorkQueue instances or multiple queue
608       * arrays sharing cache lines. (It would be best for queue objects
609       * and their arrays to share, but there is nothing available to
610 <     * help arrange that).  Unfortunately, because they are recorded
611 <     * in a common array, WorkQueue instances are often moved to be
560 <     * adjacent by garbage collectors. To reduce impact, we use field
561 <     * padding that works OK on common platforms; this effectively
562 <     * trades off slightly slower average field access for the sake of
563 <     * avoiding really bad worst-case access. (Until better JVM
564 <     * support is in place, this padding is dependent on transient
565 <     * properties of JVM field layout rules.)  We also take care in
566 <     * allocating, sizing and resizing the array. Non-shared queue
567 <     * arrays are initialized (via method growArray) by workers before
568 <     * use. Others are allocated on first use.
610 >     * help arrange that). The @Contended annotation alerts JVMs to
611 >     * try to keep instances apart.
612       */
613      static final class WorkQueue {
614          /**
# Line 588 | Line 631 | public class ForkJoinPool extends Abstra
631           */
632          static final int MAXIMUM_QUEUE_CAPACITY = 1 << 26; // 64M
633  
634 <        volatile long totalSteals; // cumulative number of steals
635 <        int seed;                  // for random scanning; initialize nonzero
634 >        // Heuristic padding to ameliorate unfortunate memory placements
635 >        volatile long pad00, pad01, pad02, pad03, pad04, pad05, pad06;
636 >
637          volatile int eventCount;   // encoded inactivation count; < 0 if inactive
638          int nextWait;              // encoded record of next event waiter
639 <        int rescans;               // remaining scans until block
640 <        int nsteals;               // top-level task executions since last idle
641 <        final int mode;            // lifo, fifo, or shared
642 <        int poolIndex;             // index of this queue in pool (or 0)
643 <        int stealHint;             // index of most recent known stealer
600 <        volatile int runState;     // 1: locked, -1: terminate; else 0
639 >        int nsteals;               // number of steals
640 >        int hint;                  // steal index hint
641 >        short poolIndex;           // index of this queue in pool
642 >        final short mode;          // 0: lifo, > 0: fifo, < 0: shared
643 >        volatile int qlock;        // 1: locked, -1: terminate; else 0
644          volatile int base;         // index of next slot for poll
645          int top;                   // index of next slot for push
646          ForkJoinTask<?>[] array;   // the elements (initially unallocated)
# Line 606 | Line 649 | public class ForkJoinPool extends Abstra
649          volatile Thread parker;    // == owner during call to park; else null
650          volatile ForkJoinTask<?> currentJoin;  // task being joined in awaitJoin
651          ForkJoinTask<?> currentSteal; // current non-local task being executed
609        // Heuristic padding to ameliorate unfortunate memory placements
610        Object p00, p01, p02, p03, p04, p05, p06, p07;
611        Object p08, p09, p0a, p0b, p0c, p0d, p0e;
652  
653 <        WorkQueue(ForkJoinPool pool, ForkJoinWorkerThread owner, int mode) {
654 <            this.mode = mode;
653 >        volatile Object pad10, pad11, pad12, pad13, pad14, pad15, pad16, pad17;
654 >        volatile Object pad18, pad19, pad1a, pad1b, pad1c, pad1d;
655 >
656 >        WorkQueue(ForkJoinPool pool, ForkJoinWorkerThread owner, int mode,
657 >                  int seed) {
658              this.pool = pool;
659              this.owner = owner;
660 +            this.mode = (short)mode;
661 +            this.hint = seed; // store initial seed for runWorker
662              // Place indices in the center of array (that is not yet allocated)
663              base = top = INITIAL_QUEUE_CAPACITY >>> 1;
664          }
# Line 638 | Line 683 | public class ForkJoinPool extends Abstra
683                      (n == -1 &&
684                       ((a = array) == null ||
685                        (m = a.length - 1) < 0 ||
686 <                      U.getObjectVolatile
687 <                      (a, ((m & (s - 1)) << ASHIFT) + ABASE) == null)));
686 >                      U.getObject
687 >                      (a, (long)((m & (s - 1)) << ASHIFT) + ABASE) == null)));
688          }
689  
690          /**
691 <         * Pushes a task. Call only by owner in unshared queues.
691 >         * Pushes a task. Call only by owner in unshared queues.  (The
692 >         * shared-queue version is embedded in method externalPush.)
693           *
694           * @param task the task. Caller must ensure non-null.
695 <         * @throw RejectedExecutionException if array cannot be resized
695 >         * @throws RejectedExecutionException if array cannot be resized
696           */
697          final void push(ForkJoinTask<?> task) {
698              ForkJoinTask<?>[] a; ForkJoinPool p;
699 <            int s = top, m, n;
699 >            int s = top, n;
700              if ((a = array) != null) {    // ignore if queue removed
701 <                U.putOrderedObject
702 <                    (a, (((m = a.length - 1) & s) << ASHIFT) + ABASE, task);
703 <                if ((n = (top = s + 1) - base) <= 2) {
704 <                    if ((p = pool) != null)
659 <                        p.signalWork();
660 <                }
701 >                int m = a.length - 1;
702 >                U.putOrderedObject(a, ((m & s) << ASHIFT) + ABASE, task);
703 >                if ((n = (top = s + 1) - base) <= 2)
704 >                    (p = pool).signalWork(p.workQueues, this);
705                  else if (n >= m)
706 <                    growArray(true);
706 >                    growArray();
707              }
708          }
709  
710          /**
711 <         * Pushes a task if lock is free and array is either big
712 <         * enough or can be resized to be big enough.
713 <         *
670 <         * @param task the task. Caller must ensure non-null.
671 <         * @return true if submitted
711 >         * Initializes or doubles the capacity of array. Call either
712 >         * by owner or with lock held -- it is OK for base, but not
713 >         * top, to move while resizings are in progress.
714           */
715 <        final boolean trySharedPush(ForkJoinTask<?> task) {
716 <            boolean submitted = false;
717 <            if (runState == 0 && U.compareAndSwapInt(this, RUNSTATE, 0, 1)) {
718 <                ForkJoinTask<?>[] a = array;
719 <                int s = top;
720 <                try {
721 <                    if ((a != null && a.length > s + 1 - base) ||
722 <                        (a = growArray(false)) != null) { // must presize
723 <                        int j = (((a.length - 1) & s) << ASHIFT) + ABASE;
724 <                        U.putObject(a, (long)j, task);    // don't need "ordered"
725 <                        top = s + 1;
726 <                        submitted = true;
727 <                    }
728 <                } finally {
729 <                    runState = 0;                         // unlock
730 <                }
715 >        final ForkJoinTask<?>[] growArray() {
716 >            ForkJoinTask<?>[] oldA = array;
717 >            int size = oldA != null ? oldA.length << 1 : INITIAL_QUEUE_CAPACITY;
718 >            if (size > MAXIMUM_QUEUE_CAPACITY)
719 >                throw new RejectedExecutionException("Queue capacity exceeded");
720 >            int oldMask, t, b;
721 >            ForkJoinTask<?>[] a = array = new ForkJoinTask<?>[size];
722 >            if (oldA != null && (oldMask = oldA.length - 1) >= 0 &&
723 >                (t = top) - (b = base) > 0) {
724 >                int mask = size - 1;
725 >                do {
726 >                    ForkJoinTask<?> x;
727 >                    int oldj = ((b & oldMask) << ASHIFT) + ABASE;
728 >                    int j    = ((b &    mask) << ASHIFT) + ABASE;
729 >                    x = (ForkJoinTask<?>)U.getObjectVolatile(oldA, oldj);
730 >                    if (x != null &&
731 >                        U.compareAndSwapObject(oldA, oldj, x, null))
732 >                        U.putObjectVolatile(a, j, x);
733 >                } while (++b != t);
734              }
735 <            return submitted;
735 >            return a;
736          }
737  
738          /**
# Line 710 | Line 755 | public class ForkJoinPool extends Abstra
755              return null;
756          }
757  
713        final ForkJoinTask<?> sharedPop() {
714            ForkJoinTask<?> task = null;
715            if (runState == 0 && U.compareAndSwapInt(this, RUNSTATE, 0, 1)) {
716                try {
717                    ForkJoinTask<?>[] a; int m;
718                    if ((a = array) != null && (m = a.length - 1) >= 0) {
719                        for (int s; (s = top - 1) - base >= 0;) {
720                            long j = ((m & s) << ASHIFT) + ABASE;
721                            ForkJoinTask<?> t =
722                                (ForkJoinTask<?>)U.getObject(a, j);
723                            if (t == null)
724                                break;
725                            if (U.compareAndSwapObject(a, j, t, null)) {
726                                top = s;
727                                task = t;
728                                break;
729                            }
730                        }
731                    }
732                } finally {
733                    runState = 0;
734                }
735            }
736            return task;
737        }
738
739        /**
740         * Version of pop that takes top element only if it
741         * its root is the given CountedCompleter.
742         */
743        final ForkJoinTask<?> popCC(CountedCompleter<?> root) {
744            ForkJoinTask<?>[] a; int m;
745            if (root != null && (a = array) != null && (m = a.length - 1) >= 0) {
746                for (int s; (s = top - 1) - base >= 0;) {
747                    long j = ((m & s) << ASHIFT) + ABASE;
748                    ForkJoinTask<?> t =
749                        (ForkJoinTask<?>)U.getObject(a, j);
750                    if (t == null || !(t instanceof CountedCompleter) ||
751                        ((CountedCompleter<?>)t).getRoot() != root)
752                        break;
753                    if (U.compareAndSwapObject(a, j, t, null)) {
754                        top = s;
755                        return t;
756                    }
757                    if (root.status < 0)
758                        break;
759                }
760            }
761            return null;
762        }
763
764        /**
765         * Shared version of popCC
766         */
767        final ForkJoinTask<?> sharedPopCC(CountedCompleter<?> root) {
768            ForkJoinTask<?> task = null;
769            if (root != null &&
770                runState == 0 && U.compareAndSwapInt(this, RUNSTATE, 0, 1)) {
771                try {
772                    ForkJoinTask<?>[] a; int m;
773                    if ((a = array) != null && (m = a.length - 1) >= 0) {
774                        for (int s; (s = top - 1) - base >= 0;) {
775                            long j = ((m & s) << ASHIFT) + ABASE;
776                            ForkJoinTask<?> t =
777                                (ForkJoinTask<?>)U.getObject(a, j);
778                            if (t == null || !(t instanceof CountedCompleter) ||
779                                ((CountedCompleter<?>)t).getRoot() != root)
780                                break;
781                            if (U.compareAndSwapObject(a, j, t, null)) {
782                                top = s;
783                                task = t;
784                                break;
785                            }
786                            if (root.status < 0)
787                                break;
788                        }
789                    }
790                } finally {
791                    runState = 0;
792                }
793            }
794            return task;
795        }
796
758          /**
759           * Takes a task in FIFO order if b is base of queue and a task
760           * can be claimed without contention. Specialized versions
# Line 804 | Line 765 | public class ForkJoinPool extends Abstra
765              if ((a = array) != null) {
766                  int j = (((a.length - 1) & b) << ASHIFT) + ABASE;
767                  if ((t = (ForkJoinTask<?>)U.getObjectVolatile(a, j)) != null &&
768 <                    base == b &&
769 <                    U.compareAndSwapObject(a, j, t, null)) {
809 <                    base = b + 1;
768 >                    base == b && U.compareAndSwapObject(a, j, t, null)) {
769 >                    U.putOrderedInt(this, QBASE, b + 1);
770                      return t;
771                  }
772              }
# Line 822 | Line 782 | public class ForkJoinPool extends Abstra
782                  int j = (((a.length - 1) & b) << ASHIFT) + ABASE;
783                  t = (ForkJoinTask<?>)U.getObjectVolatile(a, j);
784                  if (t != null) {
785 <                    if (base == b &&
786 <                        U.compareAndSwapObject(a, j, t, null)) {
827 <                        base = b + 1;
785 >                    if (U.compareAndSwapObject(a, j, t, null)) {
786 >                        U.putOrderedInt(this, QBASE, b + 1);
787                          return t;
788                      }
789                  }
790                  else if (base == b) {
791                      if (b + 1 == top)
792                          break;
793 <                    Thread.yield(); // wait for lagging update
793 >                    Thread.yield(); // wait for lagging update (very rare)
794                  }
795              }
796              return null;
# Line 858 | Line 817 | public class ForkJoinPool extends Abstra
817  
818          /**
819           * Pops the given task only if it is at the current top.
820 +         * (A shared version is available only via FJP.tryExternalUnpush)
821           */
822          final boolean tryUnpush(ForkJoinTask<?> t) {
823              ForkJoinTask<?>[] a; int s;
# Line 871 | Line 831 | public class ForkJoinPool extends Abstra
831          }
832  
833          /**
874         * Version of tryUnpush for shared queues; called by non-FJ
875         * submitters after prechecking that task probably exists.
876         */
877        final boolean trySharedUnpush(ForkJoinTask<?> t) {
878            boolean success = false;
879            if (runState == 0 && U.compareAndSwapInt(this, RUNSTATE, 0, 1)) {
880                try {
881                    ForkJoinTask<?>[] a; int s;
882                    if ((a = array) != null && (s = top) != base &&
883                        U.compareAndSwapObject
884                        (a, (((a.length - 1) & --s) << ASHIFT) + ABASE, t, null)) {
885                        top = s;
886                        success = true;
887                    }
888                } finally {
889                    runState = 0;                         // unlock
890                }
891            }
892            return success;
893        }
894
895        /**
896         * Polls the given task only if it is at the current base.
897         */
898        final boolean pollFor(ForkJoinTask<?> task) {
899            ForkJoinTask<?>[] a; int b;
900            if ((b = base) - top < 0 && (a = array) != null) {
901                int j = (((a.length - 1) & b) << ASHIFT) + ABASE;
902                if (U.getObjectVolatile(a, j) == task && base == b &&
903                    U.compareAndSwapObject(a, j, task, null)) {
904                    base = b + 1;
905                    return true;
906                }
907            }
908            return false;
909        }
910
911        /**
912         * Initializes or doubles the capacity of array. Call either
913         * by owner or with lock held -- it is OK for base, but not
914         * top, to move while resizings are in progress.
915         *
916         * @param rejectOnFailure if true, throw exception if capacity
917         * exceeded (relayed ultimately to user); else return null.
918         */
919        final ForkJoinTask<?>[] growArray(boolean rejectOnFailure) {
920            ForkJoinTask<?>[] oldA = array;
921            int size = oldA != null ? oldA.length << 1 : INITIAL_QUEUE_CAPACITY;
922            if (size <= MAXIMUM_QUEUE_CAPACITY) {
923                int oldMask, t, b;
924                ForkJoinTask<?>[] a = array = new ForkJoinTask<?>[size];
925                if (oldA != null && (oldMask = oldA.length - 1) >= 0 &&
926                    (t = top) - (b = base) > 0) {
927                    int mask = size - 1;
928                    do {
929                        ForkJoinTask<?> x;
930                        int oldj = ((b & oldMask) << ASHIFT) + ABASE;
931                        int j    = ((b &    mask) << ASHIFT) + ABASE;
932                        x = (ForkJoinTask<?>)U.getObjectVolatile(oldA, oldj);
933                        if (x != null &&
934                            U.compareAndSwapObject(oldA, oldj, x, null))
935                            U.putObjectVolatile(a, j, x);
936                    } while (++b != t);
937                }
938                return a;
939            }
940            else if (!rejectOnFailure)
941                return null;
942            else
943                throw new RejectedExecutionException("Queue capacity exceeded");
944        }
945
946        /**
834           * Removes and cancels all known tasks, ignoring any exceptions.
835           */
836          final void cancelAll() {
# Line 953 | Line 840 | public class ForkJoinPool extends Abstra
840                  ForkJoinTask.cancelIgnoringExceptions(t);
841          }
842  
843 <        /**
957 <         * Computes next value for random probes.  Scans don't require
958 <         * a very high quality generator, but also not a crummy one.
959 <         * Marsaglia xor-shift is cheap and works well enough.  Note:
960 <         * This is manually inlined in its usages in ForkJoinPool to
961 <         * avoid writes inside busy scan loops.
962 <         */
963 <        final int nextSeed() {
964 <            int r = seed;
965 <            r ^= r << 13;
966 <            r ^= r >>> 17;
967 <            return seed = r ^= r << 5;
968 <        }
969 <
970 <        // Execution methods
971 <
972 <        /**
973 <         * Pops and runs tasks until empty.
974 <         */
975 <        private void popAndExecAll() {
976 <            // A bit faster than repeated pop calls
977 <            ForkJoinTask<?>[] a; int m, s; long j; ForkJoinTask<?> t;
978 <            while ((a = array) != null && (m = a.length - 1) >= 0 &&
979 <                   (s = top - 1) - base >= 0 &&
980 <                   (t = ((ForkJoinTask<?>)
981 <                         U.getObject(a, j = ((m & s) << ASHIFT) + ABASE)))
982 <                   != null) {
983 <                if (U.compareAndSwapObject(a, j, t, null)) {
984 <                    top = s;
985 <                    t.doExec();
986 <                }
987 <            }
988 <        }
843 >        // Specialized execution methods
844  
845          /**
846           * Polls and runs tasks until empty.
847           */
848 <        private void pollAndExecAll() {
848 >        final void pollAndExecAll() {
849              for (ForkJoinTask<?> t; (t = poll()) != null;)
850                  t.doExec();
851          }
852  
853          /**
854 <         * If present, removes from queue and executes the given task, or
855 <         * any other cancelled task. Returns (true) immediately on any CAS
854 >         * Executes a top-level task and any local tasks remaining
855 >         * after execution.
856 >         */
857 >        final void runTask(ForkJoinTask<?> task) {
858 >            if ((currentSteal = task) != null) {
859 >                task.doExec();
860 >                ForkJoinTask<?>[] a = array;
861 >                int md = mode;
862 >                ++nsteals;
863 >                currentSteal = null;
864 >                if (md != 0)
865 >                    pollAndExecAll();
866 >                else if (a != null) {
867 >                    int s, m = a.length - 1;
868 >                    while ((s = top - 1) - base >= 0) {
869 >                        long i = ((m & s) << ASHIFT) + ABASE;
870 >                        ForkJoinTask<?> t = (ForkJoinTask<?>)U.getObject(a, i);
871 >                        if (t == null)
872 >                            break;
873 >                        if (U.compareAndSwapObject(a, i, t, null)) {
874 >                            top = s;
875 >                            t.doExec();
876 >                        }
877 >                    }
878 >                }
879 >            }
880 >        }
881 >
882 >        /**
883 >         * If present, removes from queue and executes the given task,
884 >         * or any other cancelled task. Returns (true) on any CAS
885           * or consistency check failure so caller can retry.
886           *
887 <         * @return 0 if no progress can be made, else positive
1004 <         * (this unusual convention simplifies use with tryHelpStealer.)
887 >         * @return false if no progress can be made, else true
888           */
889 <        final int tryRemoveAndExec(ForkJoinTask<?> task) {
890 <            int stat = 1;
1008 <            boolean removed = false, empty = true;
889 >        final boolean tryRemoveAndExec(ForkJoinTask<?> task) {
890 >            boolean stat;
891              ForkJoinTask<?>[] a; int m, s, b, n;
892 <            if ((a = array) != null && (m = a.length - 1) >= 0 &&
892 >            if (task != null && (a = array) != null && (m = a.length - 1) >= 0 &&
893                  (n = (s = top) - (b = base)) > 0) {
894 +                boolean removed = false, empty = true;
895 +                stat = true;
896                  for (ForkJoinTask<?> t;;) {           // traverse from s to b
897 <                    int j = ((--s & m) << ASHIFT) + ABASE;
898 <                    t = (ForkJoinTask<?>)U.getObjectVolatile(a, j);
897 >                    long j = ((--s & m) << ASHIFT) + ABASE;
898 >                    t = (ForkJoinTask<?>)U.getObject(a, j);
899                      if (t == null)                    // inconsistent length
900                          break;
901                      else if (t == task) {
# Line 1035 | Line 919 | public class ForkJoinPool extends Abstra
919                      }
920                      if (--n == 0) {
921                          if (!empty && base == b)
922 <                            stat = 0;
922 >                            stat = false;
923                          break;
924                      }
925                  }
926 +                if (removed)
927 +                    task.doExec();
928              }
929 <            if (removed)
930 <                task.doExec();
929 >            else
930 >                stat = false;
931              return stat;
932          }
933  
934          /**
935 <         * Executes a top-level task and any local tasks remaining
936 <         * after execution.
935 >         * Tries to poll for and execute the given task or any other
936 >         * task in its CountedCompleter computation.
937           */
938 <        final void runTask(ForkJoinTask<?> t) {
939 <            if (t != null) {
940 <                currentSteal = t;
941 <                t.doExec();
942 <                if (top != base) {       // process remaining local tasks
943 <                    if (mode == 0)
944 <                        popAndExecAll();
945 <                    else
946 <                        pollAndExecAll();
938 >        final boolean pollAndExecCC(CountedCompleter<?> root) {
939 >            ForkJoinTask<?>[] a; int b; Object o; CountedCompleter<?> t, r;
940 >            if ((b = base) - top < 0 && (a = array) != null) {
941 >                long j = (((a.length - 1) & b) << ASHIFT) + ABASE;
942 >                if ((o = U.getObjectVolatile(a, j)) == null)
943 >                    return true; // retry
944 >                if (o instanceof CountedCompleter) {
945 >                    for (t = (CountedCompleter<?>)o, r = t;;) {
946 >                        if (r == root) {
947 >                            if (base == b &&
948 >                                U.compareAndSwapObject(a, j, t, null)) {
949 >                                U.putOrderedInt(this, QBASE, b + 1);
950 >                                t.doExec();
951 >                            }
952 >                            return true;
953 >                        }
954 >                        else if ((r = r.completer) == null)
955 >                            break; // not part of root computation
956 >                    }
957                  }
1062                ++nsteals;
1063                currentSteal = null;
958              }
959 +            return false;
960          }
961  
962          /**
963 <         * Executes a non-top-level (stolen) task.
963 >         * Tries to pop and execute the given task or any other task
964 >         * in its CountedCompleter computation.
965           */
966 <        final void runSubtask(ForkJoinTask<?> t) {
967 <            if (t != null) {
968 <                ForkJoinTask<?> ps = currentSteal;
969 <                currentSteal = t;
970 <                t.doExec();
971 <                currentSteal = ps;
966 >        final boolean externalPopAndExecCC(CountedCompleter<?> root) {
967 >            ForkJoinTask<?>[] a; int s; Object o; CountedCompleter<?> t, r;
968 >            if (base - (s = top) < 0 && (a = array) != null) {
969 >                long j = (((a.length - 1) & (s - 1)) << ASHIFT) + ABASE;
970 >                if ((o = U.getObject(a, j)) instanceof CountedCompleter) {
971 >                    for (t = (CountedCompleter<?>)o, r = t;;) {
972 >                        if (r == root) {
973 >                            if (U.compareAndSwapInt(this, QLOCK, 0, 1)) {
974 >                                if (top == s && array == a &&
975 >                                    U.compareAndSwapObject(a, j, t, null)) {
976 >                                    top = s - 1;
977 >                                    qlock = 0;
978 >                                    t.doExec();
979 >                                }
980 >                                else
981 >                                    qlock = 0;
982 >                            }
983 >                            return true;
984 >                        }
985 >                        else if ((r = r.completer) == null)
986 >                            break;
987 >                    }
988 >                }
989 >            }
990 >            return false;
991 >        }
992 >
993 >        /**
994 >         * Internal version
995 >         */
996 >        final boolean internalPopAndExecCC(CountedCompleter<?> root) {
997 >            ForkJoinTask<?>[] a; int s; Object o; CountedCompleter<?> t, r;
998 >            if (base - (s = top) < 0 && (a = array) != null) {
999 >                long j = (((a.length - 1) & (s - 1)) << ASHIFT) + ABASE;
1000 >                if ((o = U.getObject(a, j)) instanceof CountedCompleter) {
1001 >                    for (t = (CountedCompleter<?>)o, r = t;;) {
1002 >                        if (r == root) {
1003 >                            if (U.compareAndSwapObject(a, j, t, null)) {
1004 >                                top = s - 1;
1005 >                                t.doExec();
1006 >                            }
1007 >                            return true;
1008 >                        }
1009 >                        else if ((r = r.completer) == null)
1010 >                            break;
1011 >                    }
1012 >                }
1013              }
1014 +            return false;
1015          }
1016  
1017          /**
# Line 1088 | Line 1026 | public class ForkJoinPool extends Abstra
1026                      s != Thread.State.TIMED_WAITING);
1027          }
1028  
1091        /**
1092         * If this owned and is not already interrupted, try to
1093         * interrupt and/or unpark, ignoring exceptions.
1094         */
1095        final void interruptOwner() {
1096            Thread wt, p;
1097            if ((wt = owner) != null && !wt.isInterrupted()) {
1098                try {
1099                    wt.interrupt();
1100                } catch (SecurityException ignore) {
1101                }
1102            }
1103            if ((p = parker) != null)
1104                U.unpark(p);
1105        }
1106
1029          // Unsafe mechanics
1030          private static final sun.misc.Unsafe U;
1031 <        private static final long RUNSTATE;
1031 >        private static final long QBASE;
1032 >        private static final long QLOCK;
1033          private static final int ABASE;
1034          private static final int ASHIFT;
1035          static {
1113            int s;
1036              try {
1037                  U = getUnsafe();
1038                  Class<?> k = WorkQueue.class;
1039                  Class<?> ak = ForkJoinTask[].class;
1040 <                RUNSTATE = U.objectFieldOffset
1041 <                    (k.getDeclaredField("runState"));
1040 >                QBASE = U.objectFieldOffset
1041 >                    (k.getDeclaredField("base"));
1042 >                QLOCK = U.objectFieldOffset
1043 >                    (k.getDeclaredField("qlock"));
1044                  ABASE = U.arrayBaseOffset(ak);
1045 <                s = U.arrayIndexScale(ak);
1045 >                int scale = U.arrayIndexScale(ak);
1046 >                if ((scale & (scale - 1)) != 0)
1047 >                    throw new Error("data type scale not a power of two");
1048 >                ASHIFT = 31 - Integer.numberOfLeadingZeros(scale);
1049              } catch (Exception e) {
1050                  throw new Error(e);
1051              }
1125            if ((s & (s-1)) != 0)
1126                throw new Error("data type scale not a power of two");
1127            ASHIFT = 31 - Integer.numberOfLeadingZeros(s);
1052          }
1053      }
1054  
1055 +    // static fields (initialized in static initializer below)
1056 +
1057      /**
1058 <     * Per-thread records for threads that submit to pools. Currently
1059 <     * holds only pseudo-random seed / index that is used to choose
1060 <     * submission queues in method doSubmit. In the future, this may
1061 <     * also incorporate a means to implement different task rejection
1062 <     * and resubmission policies.
1137 <     *
1138 <     * Seeds for submitters and workers/workQueues work in basically
1139 <     * the same way but are initialized and updated using slightly
1140 <     * different mechanics. Both are initialized using the same
1141 <     * approach as in class ThreadLocal, where successive values are
1142 <     * unlikely to collide with previous values. This is done during
1143 <     * registration for workers, but requires a separate AtomicInteger
1144 <     * for submitters. Seeds are then randomly modified upon
1145 <     * collisions using xorshifts, which requires a non-zero seed.
1058 >     * Per-thread submission bookkeeping. Shared across all pools
1059 >     * to reduce ThreadLocal pollution and because random motion
1060 >     * to avoid contention in one pool is likely to hold for others.
1061 >     * Lazily initialized on first submission (but null-checked
1062 >     * in other contexts to avoid unnecessary initialization).
1063       */
1064 <    static final class Submitter {
1148 <        int seed;
1149 <        Submitter() {
1150 <            int s = nextSubmitterSeed.getAndAdd(SEED_INCREMENT);
1151 <            seed = (s == 0) ? 1 : s; // ensure non-zero
1152 <        }
1153 <    }
1154 <
1155 <    /** ThreadLocal class for Submitters */
1156 <    static final class ThreadSubmitter extends ThreadLocal<Submitter> {
1157 <        public Submitter initialValue() { return new Submitter(); }
1158 <    }
1159 <
1160 <    // static fields (initialized in static initializer below)
1064 >    static final ThreadLocal<Submitter> submitters;
1065  
1066      /**
1067       * Creates a new ForkJoinWorkerThread. This factory is used unless
# Line 1166 | Line 1070 | public class ForkJoinPool extends Abstra
1070      public static final ForkJoinWorkerThreadFactory
1071          defaultForkJoinWorkerThreadFactory;
1072  
1169
1170    /** Property prefix for constructing common pool */
1171    private static final String propPrefix =
1172        "java.util.concurrent.ForkJoinPool.common.";
1173
1174    /**
1175     * Common (static) pool. Non-null for public use unless a static
1176     * construction exception, but internal usages must null-check on
1177     * use.
1178     */
1179    static final ForkJoinPool commonPool;
1180
1073      /**
1074 <     * Common pool parallelism. Must equal commonPool.parallelism.
1074 >     * Permission required for callers of methods that may start or
1075 >     * kill threads.
1076       */
1077 <    static final int commonPoolParallelism;
1077 >    private static final RuntimePermission modifyThreadPermission;
1078  
1079      /**
1080 <     * Generator for assigning sequence numbers as pool names.
1080 >     * Common (static) pool. Non-null for public use unless a static
1081 >     * construction exception, but internal usages null-check on use
1082 >     * to paranoically avoid potential initialization circularities
1083 >     * as well as to simplify generated code.
1084       */
1085 <    private static final AtomicInteger poolNumberGenerator;
1085 >    static final ForkJoinPool common;
1086  
1087      /**
1088 <     * Generator for initial hashes/seeds for submitters. Accessed by
1089 <     * Submitter class constructor.
1088 >     * Common pool parallelism. To allow simpler use and management
1089 >     * when common pool threads are disabled, we allow the underlying
1090 >     * common.parallelism field to be zero, but in that case still report
1091 >     * parallelism as 1 to reflect resulting caller-runs mechanics.
1092       */
1093 <    static final AtomicInteger nextSubmitterSeed;
1093 >    static final int commonParallelism;
1094  
1095      /**
1096 <     * Permission required for callers of methods that may start or
1199 <     * kill threads.
1096 >     * Sequence number for creating workerNamePrefix.
1097       */
1098 <    private static final RuntimePermission modifyThreadPermission;
1098 >    private static int poolNumberSequence;
1099  
1100      /**
1101 <     * Per-thread submission bookkeeping. Shared across all pools
1102 <     * to reduce ThreadLocal pollution and because random motion
1206 <     * to avoid contention in one pool is likely to hold for others.
1101 >     * Returns the next sequence number. We don't expect this to
1102 >     * ever contend, so use simple builtin sync.
1103       */
1104 <    private static final ThreadSubmitter submitters;
1104 >    private static final synchronized int nextPoolId() {
1105 >        return ++poolNumberSequence;
1106 >    }
1107  
1108      // static constants
1109  
1110      /**
1111 <     * Initial timeout value (in nanoseconds) for the thread triggering
1112 <     * quiescence to park waiting for new work. On timeout, the thread
1113 <     * will instead try to shrink the number of workers.
1111 >     * Initial timeout value (in nanoseconds) for the thread
1112 >     * triggering quiescence to park waiting for new work. On timeout,
1113 >     * the thread will instead try to shrink the number of
1114 >     * workers. The value should be large enough to avoid overly
1115 >     * aggressive shrinkage during most transient stalls (long GCs
1116 >     * etc).
1117       */
1118 <    private static final long IDLE_TIMEOUT      = 1000L * 1000L * 1000L; // 1sec
1118 >    private static final long IDLE_TIMEOUT      = 2000L * 1000L * 1000L; // 2sec
1119  
1120      /**
1121       * Timeout value when there are more threads than parallelism level
1122       */
1123 <    private static final long FAST_IDLE_TIMEOUT =  100L * 1000L * 1000L;
1123 >    private static final long FAST_IDLE_TIMEOUT =  200L * 1000L * 1000L;
1124 >
1125 >    /**
1126 >     * Tolerance for idle timeouts, to cope with timer undershoots
1127 >     */
1128 >    private static final long TIMEOUT_SLOP = 2000000L;
1129  
1130      /**
1131       * The maximum stolen->joining link depth allowed in method
1132 <     * tryHelpStealer.  Must be a power of two. This value also
1227 <     * controls the maximum number of times to try to help join a task
1228 <     * without any apparent progress or change in pool state before
1229 <     * giving up and blocking (see awaitJoin).  Depths for legitimate
1132 >     * tryHelpStealer.  Must be a power of two.  Depths for legitimate
1133       * chains are unbounded, but we use a fixed constant to avoid
1134       * (otherwise unchecked) cycles and to bound staleness of
1135       * traversal parameters at the expense of sometimes blocking when
# Line 1235 | Line 1138 | public class ForkJoinPool extends Abstra
1138      private static final int MAX_HELP = 64;
1139  
1140      /**
1238     * Secondary time-based bound (in nanosecs) for helping attempts
1239     * before trying compensated blocking in awaitJoin. Used in
1240     * conjunction with MAX_HELP to reduce variance due to different
1241     * polling rates associated with different helping options. The
1242     * value should roughly approximate the time required to create
1243     * and/or activate a worker thread.
1244     */
1245    private static final long COMPENSATION_DELAY = 1L << 18; // ~0.25 millisec
1246
1247    /**
1141       * Increment for seed generators. See class ThreadLocal for
1142       * explanation.
1143       */
1144      private static final int SEED_INCREMENT = 0x61c88647;
1145  
1146 <    /**
1146 >    /*
1147       * Bits and masks for control variables
1148       *
1149       * Field ctl is a long packed with:
# Line 1278 | Line 1171 | public class ForkJoinPool extends Abstra
1171       * scan for them to avoid queuing races. Note however that
1172       * eventCount updates lag releases so usage requires care.
1173       *
1174 <     * Field runState is an int packed with:
1174 >     * Field plock is an int packed with:
1175       * SHUTDOWN: true if shutdown is enabled (1 bit)
1176 <     * SEQ:  a sequence number updated upon (de)registering workers (30 bits)
1177 <     * INIT: set true after workQueues array construction (1 bit)
1176 >     * SEQ:  a sequence lock, with PL_LOCK bit set if locked (30 bits)
1177 >     * SIGNAL: set when threads may be waiting on the lock (1 bit)
1178       *
1179       * The sequence number enables simple consistency checks:
1180       * Staleness of read-only operations on the workQueues array can
1181 <     * be checked by comparing runState before vs after the reads.
1181 >     * be checked by comparing plock before vs after the reads.
1182       */
1183  
1184      // bit positions/shifts for fields
# Line 1297 | Line 1190 | public class ForkJoinPool extends Abstra
1190      // bounds
1191      private static final int  SMASK      = 0xffff;  // short bits
1192      private static final int  MAX_CAP    = 0x7fff;  // max #workers - 1
1193 <    private static final int  SQMASK     = 0xfffe;  // even short bits
1193 >    private static final int  EVENMASK   = 0xfffe;  // even short bits
1194 >    private static final int  SQMASK     = 0x007e;  // max 64 (even) slots
1195      private static final int  SHORT_SIGN = 1 << 15;
1196      private static final int  INT_SIGN   = 1 << 31;
1197  
# Line 1322 | Line 1216 | public class ForkJoinPool extends Abstra
1216      private static final int E_MASK      = 0x7fffffff; // no STOP_BIT
1217      private static final int E_SEQ       = 1 << EC_SHIFT;
1218  
1219 <    // runState bits
1219 >    // plock bits
1220      private static final int SHUTDOWN    = 1 << 31;
1221 +    private static final int PL_LOCK     = 2;
1222 +    private static final int PL_SIGNAL   = 1;
1223 +    private static final int PL_SPINS    = 1 << 8;
1224  
1225      // access mode for WorkQueue
1226      static final int LIFO_QUEUE          =  0;
1227      static final int FIFO_QUEUE          =  1;
1228      static final int SHARED_QUEUE        = -1;
1229  
1230 <    // Instance fields
1231 <
1335 <    /*
1336 <     * Field layout order in this class tends to matter more than one
1337 <     * would like. Runtime layout order is only loosely related to
1338 <     * declaration order and may differ across JVMs, but the following
1339 <     * empirically works OK on current JVMs.
1340 <     */
1230 >    // Heuristic padding to ameliorate unfortunate memory placements
1231 >    volatile long pad00, pad01, pad02, pad03, pad04, pad05, pad06;
1232  
1233 +    // Instance fields
1234      volatile long stealCount;                  // collects worker counts
1235      volatile long ctl;                         // main pool control
1236 <    final int parallelism;                     // parallelism level
1237 <    final int localMode;                       // per-worker scheduling mode
1238 <    volatile int nextWorkerNumber;             // to create worker name string
1239 <    final int submitMask;                      // submit queue index bound
1348 <    int nextSeed;                              // for initializing worker seeds
1349 <    volatile int mainLock;                     // spinlock for array updates
1350 <    volatile int runState;                     // shutdown status and seq
1236 >    volatile int plock;                        // shutdown status and seqLock
1237 >    volatile int indexSeed;                    // worker/submitter index seed
1238 >    final short parallelism;                   // parallelism level
1239 >    final short mode;                          // LIFO/FIFO
1240      WorkQueue[] workQueues;                    // main registry
1241 <    final ForkJoinWorkerThreadFactory factory; // factory for new workers
1242 <    final Thread.UncaughtExceptionHandler ueh; // per-worker UEH
1241 >    final ForkJoinWorkerThreadFactory factory;
1242 >    final UncaughtExceptionHandler ueh;        // per-worker UEH
1243      final String workerNamePrefix;             // to create worker name string
1244  
1245 <    /*
1246 <     * Mechanics for main lock protecting worker array updates.  Uses
1358 <     * the same strategy as ConcurrentHashMap bins -- a spinLock for
1359 <     * normal cases, but falling back to builtin lock when (rarely)
1360 <     * needed.  See internal ConcurrentHashMap documentation for
1361 <     * explanation.
1362 <     */
1363 <
1364 <    static final int LOCK_WAITING = 2; // bit to indicate need for signal
1365 <    static final int MAX_LOCK_SPINS = 1 << 8;
1245 >    volatile Object pad10, pad11, pad12, pad13, pad14, pad15, pad16, pad17;
1246 >    volatile Object pad18, pad19, pad1a, pad1b;
1247  
1248 <    private void tryAwaitMainLock() {
1249 <        int spins = MAX_LOCK_SPINS, r = 0, h;
1250 <        while (((h = mainLock) & 1) != 0) {
1251 <            if (r == 0)
1252 <                r = ThreadLocalRandom.current().nextInt(); // randomize spins
1248 >    /**
1249 >     * Acquires the plock lock to protect worker array and related
1250 >     * updates. This method is called only if an initial CAS on plock
1251 >     * fails. This acts as a spinlock for normal cases, but falls back
1252 >     * to builtin monitor to block when (rarely) needed. This would be
1253 >     * a terrible idea for a highly contended lock, but works fine as
1254 >     * a more conservative alternative to a pure spinlock.
1255 >     */
1256 >    private int acquirePlock() {
1257 >        int spins = PL_SPINS, ps, nps;
1258 >        for (;;) {
1259 >            if (((ps = plock) & PL_LOCK) == 0 &&
1260 >                U.compareAndSwapInt(this, PLOCK, ps, nps = ps + PL_LOCK))
1261 >                return nps;
1262              else if (spins >= 0) {
1263 <                r ^= r << 1; r ^= r >>> 3; r ^= r << 10; // xorshift
1374 <                if (r >= 0)
1263 >                if (ThreadLocalRandom.current().nextInt() >= 0)
1264                      --spins;
1265              }
1266 <            else if (U.compareAndSwapInt(this, MAINLOCK, h, h | LOCK_WAITING)) {
1266 >            else if (U.compareAndSwapInt(this, PLOCK, ps, ps | PL_SIGNAL)) {
1267                  synchronized (this) {
1268 <                    if ((mainLock & LOCK_WAITING) != 0) {
1268 >                    if ((plock & PL_SIGNAL) != 0) {
1269                          try {
1270                              wait();
1271                          } catch (InterruptedException ie) {
1272 <                            Thread.currentThread().interrupt();
1272 >                            try {
1273 >                                Thread.currentThread().interrupt();
1274 >                            } catch (SecurityException ignore) {
1275 >                            }
1276                          }
1277                      }
1278                      else
1279 <                        notifyAll(); // possibly won race vs signaller
1279 >                        notifyAll();
1280                  }
1389                break;
1281              }
1282          }
1283      }
1284  
1394    //  Creating, registering, and deregistering workers
1395
1285      /**
1286 <     * Tries to create and start a worker
1286 >     * Unlocks and signals any thread waiting for plock. Called only
1287 >     * when CAS of seq value for unlock fails.
1288       */
1289 <    private void addWorker() {
1290 <        Throwable ex = null;
1291 <        ForkJoinWorkerThread wt = null;
1402 <        try {
1403 <            if ((wt = factory.newThread(this)) != null) {
1404 <                wt.start();
1405 <                return;
1406 <            }
1407 <        } catch (Throwable e) {
1408 <            ex = e;
1409 <        }
1410 <        deregisterWorker(wt, ex); // adjust counts etc on failure
1289 >    private void releasePlock(int ps) {
1290 >        plock = ps;
1291 >        synchronized (this) { notifyAll(); }
1292      }
1293  
1294      /**
1295 <     * Callback from ForkJoinWorkerThread constructor to assign a
1296 <     * public name. This must be separate from registerWorker because
1416 <     * it is called during the "super" constructor call in
1417 <     * ForkJoinWorkerThread.
1295 >     * Tries to create and start one worker if fewer than target
1296 >     * parallelism level exist. Adjusts counts etc on failure.
1297       */
1298 <    final String nextWorkerName() {
1299 <        int n;
1300 <        do {} while(!U.compareAndSwapInt(this, NEXTWORKERNUMBER,
1301 <                                         n = nextWorkerNumber, ++n));
1302 <        return workerNamePrefix.concat(Integer.toString(n));
1298 >    private void tryAddWorker() {
1299 >        long c; int u, e;
1300 >        while ((u = (int)((c = ctl) >>> 32)) < 0 &&
1301 >               (u & SHORT_SIGN) != 0 && (e = (int)c) >= 0) {
1302 >            long nc = ((long)(((u + UTC_UNIT) & UTC_MASK) |
1303 >                              ((u + UAC_UNIT) & UAC_MASK)) << 32) | (long)e;
1304 >            if (U.compareAndSwapLong(this, CTL, c, nc)) {
1305 >                ForkJoinWorkerThreadFactory fac;
1306 >                Throwable ex = null;
1307 >                ForkJoinWorkerThread wt = null;
1308 >                try {
1309 >                    if ((fac = factory) != null &&
1310 >                        (wt = fac.newThread(this)) != null) {
1311 >                        wt.start();
1312 >                        break;
1313 >                    }
1314 >                } catch (Throwable rex) {
1315 >                    ex = rex;
1316 >                }
1317 >                deregisterWorker(wt, ex);
1318 >                break;
1319 >            }
1320 >        }
1321      }
1322  
1323 +    //  Registering and deregistering workers
1324 +
1325      /**
1326 <     * Callback from ForkJoinWorkerThread constructor to establish its
1327 <     * poolIndex and record its WorkQueue. To avoid scanning bias due
1328 <     * to packing entries in front of the workQueues array, we treat
1329 <     * the array as a simple power-of-two hash table using per-thread
1330 <     * seed as hash, expanding as needed.
1331 <     *
1332 <     * @param w the worker's queue
1333 <     */
1334 <    final void registerWorker(WorkQueue w) {
1335 <        while (!U.compareAndSwapInt(this, MAINLOCK, 0, 1))
1336 <            tryAwaitMainLock();
1326 >     * Callback from ForkJoinWorkerThread to establish and record its
1327 >     * WorkQueue. To avoid scanning bias due to packing entries in
1328 >     * front of the workQueues array, we treat the array as a simple
1329 >     * power-of-two hash table using per-thread seed as hash,
1330 >     * expanding as needed.
1331 >     *
1332 >     * @param wt the worker thread
1333 >     * @return the worker's queue
1334 >     */
1335 >    final WorkQueue registerWorker(ForkJoinWorkerThread wt) {
1336 >        UncaughtExceptionHandler handler; WorkQueue[] ws; int s, ps;
1337 >        wt.setDaemon(true);
1338 >        if ((handler = ueh) != null)
1339 >            wt.setUncaughtExceptionHandler(handler);
1340 >        do {} while (!U.compareAndSwapInt(this, INDEXSEED, s = indexSeed,
1341 >                                          s += SEED_INCREMENT) ||
1342 >                     s == 0); // skip 0
1343 >        WorkQueue w = new WorkQueue(this, wt, mode, s);
1344 >        if (((ps = plock) & PL_LOCK) != 0 ||
1345 >            !U.compareAndSwapInt(this, PLOCK, ps, ps += PL_LOCK))
1346 >            ps = acquirePlock();
1347 >        int nps = (ps & SHUTDOWN) | ((ps + PL_LOCK) & ~SHUTDOWN);
1348          try {
1349 <            WorkQueue[] ws;
1350 <            if ((ws = workQueues) == null)
1351 <                ws = workQueues = new WorkQueue[submitMask + 1];
1352 <            if (w != null) {
1353 <                int rs, n =  ws.length, m = n - 1;
1354 <                int s = nextSeed += SEED_INCREMENT; // rarely-colliding sequence
1445 <                w.seed = (s == 0) ? 1 : s;          // ensure non-zero seed
1446 <                int r = (s << 1) | 1;               // use odd-numbered indices
1447 <                if (ws[r &= m] != null) {           // collision
1448 <                    int probes = 0;                 // step by approx half size
1449 <                    int step = (n <= 4) ? 2 : ((n >>> 1) & SQMASK) + 2;
1349 >            if ((ws = workQueues) != null) {    // skip if shutting down
1350 >                int n = ws.length, m = n - 1;
1351 >                int r = (s << 1) | 1;           // use odd-numbered indices
1352 >                if (ws[r &= m] != null) {       // collision
1353 >                    int probes = 0;             // step by approx half size
1354 >                    int step = (n <= 4) ? 2 : ((n >>> 1) & EVENMASK) + 2;
1355                      while (ws[r = (r + step) & m] != null) {
1356                          if (++probes >= n) {
1357                              workQueues = ws = Arrays.copyOf(ws, n <<= 1);
# Line 1455 | Line 1360 | public class ForkJoinPool extends Abstra
1360                          }
1361                      }
1362                  }
1363 <                w.eventCount = w.poolIndex = r;     // establish before recording
1364 <                ws[r] = w;                          // also update seq
1365 <                runState = ((rs = runState) & SHUTDOWN) | ((rs + 2) & ~SHUTDOWN);
1363 >                w.poolIndex = (short)r;
1364 >                w.eventCount = r; // volatile write orders
1365 >                ws[r] = w;
1366              }
1367          } finally {
1368 <            if (!U.compareAndSwapInt(this, MAINLOCK, 1, 0)) {
1369 <                mainLock = 0;
1465 <                synchronized (this) { notifyAll(); };
1466 <            }
1368 >            if (!U.compareAndSwapInt(this, PLOCK, ps, nps))
1369 >                releasePlock(nps);
1370          }
1371 <
1371 >        wt.setName(workerNamePrefix.concat(Integer.toString(w.poolIndex >>> 1)));
1372 >        return w;
1373      }
1374  
1375      /**
1376       * Final callback from terminating worker, as well as upon failure
1377 <     * to construct or start a worker in addWorker.  Removes record of
1378 <     * worker from array, and adjusts counts. If pool is shutting
1379 <     * down, tries to complete termination.
1377 >     * to construct or start a worker.  Removes record of worker from
1378 >     * array, and adjusts counts. If pool is shutting down, tries to
1379 >     * complete termination.
1380       *
1381 <     * @param wt the worker thread or null if addWorker failed
1381 >     * @param wt the worker thread, or null if construction failed
1382       * @param ex the exception causing failure, or null if none
1383       */
1384      final void deregisterWorker(ForkJoinWorkerThread wt, Throwable ex) {
1385          WorkQueue w = null;
1386          if (wt != null && (w = wt.workQueue) != null) {
1387 <            w.runState = -1;                // ensure runState is set
1388 <            long steals = w.totalSteals + w.nsteals, sc;
1389 <            do {} while(!U.compareAndSwapLong(this, STEALCOUNT,
1390 <                                              sc = stealCount, sc + steals));
1391 <            int idx = w.poolIndex;
1392 <            while (!U.compareAndSwapInt(this, MAINLOCK, 0, 1))
1393 <                tryAwaitMainLock();
1387 >            int ps; long sc;
1388 >            w.qlock = -1;                // ensure set
1389 >            do {} while (!U.compareAndSwapLong(this, STEALCOUNT,
1390 >                                               sc = stealCount,
1391 >                                               sc + w.nsteals));
1392 >            if (((ps = plock) & PL_LOCK) != 0 ||
1393 >                !U.compareAndSwapInt(this, PLOCK, ps, ps += PL_LOCK))
1394 >                ps = acquirePlock();
1395 >            int nps = (ps & SHUTDOWN) | ((ps + PL_LOCK) & ~SHUTDOWN);
1396              try {
1397 +                int idx = w.poolIndex;
1398                  WorkQueue[] ws = workQueues;
1399                  if (ws != null && idx >= 0 && idx < ws.length && ws[idx] == w)
1400                      ws[idx] = null;
1401              } finally {
1402 <                if (!U.compareAndSwapInt(this, MAINLOCK, 1, 0)) {
1403 <                    mainLock = 0;
1497 <                    synchronized (this) { notifyAll(); };
1498 <                }
1402 >                if (!U.compareAndSwapInt(this, PLOCK, ps, nps))
1403 >                    releasePlock(nps);
1404              }
1405          }
1406  
1407 <        long c;                             // adjust ctl counts
1407 >        long c;                          // adjust ctl counts
1408          do {} while (!U.compareAndSwapLong
1409                       (this, CTL, c = ctl, (((c - AC_UNIT) & AC_MASK) |
1410                                             ((c - TC_UNIT) & TC_MASK) |
1411                                             (c & ~(AC_MASK|TC_MASK)))));
1412  
1413 <        if (!tryTerminate(false, false) && w != null) {
1414 <            w.cancelAll();                  // cancel remaining tasks
1415 <            if (w.array != null)            // suppress signal if never ran
1416 <                signalWork();               // wake up or create replacement
1417 <            if (ex == null)                 // help clean refs on way out
1418 <                ForkJoinTask.helpExpungeStaleExceptions();
1419 <        }
1420 <
1421 <        if (ex != null)                     // rethrow
1422 <            U.throwException(ex);
1423 <    }
1424 <
1425 <    // Submissions
1426 <
1427 <    /**
1428 <     * Unless shutting down, adds the given task to a submission queue
1429 <     * at submitter's current queue index (modulo submission
1430 <     * range). If no queue exists at the index, one is created.  If
1526 <     * the queue is busy, another index is randomly chosen. The
1527 <     * submitMask bounds the effective number of queues to the
1528 <     * (nearest power of two for) parallelism level.
1529 <     *
1530 <     * @param task the task. Caller must ensure non-null.
1531 <     */
1532 <    private void doSubmit(ForkJoinTask<?> task) {
1533 <        Submitter s = submitters.get();
1534 <        for (int r = s.seed, m = submitMask;;) {
1535 <            WorkQueue[] ws; WorkQueue q;
1536 <            int k = r & m & SQMASK;          // use only even indices
1537 <            if (runState < 0)
1538 <                throw new RejectedExecutionException(); // shutting down
1539 <            else if ((ws = workQueues) == null || ws.length <= k) {
1540 <                while (!U.compareAndSwapInt(this, MAINLOCK, 0, 1))
1541 <                    tryAwaitMainLock();
1542 <                try {
1543 <                    if (workQueues == null)
1544 <                        workQueues = new WorkQueue[submitMask + 1];
1545 <                } finally {
1546 <                    if (!U.compareAndSwapInt(this, MAINLOCK, 1, 0)) {
1547 <                        mainLock = 0;
1548 <                        synchronized (this) { notifyAll(); };
1413 >        if (!tryTerminate(false, false) && w != null && w.array != null) {
1414 >            w.cancelAll();               // cancel remaining tasks
1415 >            WorkQueue[] ws; WorkQueue v; Thread p; int u, i, e;
1416 >            while ((u = (int)((c = ctl) >>> 32)) < 0 && (e = (int)c) >= 0) {
1417 >                if (e > 0) {             // activate or create replacement
1418 >                    if ((ws = workQueues) == null ||
1419 >                        (i = e & SMASK) >= ws.length ||
1420 >                        (v = ws[i]) == null)
1421 >                        break;
1422 >                    long nc = (((long)(v.nextWait & E_MASK)) |
1423 >                               ((long)(u + UAC_UNIT) << 32));
1424 >                    if (v.eventCount != (e | INT_SIGN))
1425 >                        break;
1426 >                    if (U.compareAndSwapLong(this, CTL, c, nc)) {
1427 >                        v.eventCount = (e + E_SEQ) & E_MASK;
1428 >                        if ((p = v.parker) != null)
1429 >                            U.unpark(p);
1430 >                        break;
1431                      }
1432                  }
1433 <            }
1434 <            else if ((q = ws[k]) == null) {  // create new queue
1435 <                WorkQueue nq = new WorkQueue(this, null, SHARED_QUEUE);
1436 <                while (!U.compareAndSwapInt(this, MAINLOCK, 0, 1))
1555 <                    tryAwaitMainLock();
1556 <                try {
1557 <                    int rs = runState;       // to update seq
1558 <                    if (ws == workQueues && ws[k] == null) {
1559 <                        ws[k] = nq;
1560 <                        runState = ((rs & SHUTDOWN) | ((rs + 2) & ~SHUTDOWN));
1561 <                    }
1562 <                } finally {
1563 <                    if (!U.compareAndSwapInt(this, MAINLOCK, 1, 0)) {
1564 <                        mainLock = 0;
1565 <                        synchronized (this) { notifyAll(); };
1566 <                    }
1433 >                else {
1434 >                    if ((short)u < 0)
1435 >                        tryAddWorker();
1436 >                    break;
1437                  }
1438              }
1569            else if (q.trySharedPush(task)) {
1570                signalWork();
1571                return;
1572            }
1573            else if (m > 1) {                // move to a different index
1574                r ^= r << 13;                // same xorshift as WorkQueues
1575                r ^= r >>> 17;
1576                s.seed = r ^= r << 5;
1577            }
1578            else
1579                Thread.yield();              // yield if no alternatives
1439          }
1440 +        if (ex == null)                     // help clean refs on way out
1441 +            ForkJoinTask.helpExpungeStaleExceptions();
1442 +        else                                // rethrow
1443 +            ForkJoinTask.rethrow(ex);
1444      }
1445  
1446 <    /**
1584 <     * Submits the given (non-null) task to the common pool, if possible.
1585 <     */
1586 <    static void submitToCommonPool(ForkJoinTask<?> task) {
1587 <        ForkJoinPool p;
1588 <        if ((p = commonPool) == null)
1589 <            throw new RejectedExecutionException("Common Pool Unavailable");
1590 <        p.doSubmit(task);
1591 <    }
1446 >    // Submissions
1447  
1448      /**
1449 <     * Returns true if caller is (or may be) submitter to the common
1450 <     * pool, and not all workers are active, and there appear to be
1451 <     * tasks in the associated submission queue.
1449 >     * Per-thread records for threads that submit to pools. Currently
1450 >     * holds only pseudo-random seed / index that is used to choose
1451 >     * submission queues in method externalPush. In the future, this may
1452 >     * also incorporate a means to implement different task rejection
1453 >     * and resubmission policies.
1454 >     *
1455 >     * Seeds for submitters and workers/workQueues work in basically
1456 >     * the same way but are initialized and updated using slightly
1457 >     * different mechanics. Both are initialized using the same
1458 >     * approach as in class ThreadLocal, where successive values are
1459 >     * unlikely to collide with previous values. Seeds are then
1460 >     * randomly modified upon collisions using xorshifts, which
1461 >     * requires a non-zero seed.
1462       */
1463 <    static boolean canHelpCommonPool() {
1464 <        ForkJoinPool p; WorkQueue[] ws; WorkQueue q;
1465 <        int k = submitters.get().seed & SQMASK;
1601 <        return ((p = commonPool) != null &&
1602 <                (int)(p.ctl >> AC_SHIFT) < 0 &&
1603 <                (ws = p.workQueues) != null &&
1604 <                ws.length > (k &= p.submitMask) &&
1605 <                (q = ws[k]) != null &&
1606 <                q.top - q.base > 0);
1463 >    static final class Submitter {
1464 >        int seed;
1465 >        Submitter(int s) { seed = s; }
1466      }
1467  
1468      /**
1469 <     * Returns true if the given task was submitted to common pool
1470 <     * and has not yet commenced execution, and is available for
1471 <     * removal according to execution policies; if so removing the
1472 <     * submission from the pool.
1469 >     * Unless shutting down, adds the given task to a submission queue
1470 >     * at submitter's current queue index (modulo submission
1471 >     * range). Only the most common path is directly handled in this
1472 >     * method. All others are relayed to fullExternalPush.
1473       *
1474 <     * @param task the task
1616 <     * @return true if successful
1474 >     * @param task the task. Caller must ensure non-null.
1475       */
1476 <    static boolean tryUnsubmitFromCommonPool(ForkJoinTask<?> task) {
1477 <        // Peek, looking for task and eligibility before
1478 <        // using trySharedUnpush to actually take it under lock
1479 <        ForkJoinPool p; WorkQueue[] ws; WorkQueue q;
1480 <        ForkJoinTask<?>[] a; int s;
1481 <        int k = submitters.get().seed & SQMASK;
1482 <        return ((p = commonPool) != null &&
1483 <                (int)(p.ctl >> AC_SHIFT) < 0 &&
1484 <                (ws = p.workQueues) != null &&
1485 <                ws.length > (k &= p.submitMask) &&
1486 <                (q = ws[k]) != null &&
1487 <                (a = q.array) != null &&
1488 <                (s = q.top - 1) - q.base >= 0 &&
1489 <                s >= 0 && s < a.length &&
1490 <                a[s] == task &&
1491 <                q.trySharedUnpush(task));
1476 >    final void externalPush(ForkJoinTask<?> task) {
1477 >        Submitter z = submitters.get();
1478 >        WorkQueue q; int r, m, s, n, am; ForkJoinTask<?>[] a;
1479 >        int ps = plock;
1480 >        WorkQueue[] ws = workQueues;
1481 >        if (z != null && ps > 0 && ws != null && (m = (ws.length - 1)) >= 0 &&
1482 >            (q = ws[m & (r = z.seed) & SQMASK]) != null && r != 0 &&
1483 >            U.compareAndSwapInt(q, QLOCK, 0, 1)) { // lock
1484 >            if ((a = q.array) != null &&
1485 >                (am = a.length - 1) > (n = (s = q.top) - q.base)) {
1486 >                int j = ((am & s) << ASHIFT) + ABASE;
1487 >                U.putOrderedObject(a, j, task);
1488 >                q.top = s + 1;                     // push on to deque
1489 >                q.qlock = 0;
1490 >                if (n <= 1)
1491 >                    signalWork(ws, q);
1492 >                return;
1493 >            }
1494 >            q.qlock = 0;
1495 >        }
1496 >        fullExternalPush(task);
1497      }
1498  
1499      /**
1500 <     * Tries to pop a task from common pool with given root
1501 <     */
1502 <    static ForkJoinTask<?> popCCFromCommonPool(CountedCompleter<?> root) {
1503 <        ForkJoinPool p; WorkQueue[] ws; WorkQueue q;
1504 <        ForkJoinTask<?> t;
1505 <        int k = submitters.get().seed & SQMASK;
1506 <        if (root != null &&
1507 <            (p = commonPool) != null &&
1508 <            (int)(p.ctl >> AC_SHIFT) < 0 &&
1509 <            (ws = p.workQueues) != null &&
1510 <            ws.length > (k &= p.submitMask) &&
1511 <            (q = ws[k]) != null && q.top - q.base > 0 &&
1512 <            root.status < 0 &&
1513 <            (t = q.sharedPopCC(root)) != null)
1514 <            return t;
1515 <        return null;
1500 >     * Full version of externalPush. This method is called, among
1501 >     * other times, upon the first submission of the first task to the
1502 >     * pool, so must perform secondary initialization.  It also
1503 >     * detects first submission by an external thread by looking up
1504 >     * its ThreadLocal, and creates a new shared queue if the one at
1505 >     * index if empty or contended. The plock lock body must be
1506 >     * exception-free (so no try/finally) so we optimistically
1507 >     * allocate new queues outside the lock and throw them away if
1508 >     * (very rarely) not needed.
1509 >     *
1510 >     * Secondary initialization occurs when plock is zero, to create
1511 >     * workQueue array and set plock to a valid value.  This lock body
1512 >     * must also be exception-free. Because the plock seq value can
1513 >     * eventually wrap around zero, this method harmlessly fails to
1514 >     * reinitialize if workQueues exists, while still advancing plock.
1515 >     */
1516 >    private void fullExternalPush(ForkJoinTask<?> task) {
1517 >        int r = 0; // random index seed
1518 >        for (Submitter z = submitters.get();;) {
1519 >            WorkQueue[] ws; WorkQueue q; int ps, m, k;
1520 >            if (z == null) {
1521 >                if (U.compareAndSwapInt(this, INDEXSEED, r = indexSeed,
1522 >                                        r += SEED_INCREMENT) && r != 0)
1523 >                    submitters.set(z = new Submitter(r));
1524 >            }
1525 >            else if (r == 0) {                  // move to a different index
1526 >                r = z.seed;
1527 >                r ^= r << 13;                   // same xorshift as WorkQueues
1528 >                r ^= r >>> 17;
1529 >                z.seed = r ^= (r << 5);
1530 >            }
1531 >            if ((ps = plock) < 0)
1532 >                throw new RejectedExecutionException();
1533 >            else if (ps == 0 || (ws = workQueues) == null ||
1534 >                     (m = ws.length - 1) < 0) { // initialize workQueues
1535 >                int p = parallelism;            // find power of two table size
1536 >                int n = (p > 1) ? p - 1 : 1;    // ensure at least 2 slots
1537 >                n |= n >>> 1; n |= n >>> 2;  n |= n >>> 4;
1538 >                n |= n >>> 8; n |= n >>> 16; n = (n + 1) << 1;
1539 >                WorkQueue[] nws = ((ws = workQueues) == null || ws.length == 0 ?
1540 >                                   new WorkQueue[n] : null);
1541 >                if (((ps = plock) & PL_LOCK) != 0 ||
1542 >                    !U.compareAndSwapInt(this, PLOCK, ps, ps += PL_LOCK))
1543 >                    ps = acquirePlock();
1544 >                if (((ws = workQueues) == null || ws.length == 0) && nws != null)
1545 >                    workQueues = nws;
1546 >                int nps = (ps & SHUTDOWN) | ((ps + PL_LOCK) & ~SHUTDOWN);
1547 >                if (!U.compareAndSwapInt(this, PLOCK, ps, nps))
1548 >                    releasePlock(nps);
1549 >            }
1550 >            else if ((q = ws[k = r & m & SQMASK]) != null) {
1551 >                if (q.qlock == 0 && U.compareAndSwapInt(q, QLOCK, 0, 1)) {
1552 >                    ForkJoinTask<?>[] a = q.array;
1553 >                    int s = q.top;
1554 >                    boolean submitted = false;
1555 >                    try {                      // locked version of push
1556 >                        if ((a != null && a.length > s + 1 - q.base) ||
1557 >                            (a = q.growArray()) != null) {   // must presize
1558 >                            int j = (((a.length - 1) & s) << ASHIFT) + ABASE;
1559 >                            U.putOrderedObject(a, j, task);
1560 >                            q.top = s + 1;
1561 >                            submitted = true;
1562 >                        }
1563 >                    } finally {
1564 >                        q.qlock = 0;  // unlock
1565 >                    }
1566 >                    if (submitted) {
1567 >                        signalWork(ws, q);
1568 >                        return;
1569 >                    }
1570 >                }
1571 >                r = 0; // move on failure
1572 >            }
1573 >            else if (((ps = plock) & PL_LOCK) == 0) { // create new queue
1574 >                q = new WorkQueue(this, null, SHARED_QUEUE, r);
1575 >                q.poolIndex = (short)k;
1576 >                if (((ps = plock) & PL_LOCK) != 0 ||
1577 >                    !U.compareAndSwapInt(this, PLOCK, ps, ps += PL_LOCK))
1578 >                    ps = acquirePlock();
1579 >                if ((ws = workQueues) != null && k < ws.length && ws[k] == null)
1580 >                    ws[k] = q;
1581 >                int nps = (ps & SHUTDOWN) | ((ps + PL_LOCK) & ~SHUTDOWN);
1582 >                if (!U.compareAndSwapInt(this, PLOCK, ps, nps))
1583 >                    releasePlock(nps);
1584 >            }
1585 >            else
1586 >                r = 0;
1587 >        }
1588      }
1589  
1655
1590      // Maintaining ctl counts
1591  
1592      /**
# Line 1660 | Line 1594 | public class ForkJoinPool extends Abstra
1594       */
1595      final void incrementActiveCount() {
1596          long c;
1597 <        do {} while (!U.compareAndSwapLong(this, CTL, c = ctl, c + AC_UNIT));
1597 >        do {} while (!U.compareAndSwapLong
1598 >                     (this, CTL, c = ctl, ((c & ~AC_MASK) |
1599 >                                           ((c & AC_MASK) + AC_UNIT))));
1600      }
1601  
1602      /**
1603 <     * Tries to create one or activate one or more workers if too few are active.
1603 >     * Tries to create or activate a worker if too few are active.
1604 >     *
1605 >     * @param ws the worker array to use to find signallees
1606 >     * @param q if non-null, the queue holding tasks to be processed
1607       */
1608 <    final void signalWork() {
1609 <        long c; int u;
1610 <        while ((u = (int)((c = ctl) >>> 32)) < 0) {     // too few active
1611 <            WorkQueue[] ws = workQueues; int e, i; WorkQueue w; Thread p;
1612 <            if ((e = (int)c) > 0) {                     // at least one waiting
1613 <                if (ws != null && (i = e & SMASK) < ws.length &&
1614 <                    (w = ws[i]) != null && w.eventCount == (e | INT_SIGN)) {
1615 <                    long nc = (((long)(w.nextWait & E_MASK)) |
1616 <                               ((long)(u + UAC_UNIT) << 32));
1678 <                    if (U.compareAndSwapLong(this, CTL, c, nc)) {
1679 <                        w.eventCount = (e + E_SEQ) & E_MASK;
1680 <                        if ((p = w.parker) != null)
1681 <                            U.unpark(p);                // activate and release
1682 <                        break;
1683 <                    }
1684 <                }
1685 <                else
1686 <                    break;
1608 >    final void signalWork(WorkQueue[] ws, WorkQueue q) {
1609 >        for (;;) {
1610 >            long c; int e, u, i; WorkQueue w; Thread p;
1611 >            if ((u = (int)((c = ctl) >>> 32)) >= 0)
1612 >                break;
1613 >            if ((e = (int)c) <= 0) {
1614 >                if ((short)u < 0)
1615 >                    tryAddWorker();
1616 >                break;
1617              }
1618 <            else if (e == 0 && (u & SHORT_SIGN) != 0) { // too few total
1619 <                long nc = (long)(((u + UTC_UNIT) & UTC_MASK) |
1620 <                                 ((u + UAC_UNIT) & UAC_MASK)) << 32;
1621 <                if (U.compareAndSwapLong(this, CTL, c, nc)) {
1622 <                    addWorker();
1623 <                    break;
1624 <                }
1618 >            if (ws == null || ws.length <= (i = e & SMASK) ||
1619 >                (w = ws[i]) == null)
1620 >                break;
1621 >            long nc = (((long)(w.nextWait & E_MASK)) |
1622 >                       ((long)(u + UAC_UNIT)) << 32);
1623 >            int ne = (e + E_SEQ) & E_MASK;
1624 >            if (w.eventCount == (e | INT_SIGN) &&
1625 >                U.compareAndSwapLong(this, CTL, c, nc)) {
1626 >                w.eventCount = ne;
1627 >                if ((p = w.parker) != null)
1628 >                    U.unpark(p);
1629 >                break;
1630              }
1631 <            else
1631 >            if (q != null && q.base >= q.top)
1632                  break;
1633          }
1634      }
# Line 1704 | Line 1639 | public class ForkJoinPool extends Abstra
1639       * Top-level runloop for workers, called by ForkJoinWorkerThread.run.
1640       */
1641      final void runWorker(WorkQueue w) {
1642 <        w.growArray(false);         // initialize queue array in this thread
1643 <        do { w.runTask(scan(w)); } while (w.runState >= 0);
1642 >        w.growArray(); // allocate queue
1643 >        for (int r = w.hint; scan(w, r) == 0; ) {
1644 >            r ^= r << 13; r ^= r >>> 17; r ^= r << 5; // xorshift
1645 >        }
1646      }
1647  
1648      /**
1649 <     * Scans for and, if found, returns one task, else possibly
1649 >     * Scans for and, if found, runs one task, else possibly
1650       * inactivates the worker. This method operates on single reads of
1651       * volatile state and is designed to be re-invoked continuously,
1652       * in part because it returns upon detecting inconsistencies,
1653       * contention, or state changes that indicate possible success on
1654       * re-invocation.
1655       *
1656 <     * The scan searches for tasks across a random permutation of
1657 <     * queues (starting at a random index and stepping by a random
1658 <     * relative prime, checking each at least once).  The scan
1659 <     * terminates upon either finding a non-empty queue, or completing
1660 <     * the sweep. If the worker is not inactivated, it takes and
1661 <     * returns a task from this queue.  On failure to find a task, we
1662 <     * take one of the following actions, after which the caller will
1663 <     * retry calling this method unless terminated.
1664 <     *
1728 <     * * If pool is terminating, terminate the worker.
1729 <     *
1730 <     * * If not a complete sweep, try to release a waiting worker.  If
1731 <     * the scan terminated because the worker is inactivated, then the
1732 <     * released worker will often be the calling worker, and it can
1733 <     * succeed obtaining a task on the next call. Or maybe it is
1734 <     * another worker, but with same net effect. Releasing in other
1735 <     * cases as well ensures that we have enough workers running.
1736 <     *
1737 <     * * If not already enqueued, try to inactivate and enqueue the
1738 <     * worker on wait queue. Or, if inactivating has caused the pool
1739 <     * to be quiescent, relay to idleAwaitWork to check for
1740 <     * termination and possibly shrink pool.
1741 <     *
1742 <     * * If already inactive, and the caller has run a task since the
1743 <     * last empty scan, return (to allow rescan) unless others are
1744 <     * also inactivated.  Field WorkQueue.rescans counts down on each
1745 <     * scan to ensure eventual inactivation and blocking.
1746 <     *
1747 <     * * If already enqueued and none of the above apply, park
1748 <     * awaiting signal,
1656 >     * The scan searches for tasks across queues starting at a random
1657 >     * index, checking each at least twice.  The scan terminates upon
1658 >     * either finding a non-empty queue, or completing the sweep. If
1659 >     * the worker is not inactivated, it takes and runs a task from
1660 >     * this queue. Otherwise, if not activated, it tries to activate
1661 >     * itself or some other worker by signalling. On failure to find a
1662 >     * task, returns (for retry) if pool state may have changed during
1663 >     * an empty scan, or tries to inactivate if active, else possibly
1664 >     * blocks or terminates via method awaitWork.
1665       *
1666       * @param w the worker (via its WorkQueue)
1667 <     * @return a task or null if none found
1667 >     * @param r a random seed
1668 >     * @return worker qlock status if would have waited, else 0
1669       */
1670 <    private final ForkJoinTask<?> scan(WorkQueue w) {
1671 <        WorkQueue[] ws;                       // first update random seed
1672 <        int r = w.seed; r ^= r << 13; r ^= r >>> 17; w.seed = r ^= r << 5;
1673 <        int rs = runState, m;                 // volatile read order matters
1674 <        if ((ws = workQueues) != null && (m = ws.length - 1) > 0) {
1675 <            int ec = w.eventCount;            // ec is negative if inactive
1676 <            int step = (r >>> 16) | 1;        // relative prime
1677 <            for (int j = (m + 1) << 2; ; r += step) {
1678 <                WorkQueue q; ForkJoinTask<?> t; ForkJoinTask<?>[] a; int b;
1679 <                if ((q = ws[r & m]) != null && (b = q.base) - q.top < 0 &&
1680 <                    (a = q.array) != null) {  // probably nonempty
1681 <                    int i = (((a.length - 1) & b) << ASHIFT) + ABASE;
1682 <                    t = (ForkJoinTask<?>)U.getObjectVolatile(a, i);
1683 <                    if (q.base == b && ec >= 0 && t != null &&
1684 <                        U.compareAndSwapObject(a, i, t, null)) {
1685 <                        if (q.top - (q.base = b + 1) > 0)
1686 <                            signalWork();    // help pushes signal
1687 <                        return t;
1688 <                    }
1689 <                    else if (ec < 0 || j <= m) {
1773 <                        rs = 0;               // mark scan as imcomplete
1774 <                        break;                // caller can retry after release
1670 >    private final int scan(WorkQueue w, int r) {
1671 >        WorkQueue[] ws; int m;
1672 >        long c = ctl;                            // for consistency check
1673 >        if ((ws = workQueues) != null && (m = ws.length - 1) >= 0 && w != null) {
1674 >            for (int j = m + m + 1, ec = w.eventCount;;) {
1675 >                WorkQueue q; int b, e; ForkJoinTask<?>[] a; ForkJoinTask<?> t;
1676 >                if ((q = ws[(r - j) & m]) != null &&
1677 >                    (b = q.base) - q.top < 0 && (a = q.array) != null) {
1678 >                    long i = (((a.length - 1) & b) << ASHIFT) + ABASE;
1679 >                    if ((t = ((ForkJoinTask<?>)
1680 >                              U.getObjectVolatile(a, i))) != null) {
1681 >                        if (ec < 0)
1682 >                            helpRelease(c, ws, w, q, b);
1683 >                        else if (q.base == b &&
1684 >                                 U.compareAndSwapObject(a, i, t, null)) {
1685 >                            U.putOrderedInt(q, QBASE, b + 1);
1686 >                            if ((b + 1) - q.top < 0)
1687 >                                signalWork(ws, q);
1688 >                            w.runTask(t);
1689 >                        }
1690                      }
1691 +                    break;
1692                  }
1693 <                if (--j < 0)
1693 >                else if (--j < 0) {
1694 >                    if ((ec | (e = (int)c)) < 0) // inactive or terminating
1695 >                        return awaitWork(w, c, ec);
1696 >                    else if (ctl == c) {         // try to inactivate and enqueue
1697 >                        long nc = (long)ec | ((c - AC_UNIT) & (AC_MASK|TC_MASK));
1698 >                        w.nextWait = e;
1699 >                        w.eventCount = ec | INT_SIGN;
1700 >                        if (!U.compareAndSwapLong(this, CTL, c, nc))
1701 >                            w.eventCount = ec;   // back out
1702 >                    }
1703                      break;
1704 +                }
1705              }
1706 +        }
1707 +        return 0;
1708 +    }
1709  
1710 <            long c = ctl; int e = (int)c, a = (int)(c >> AC_SHIFT), nr, ns;
1711 <            if (e < 0)                        // decode ctl on empty scan
1712 <                w.runState = -1;              // pool is terminating
1713 <            else if (rs == 0 || rs != runState) { // incomplete scan
1714 <                WorkQueue v; Thread p;        // try to release a waiter
1715 <                if (e > 0 && a < 0 && w.eventCount == ec &&
1716 <                    (v = ws[e & m]) != null && v.eventCount == (e | INT_SIGN)) {
1717 <                    long nc = ((long)(v.nextWait & E_MASK) |
1718 <                               ((c + AC_UNIT) & (AC_MASK|TC_MASK)));
1719 <                    if (ctl == c && U.compareAndSwapLong(this, CTL, c, nc)) {
1720 <                        v.eventCount = (e + E_SEQ) & E_MASK;
1721 <                        if ((p = v.parker) != null)
1722 <                            U.unpark(p);
1723 <                    }
1724 <                }
1710 >    /**
1711 >     * A continuation of scan(), possibly blocking or terminating
1712 >     * worker w. Returns without blocking if pool state has apparently
1713 >     * changed since last invocation.  Also, if inactivating w has
1714 >     * caused the pool to become quiescent, checks for pool
1715 >     * termination, and, so long as this is not the only worker, waits
1716 >     * for event for up to a given duration.  On timeout, if ctl has
1717 >     * not changed, terminates the worker, which will in turn wake up
1718 >     * another worker to possibly repeat this process.
1719 >     *
1720 >     * @param w the calling worker
1721 >     * @param c the ctl value on entry to scan
1722 >     * @param ec the worker's eventCount on entry to scan
1723 >     */
1724 >    private final int awaitWork(WorkQueue w, long c, int ec) {
1725 >        int stat, ns; long parkTime, deadline;
1726 >        if ((stat = w.qlock) >= 0 && w.eventCount == ec && ctl == c &&
1727 >            !Thread.interrupted()) {
1728 >            int e = (int)c;
1729 >            int u = (int)(c >>> 32);
1730 >            int d = (u >> UAC_SHIFT) + parallelism; // active count
1731 >
1732 >            if (e < 0 || (d <= 0 && tryTerminate(false, false)))
1733 >                stat = w.qlock = -1;          // pool is terminating
1734 >            else if ((ns = w.nsteals) != 0) { // collect steals and retry
1735 >                long sc;
1736 >                w.nsteals = 0;
1737 >                do {} while (!U.compareAndSwapLong(this, STEALCOUNT,
1738 >                                                   sc = stealCount, sc + ns));
1739              }
1740 <            else if (ec >= 0) {               // try to enqueue/inactivate
1741 <                long nc = (long)ec | ((c - AC_UNIT) & (AC_MASK|TC_MASK));
1742 <                w.nextWait = e;
1743 <                w.eventCount = ec | INT_SIGN; // mark as inactive
1744 <                if (ctl != c || !U.compareAndSwapLong(this, CTL, c, nc))
1745 <                    w.eventCount = ec;        // unmark on CAS failure
1746 <                else {
1747 <                    if ((ns = w.nsteals) != 0) {
1748 <                        w.nsteals = 0;        // set rescans if ran task
1806 <                        w.rescans = (a > 0) ? 0 : a + parallelism;
1807 <                        w.totalSteals += ns;
1808 <                    }
1809 <                    if (a == 1 - parallelism) // quiescent
1810 <                        idleAwaitWork(w, nc, c);
1740 >            else {
1741 >                long pc = ((d > 0 || ec != (e | INT_SIGN)) ? 0L :
1742 >                           ((long)(w.nextWait & E_MASK)) | // ctl to restore
1743 >                           ((long)(u + UAC_UNIT)) << 32);
1744 >                if (pc != 0L) {               // timed wait if last waiter
1745 >                    int dc = -(short)(c >>> TC_SHIFT);
1746 >                    parkTime = (dc < 0 ? FAST_IDLE_TIMEOUT:
1747 >                                (dc + 1) * IDLE_TIMEOUT);
1748 >                    deadline = System.nanoTime() + parkTime - TIMEOUT_SLOP;
1749                  }
1750 <            }
1751 <            else if (w.eventCount < 0) {      // already queued
1752 <                int ac = a + parallelism;
1815 <                if ((nr = w.rescans) > 0)     // continue rescanning
1816 <                    w.rescans = (ac < nr) ? ac : nr - 1;
1817 <                else if (((w.seed >>> 16) & ac) == 0) { // randomize park
1818 <                    Thread.interrupted();     // clear status
1750 >                else
1751 >                    parkTime = deadline = 0L;
1752 >                if (w.eventCount == ec && ctl == c) {
1753                      Thread wt = Thread.currentThread();
1754                      U.putObject(wt, PARKBLOCKER, this);
1755                      w.parker = wt;            // emulate LockSupport.park
1756 <                    if (w.eventCount < 0)     // recheck
1757 <                        U.park(false, 0L);
1756 >                    if (w.eventCount == ec && ctl == c)
1757 >                        U.park(false, parkTime);  // must recheck before park
1758                      w.parker = null;
1759                      U.putObject(wt, PARKBLOCKER, null);
1760 +                    if (parkTime != 0L && ctl == c &&
1761 +                        deadline - System.nanoTime() <= 0L &&
1762 +                        U.compareAndSwapLong(this, CTL, c, pc))
1763 +                        stat = w.qlock = -1;  // shrink pool
1764                  }
1765              }
1766          }
1767 <        return null;
1767 >        return stat;
1768      }
1769  
1770      /**
1771 <     * If inactivating worker w has caused the pool to become
1772 <     * quiescent, checks for pool termination, and, so long as this is
1773 <     * not the only worker, waits for event for up to a given
1774 <     * duration.  On timeout, if ctl has not changed, terminates the
1775 <     * worker, which will in turn wake up another worker to possibly
1776 <     * repeat this process.
1777 <     *
1778 <     * @param w the calling worker
1779 <     * @param currentCtl the ctl value triggering possible quiescence
1780 <     * @param prevCtl the ctl value to restore if thread is terminated
1781 <     */
1782 <    private void idleAwaitWork(WorkQueue w, long currentCtl, long prevCtl) {
1783 <        if (w.eventCount < 0 && !tryTerminate(false, false) &&
1784 <            (int)prevCtl != 0 && !hasQueuedSubmissions() && ctl == currentCtl) {
1785 <            int dc = -(short)(currentCtl >>> TC_SHIFT);
1786 <            long parkTime = dc < 0 ? FAST_IDLE_TIMEOUT: (dc + 1) * IDLE_TIMEOUT;
1787 <            long deadline = System.nanoTime() + parkTime - 100000L; // 1ms slop
1788 <            Thread wt = Thread.currentThread();
1789 <            while (ctl == currentCtl) {
1790 <                Thread.interrupted();  // timed variant of version in scan()
1853 <                U.putObject(wt, PARKBLOCKER, this);
1854 <                w.parker = wt;
1855 <                if (ctl == currentCtl)
1856 <                    U.park(false, parkTime);
1857 <                w.parker = null;
1858 <                U.putObject(wt, PARKBLOCKER, null);
1859 <                if (ctl != currentCtl)
1860 <                    break;
1861 <                if (deadline - System.nanoTime() <= 0L &&
1862 <                    U.compareAndSwapLong(this, CTL, currentCtl, prevCtl)) {
1863 <                    w.eventCount = (w.eventCount + E_SEQ) | E_MASK;
1864 <                    w.runState = -1;   // shrink
1865 <                    break;
1866 <                }
1771 >     * Possibly releases (signals) a worker. Called only from scan()
1772 >     * when a worker with apparently inactive status finds a non-empty
1773 >     * queue. This requires revalidating all of the associated state
1774 >     * from caller.
1775 >     */
1776 >    private final void helpRelease(long c, WorkQueue[] ws, WorkQueue w,
1777 >                                   WorkQueue q, int b) {
1778 >        WorkQueue v; int e, i; Thread p;
1779 >        if (w != null && w.eventCount < 0 && (e = (int)c) > 0 &&
1780 >            ws != null && ws.length > (i = e & SMASK) &&
1781 >            (v = ws[i]) != null && ctl == c) {
1782 >            long nc = (((long)(v.nextWait & E_MASK)) |
1783 >                       ((long)((int)(c >>> 32) + UAC_UNIT)) << 32);
1784 >            int ne = (e + E_SEQ) & E_MASK;
1785 >            if (q != null && q.base == b && w.eventCount < 0 &&
1786 >                v.eventCount == (e | INT_SIGN) &&
1787 >                U.compareAndSwapLong(this, CTL, c, nc)) {
1788 >                v.eventCount = ne;
1789 >                if ((p = v.parker) != null)
1790 >                    U.unpark(p);
1791              }
1792          }
1793      }
# Line 1888 | Line 1812 | public class ForkJoinPool extends Abstra
1812       */
1813      private int tryHelpStealer(WorkQueue joiner, ForkJoinTask<?> task) {
1814          int stat = 0, steps = 0;                    // bound to avoid cycles
1815 <        if (joiner != null && task != null) {       // hoist null checks
1815 >        if (task != null && joiner != null &&
1816 >            joiner.base - joiner.top >= 0) {        // hoist checks
1817              restart: for (;;) {
1818                  ForkJoinTask<?> subtask = task;     // current target
1819                  for (WorkQueue j = joiner, v;;) {   // v is stealer of subtask
# Line 1899 | Line 1824 | public class ForkJoinPool extends Abstra
1824                      }
1825                      if ((ws = workQueues) == null || (m = ws.length - 1) <= 0)
1826                          break restart;              // shutting down
1827 <                    if ((v = ws[h = (j.stealHint | 1) & m]) == null ||
1827 >                    if ((v = ws[h = (j.hint | 1) & m]) == null ||
1828                          v.currentSteal != subtask) {
1829                          for (int origin = h;;) {    // find stealer
1830                              if (((h = (h + 2) & m) & 15) == 1 &&
# Line 1907 | Line 1832 | public class ForkJoinPool extends Abstra
1832                                  continue restart;   // occasional staleness check
1833                              if ((v = ws[h]) != null &&
1834                                  v.currentSteal == subtask) {
1835 <                                j.stealHint = h;    // save hint
1835 >                                j.hint = h;        // save hint
1836                                  break;
1837                              }
1838                              if (h == origin)
# Line 1915 | Line 1840 | public class ForkJoinPool extends Abstra
1840                          }
1841                      }
1842                      for (;;) { // help stealer or descend to its stealer
1843 <                        ForkJoinTask[] a;  int b;
1843 >                        ForkJoinTask[] a; int b;
1844                          if (subtask.status < 0)     // surround probes with
1845                              continue restart;       //   consistency checks
1846                          if ((b = v.base) - v.top < 0 && (a = v.array) != null) {
# Line 1926 | Line 1851 | public class ForkJoinPool extends Abstra
1851                                  v.currentSteal != subtask)
1852                                  continue restart;   // stale
1853                              stat = 1;               // apparent progress
1854 <                            if (t != null && v.base == b &&
1855 <                                U.compareAndSwapObject(a, i, t, null)) {
1856 <                                v.base = b + 1;     // help stealer
1857 <                                joiner.runSubtask(t);
1854 >                            if (v.base == b) {
1855 >                                if (t == null)
1856 >                                    break restart;
1857 >                                if (U.compareAndSwapObject(a, i, t, null)) {
1858 >                                    U.putOrderedInt(v, QBASE, b + 1);
1859 >                                    ForkJoinTask<?> ps = joiner.currentSteal;
1860 >                                    int jt = joiner.top;
1861 >                                    do {
1862 >                                        joiner.currentSteal = t;
1863 >                                        t.doExec(); // clear local tasks too
1864 >                                    } while (task.status >= 0 &&
1865 >                                             joiner.top != jt &&
1866 >                                             (t = joiner.pop()) != null);
1867 >                                    joiner.currentSteal = ps;
1868 >                                    break restart;
1869 >                                }
1870                              }
1934                            else if (v.base == b && ++steps == MAX_HELP)
1935                                break restart;      // v apparently stalled
1871                          }
1872                          else {                      // empty -- try to descend
1873                              ForkJoinTask<?> next = v.currentJoin;
# Line 1955 | Line 1890 | public class ForkJoinPool extends Abstra
1890      }
1891  
1892      /**
1893 <     * If task is at base of some steal queue, steals and executes it.
1893 >     * Analog of tryHelpStealer for CountedCompleters. Tries to steal
1894 >     * and run tasks within the target's computation.
1895       *
1896 <     * @param joiner the joining worker
1961 <     * @param task the task
1896 >     * @param task the task to join
1897       */
1898 <    private void tryPollForAndExec(WorkQueue joiner, ForkJoinTask<?> task) {
1899 <        WorkQueue[] ws;
1900 <        if ((ws = workQueues) != null) {
1901 <            for (int j = 1; j < ws.length && task.status >= 0; j += 2) {
1902 <                WorkQueue q = ws[j];
1903 <                if (q != null && q.pollFor(task)) {
1904 <                    joiner.runSubtask(task);
1898 >    private int helpComplete(WorkQueue joiner, CountedCompleter<?> task) {
1899 >        WorkQueue[] ws; int m;
1900 >        int s = 0;
1901 >        if ((ws = workQueues) != null && (m = ws.length - 1) >= 0 &&
1902 >            joiner != null && task != null) {
1903 >            int j = joiner.poolIndex;
1904 >            int scans = m + m + 1;
1905 >            long c = 0L;              // for stability check
1906 >            for (int k = scans; ; j += 2) {
1907 >                WorkQueue q;
1908 >                if ((s = task.status) < 0)
1909 >                    break;
1910 >                else if (joiner.internalPopAndExecCC(task))
1911 >                    k = scans;
1912 >                else if ((s = task.status) < 0)
1913                      break;
1914 +                else if ((q = ws[j & m]) != null && q.pollAndExecCC(task))
1915 +                    k = scans;
1916 +                else if (--k < 0) {
1917 +                    if (c == (c = ctl))
1918 +                        break;
1919 +                    k = scans;
1920                  }
1921              }
1922          }
1923 +        return s;
1924      }
1925  
1926      /**
1927       * Tries to decrement active count (sometimes implicitly) and
1928       * possibly release or create a compensating worker in preparation
1929       * for blocking. Fails on contention or termination. Otherwise,
1930 <     * adds a new thread if no idle workers are available and either
1931 <     * pool would become completely starved or: (at least half
1932 <     * starved, and fewer than 50% spares exist, and there is at least
1933 <     * one task apparently available). Even though the availability
1984 <     * check requires a full scan, it is worthwhile in reducing false
1985 <     * alarms.
1986 <     *
1987 <     * @param task if non-null, a task being waited for
1988 <     * @param blocker if non-null, a blocker being waited for
1989 <     * @return true if the caller can block, else should recheck and retry
1930 >     * adds a new thread if no idle workers are available and pool
1931 >     * may become starved.
1932 >     *
1933 >     * @param c the assumed ctl value
1934       */
1935 <    final boolean tryCompensate(ForkJoinTask<?> task, ManagedBlocker blocker) {
1992 <        int pc = parallelism, e;
1993 <        long c = ctl;
1935 >    final boolean tryCompensate(long c) {
1936          WorkQueue[] ws = workQueues;
1937 <        if ((e = (int)c) >= 0 && ws != null) {
1938 <            int u, a, ac, hc;
1939 <            int tc = (short)((u = (int)(c >>> 32)) >>> UTC_SHIFT) + pc;
1940 <            boolean replace = false;
1941 <            if ((a = u >> UAC_SHIFT) <= 0) {
1942 <                if ((ac = a + pc) <= 1)
1943 <                    replace = true;
1944 <                else if ((e > 0 || (task != null &&
1945 <                                    ac <= (hc = pc >>> 1) && tc < pc + hc))) {
1946 <                    WorkQueue w;
1947 <                    for (int j = 0; j < ws.length; ++j) {
1948 <                        if ((w = ws[j]) != null && !w.isEmpty()) {
1949 <                            replace = true;
1950 <                            break;   // in compensation range and tasks available
1951 <                        }
1952 <                    }
1953 <                }
1937 >        int pc = parallelism, e = (int)c, m, tc;
1938 >        if (ws != null && (m = ws.length - 1) >= 0 && e >= 0 && ctl == c) {
1939 >            WorkQueue w = ws[e & m];
1940 >            if (e != 0 && w != null) {
1941 >                Thread p;
1942 >                long nc = ((long)(w.nextWait & E_MASK) |
1943 >                           (c & (AC_MASK|TC_MASK)));
1944 >                int ne = (e + E_SEQ) & E_MASK;
1945 >                if (w.eventCount == (e | INT_SIGN) &&
1946 >                    U.compareAndSwapLong(this, CTL, c, nc)) {
1947 >                    w.eventCount = ne;
1948 >                    if ((p = w.parker) != null)
1949 >                        U.unpark(p);
1950 >                    return true;   // replace with idle worker
1951 >                }
1952 >            }
1953 >            else if ((tc = (short)(c >>> TC_SHIFT)) >= 0 &&
1954 >                     (int)(c >> AC_SHIFT) + pc > 1) {
1955 >                long nc = ((c - AC_UNIT) & AC_MASK) | (c & ~AC_MASK);
1956 >                if (U.compareAndSwapLong(this, CTL, c, nc))
1957 >                    return true;   // no compensation
1958              }
1959 <            if ((task == null || task.status >= 0) && // recheck need to block
1960 <                (blocker == null || !blocker.isReleasable()) && ctl == c) {
1961 <                if (!replace) {          // no compensation
1962 <                    long nc = ((c - AC_UNIT) & AC_MASK) | (c & ~AC_MASK);
1963 <                    if (U.compareAndSwapLong(this, CTL, c, nc))
1964 <                        return true;
1965 <                }
1966 <                else if (e != 0) {       // release an idle worker
1967 <                    WorkQueue w; Thread p; int i;
1968 <                    if ((i = e & SMASK) < ws.length && (w = ws[i]) != null) {
2023 <                        long nc = ((long)(w.nextWait & E_MASK) |
2024 <                                   (c & (AC_MASK|TC_MASK)));
2025 <                        if (w.eventCount == (e | INT_SIGN) &&
2026 <                            U.compareAndSwapLong(this, CTL, c, nc)) {
2027 <                            w.eventCount = (e + E_SEQ) & E_MASK;
2028 <                            if ((p = w.parker) != null)
2029 <                                U.unpark(p);
1959 >            else if (tc + pc < MAX_CAP) {
1960 >                long nc = ((c + TC_UNIT) & TC_MASK) | (c & ~TC_MASK);
1961 >                if (U.compareAndSwapLong(this, CTL, c, nc)) {
1962 >                    ForkJoinWorkerThreadFactory fac;
1963 >                    Throwable ex = null;
1964 >                    ForkJoinWorkerThread wt = null;
1965 >                    try {
1966 >                        if ((fac = factory) != null &&
1967 >                            (wt = fac.newThread(this)) != null) {
1968 >                            wt.start();
1969                              return true;
1970                          }
1971 +                    } catch (Throwable rex) {
1972 +                        ex = rex;
1973                      }
1974 <                }
2034 <                else if (tc < MAX_CAP) { // create replacement
2035 <                    long nc = ((c + TC_UNIT) & TC_MASK) | (c & ~TC_MASK);
2036 <                    if (U.compareAndSwapLong(this, CTL, c, nc)) {
2037 <                        addWorker();
2038 <                        return true;
2039 <                    }
1974 >                    deregisterWorker(wt, ex); // clean up and return false
1975                  }
1976              }
1977          }
# Line 2051 | Line 1986 | public class ForkJoinPool extends Abstra
1986       * @return task status on exit
1987       */
1988      final int awaitJoin(WorkQueue joiner, ForkJoinTask<?> task) {
1989 <        int s;
1990 <        if ((s = task.status) >= 0) {
1989 >        int s = 0;
1990 >        if (task != null && (s = task.status) >= 0 && joiner != null) {
1991              ForkJoinTask<?> prevJoin = joiner.currentJoin;
1992              joiner.currentJoin = task;
1993 <            long startTime = 0L;
1994 <            for (int k = 0;;) {
1995 <                if ((s = (joiner.isEmpty() ?           // try to help
1996 <                          tryHelpStealer(joiner, task) :
1997 <                          joiner.tryRemoveAndExec(task))) == 0 &&
1993 >            do {} while (joiner.tryRemoveAndExec(task) && // process local tasks
1994 >                         (s = task.status) >= 0);
1995 >            if (s >= 0 && (task instanceof CountedCompleter))
1996 >                s = helpComplete(joiner, (CountedCompleter<?>)task);
1997 >            long cc = 0;        // for stability checks
1998 >            while (s >= 0 && (s = task.status) >= 0) {
1999 >                if ((s = tryHelpStealer(joiner, task)) == 0 &&
2000                      (s = task.status) >= 0) {
2001 <                    if (k == 0) {
2002 <                        startTime = System.nanoTime();
2003 <                        tryPollForAndExec(joiner, task); // check uncommon case
2004 <                    }
2068 <                    else if ((k & (MAX_HELP - 1)) == 0 &&
2069 <                             System.nanoTime() - startTime >=
2070 <                             COMPENSATION_DELAY &&
2071 <                             tryCompensate(task, null)) {
2072 <                        if (task.trySetSignal()) {
2001 >                    if (!tryCompensate(cc))
2002 >                        cc = ctl;
2003 >                    else {
2004 >                        if (task.trySetSignal() && (s = task.status) >= 0) {
2005                              synchronized (task) {
2006                                  if (task.status >= 0) {
2007                                      try {                // see ForkJoinTask
# Line 2081 | Line 2013 | public class ForkJoinPool extends Abstra
2013                                      task.notifyAll();
2014                              }
2015                          }
2016 <                        long c;                          // re-activate
2016 >                        long c; // reactivate
2017                          do {} while (!U.compareAndSwapLong
2018 <                                     (this, CTL, c = ctl, c + AC_UNIT));
2018 >                                     (this, CTL, c = ctl,
2019 >                                      ((c & ~AC_MASK) |
2020 >                                       ((c & AC_MASK) + AC_UNIT))));
2021                      }
2022                  }
2089                if (s < 0 || (s = task.status) < 0) {
2090                    joiner.currentJoin = prevJoin;
2091                    break;
2092                }
2093                else if ((k++ & (MAX_HELP - 1)) == MAX_HELP >>> 1)
2094                    Thread.yield();                     // for politeness
2023              }
2024 +            joiner.currentJoin = prevJoin;
2025          }
2026          return s;
2027      }
# Line 2104 | Line 2033 | public class ForkJoinPool extends Abstra
2033       *
2034       * @param joiner the joining worker
2035       * @param task the task
2107     * @return task status on exit
2036       */
2037 <    final int helpJoinOnce(WorkQueue joiner, ForkJoinTask<?> task) {
2037 >    final void helpJoinOnce(WorkQueue joiner, ForkJoinTask<?> task) {
2038          int s;
2039 <        while ((s = task.status) >= 0 &&
2040 <               (joiner.isEmpty() ?
2041 <                tryHelpStealer(joiner, task) :
2042 <                joiner.tryRemoveAndExec(task)) != 0)
2043 <            ;
2044 <        return s;
2039 >        if (joiner != null && task != null && (s = task.status) >= 0) {
2040 >            ForkJoinTask<?> prevJoin = joiner.currentJoin;
2041 >            joiner.currentJoin = task;
2042 >            do {} while (joiner.tryRemoveAndExec(task) && // process local tasks
2043 >                         (s = task.status) >= 0);
2044 >            if (s >= 0) {
2045 >                if (task instanceof CountedCompleter)
2046 >                    helpComplete(joiner, (CountedCompleter<?>)task);
2047 >                do {} while (task.status >= 0 &&
2048 >                             tryHelpStealer(joiner, task) > 0);
2049 >            }
2050 >            joiner.currentJoin = prevJoin;
2051 >        }
2052      }
2053  
2054      /**
2055       * Returns a (probably) non-empty steal queue, if one is found
2056 <     * during a random, then cyclic scan, else null.  This method must
2057 <     * be retried by caller if, by the time it tries to use the queue,
2058 <     * it is empty.
2059 <     */
2060 <    private WorkQueue findNonEmptyStealQueue(WorkQueue w) {
2061 <        // Similar to loop in scan(), but ignoring submissions
2062 <        int r = w.seed; r ^= r << 13; r ^= r >>> 17; w.seed = r ^= r << 5;
2063 <        int step = (r >>> 16) | 1;
2064 <        for (WorkQueue[] ws;;) {
2065 <            int rs = runState, m;
2066 <            if ((ws = workQueues) == null || (m = ws.length - 1) < 1)
2067 <                return null;
2133 <            for (int j = (m + 1) << 2; ; r += step) {
2134 <                WorkQueue q = ws[((r << 1) | 1) & m];
2135 <                if (q != null && !q.isEmpty())
2136 <                    return q;
2137 <                else if (--j < 0) {
2138 <                    if (runState == rs)
2139 <                        return null;
2140 <                    break;
2056 >     * during a scan, else null.  This method must be retried by
2057 >     * caller if, by the time it tries to use the queue, it is empty.
2058 >     */
2059 >    private WorkQueue findNonEmptyStealQueue() {
2060 >        int r = ThreadLocalRandom.current().nextInt();
2061 >        for (;;) {
2062 >            int ps = plock, m; WorkQueue[] ws; WorkQueue q;
2063 >            if ((ws = workQueues) != null && (m = ws.length - 1) >= 0) {
2064 >                for (int j = (m + 1) << 2; j >= 0; --j) {
2065 >                    if ((q = ws[(((r - j) << 1) | 1) & m]) != null &&
2066 >                        q.base - q.top < 0)
2067 >                        return q;
2068                  }
2069              }
2070 +            if (plock == ps)
2071 +                return null;
2072          }
2073      }
2074  
# Line 2150 | Line 2079 | public class ForkJoinPool extends Abstra
2079       * find tasks either.
2080       */
2081      final void helpQuiescePool(WorkQueue w) {
2082 +        ForkJoinTask<?> ps = w.currentSteal;
2083          for (boolean active = true;;) {
2084 <            ForkJoinTask<?> localTask; // exhaust local queue
2085 <            while ((localTask = w.nextLocalTask()) != null)
2086 <                localTask.doExec();
2087 <            WorkQueue q = findNonEmptyStealQueue(w);
2158 <            if (q != null) {
2159 <                ForkJoinTask<?> t; int b;
2084 >            long c; WorkQueue q; ForkJoinTask<?> t; int b;
2085 >            while ((t = w.nextLocalTask()) != null)
2086 >                t.doExec();
2087 >            if ((q = findNonEmptyStealQueue()) != null) {
2088                  if (!active) {      // re-establish active count
2161                    long c;
2089                      active = true;
2090                      do {} while (!U.compareAndSwapLong
2091 <                                 (this, CTL, c = ctl, c + AC_UNIT));
2091 >                                 (this, CTL, c = ctl,
2092 >                                  ((c & ~AC_MASK) |
2093 >                                   ((c & AC_MASK) + AC_UNIT))));
2094 >                }
2095 >                if ((b = q.base) - q.top < 0 && (t = q.pollAt(b)) != null) {
2096 >                    (w.currentSteal = t).doExec();
2097 >                    w.currentSteal = ps;
2098                  }
2166                if ((b = q.base) - q.top < 0 && (t = q.pollAt(b)) != null)
2167                    w.runSubtask(t);
2099              }
2100 <            else {
2101 <                long c;
2102 <                if (active) {       // decrement active count without queuing
2100 >            else if (active) {       // decrement active count without queuing
2101 >                long nc = ((c = ctl) & ~AC_MASK) | ((c & AC_MASK) - AC_UNIT);
2102 >                if ((int)(nc >> AC_SHIFT) + parallelism == 0)
2103 >                    break;          // bypass decrement-then-increment
2104 >                if (U.compareAndSwapLong(this, CTL, c, nc))
2105                      active = false;
2173                    do {} while (!U.compareAndSwapLong
2174                                 (this, CTL, c = ctl, c -= AC_UNIT));
2175                }
2176                else
2177                    c = ctl;        // re-increment on exit
2178                if ((int)(c >> AC_SHIFT) + parallelism == 0) {
2179                    do {} while (!U.compareAndSwapLong
2180                                 (this, CTL, c = ctl, c + AC_UNIT));
2181                    break;
2182                }
2183            }
2184        }
2185    }
2186
2187    /**
2188     * Restricted version of helpQuiescePool for non-FJ callers
2189     */
2190    static void externalHelpQuiescePool() {
2191        ForkJoinPool p; WorkQueue[] ws; WorkQueue q, sq;
2192        ForkJoinTask<?>[] a; int b;
2193        ForkJoinTask<?> t = null;
2194        int k = submitters.get().seed & SQMASK;
2195        if ((p = commonPool) != null &&
2196            (int)(p.ctl >> AC_SHIFT) < 0 &&
2197            (ws = p.workQueues) != null &&
2198            ws.length > (k &= p.submitMask) &&
2199            (q = ws[k]) != null) {
2200            while (q.top - q.base > 0) {
2201                if ((t = q.sharedPop()) != null)
2202                    break;
2106              }
2107 <            if (t == null && (sq = p.findNonEmptyStealQueue(q)) != null &&
2108 <                (b = sq.base) - sq.top < 0)
2109 <                t = sq.pollAt(b);
2110 <            if (t != null)
2111 <                t.doExec();
2107 >            else if ((int)((c = ctl) >> AC_SHIFT) + parallelism <= 0 &&
2108 >                     U.compareAndSwapLong
2109 >                     (this, CTL, c, ((c & ~AC_MASK) |
2110 >                                     ((c & AC_MASK) + AC_UNIT))))
2111 >                break;
2112          }
2113      }
2114  
# Line 2219 | Line 2122 | public class ForkJoinPool extends Abstra
2122              WorkQueue q; int b;
2123              if ((t = w.nextLocalTask()) != null)
2124                  return t;
2125 <            if ((q = findNonEmptyStealQueue(w)) == null)
2125 >            if ((q = findNonEmptyStealQueue()) == null)
2126                  return null;
2127              if ((b = q.base) - q.top < 0 && (t = q.pollAt(b)) != null)
2128                  return t;
# Line 2227 | Line 2130 | public class ForkJoinPool extends Abstra
2130      }
2131  
2132      /**
2133 <     * Returns the approximate (non-atomic) number of idle threads per
2134 <     * active thread to offset steal queue size for method
2135 <     * ForkJoinTask.getSurplusQueuedTaskCount().
2136 <     */
2137 <    final int idlePerActive() {
2138 <        // Approximate at powers of two for small values, saturate past 4
2139 <        int p = parallelism;
2140 <        int a = p + (int)(ctl >> AC_SHIFT);
2141 <        return (a > (p >>>= 1) ? 0 :
2142 <                a > (p >>>= 1) ? 1 :
2143 <                a > (p >>>= 1) ? 2 :
2144 <                a > (p >>>= 1) ? 4 :
2145 <                8);
2146 <    }
2147 <
2148 <    /**
2149 <     * Returns approximate submission queue length for the given caller
2150 <     */
2151 <    static int getEstimatedSubmitterQueueLength() {
2152 <        ForkJoinPool p; WorkQueue[] ws; WorkQueue q;
2153 <        int k = submitters.get().seed & SQMASK;
2154 <        return ((p = commonPool) != null &&
2155 <                p.runState >= 0 &&
2156 <                (ws = p.workQueues) != null &&
2157 <                ws.length > (k &= p.submitMask) &&
2158 <                (q = ws[k]) != null) ?
2159 <            q.queueSize() : 0;
2133 >     * Returns a cheap heuristic guide for task partitioning when
2134 >     * programmers, frameworks, tools, or languages have little or no
2135 >     * idea about task granularity.  In essence by offering this
2136 >     * method, we ask users only about tradeoffs in overhead vs
2137 >     * expected throughput and its variance, rather than how finely to
2138 >     * partition tasks.
2139 >     *
2140 >     * In a steady state strict (tree-structured) computation, each
2141 >     * thread makes available for stealing enough tasks for other
2142 >     * threads to remain active. Inductively, if all threads play by
2143 >     * the same rules, each thread should make available only a
2144 >     * constant number of tasks.
2145 >     *
2146 >     * The minimum useful constant is just 1. But using a value of 1
2147 >     * would require immediate replenishment upon each steal to
2148 >     * maintain enough tasks, which is infeasible.  Further,
2149 >     * partitionings/granularities of offered tasks should minimize
2150 >     * steal rates, which in general means that threads nearer the top
2151 >     * of computation tree should generate more than those nearer the
2152 >     * bottom. In perfect steady state, each thread is at
2153 >     * approximately the same level of computation tree. However,
2154 >     * producing extra tasks amortizes the uncertainty of progress and
2155 >     * diffusion assumptions.
2156 >     *
2157 >     * So, users will want to use values larger (but not much larger)
2158 >     * than 1 to both smooth over transient shortages and hedge
2159 >     * against uneven progress; as traded off against the cost of
2160 >     * extra task overhead. We leave the user to pick a threshold
2161 >     * value to compare with the results of this call to guide
2162 >     * decisions, but recommend values such as 3.
2163 >     *
2164 >     * When all threads are active, it is on average OK to estimate
2165 >     * surplus strictly locally. In steady-state, if one thread is
2166 >     * maintaining say 2 surplus tasks, then so are others. So we can
2167 >     * just use estimated queue length.  However, this strategy alone
2168 >     * leads to serious mis-estimates in some non-steady-state
2169 >     * conditions (ramp-up, ramp-down, other stalls). We can detect
2170 >     * many of these by further considering the number of "idle"
2171 >     * threads, that are known to have zero queued tasks, so
2172 >     * compensate by a factor of (#idle/#active) threads.
2173 >     *
2174 >     * Note: The approximation of #busy workers as #active workers is
2175 >     * not very good under current signalling scheme, and should be
2176 >     * improved.
2177 >     */
2178 >    static int getSurplusQueuedTaskCount() {
2179 >        Thread t; ForkJoinWorkerThread wt; ForkJoinPool pool; WorkQueue q;
2180 >        if (((t = Thread.currentThread()) instanceof ForkJoinWorkerThread)) {
2181 >            int p = (pool = (wt = (ForkJoinWorkerThread)t).pool).parallelism;
2182 >            int n = (q = wt.workQueue).top - q.base;
2183 >            int a = (int)(pool.ctl >> AC_SHIFT) + p;
2184 >            return n - (a > (p >>>= 1) ? 0 :
2185 >                        a > (p >>>= 1) ? 1 :
2186 >                        a > (p >>>= 1) ? 2 :
2187 >                        a > (p >>>= 1) ? 4 :
2188 >                        8);
2189 >        }
2190 >        return 0;
2191      }
2192  
2193      //  Termination
# Line 2273 | Line 2207 | public class ForkJoinPool extends Abstra
2207       * @return true if now terminating or terminated
2208       */
2209      private boolean tryTerminate(boolean now, boolean enable) {
2210 +        int ps;
2211 +        if (this == common)                        // cannot shut down
2212 +            return false;
2213 +        if ((ps = plock) >= 0) {                   // enable by setting plock
2214 +            if (!enable)
2215 +                return false;
2216 +            if ((ps & PL_LOCK) != 0 ||
2217 +                !U.compareAndSwapInt(this, PLOCK, ps, ps += PL_LOCK))
2218 +                ps = acquirePlock();
2219 +            int nps = ((ps + PL_LOCK) & ~SHUTDOWN) | SHUTDOWN;
2220 +            if (!U.compareAndSwapInt(this, PLOCK, ps, nps))
2221 +                releasePlock(nps);
2222 +        }
2223          for (long c;;) {
2224 <            if (((c = ctl) & STOP_BIT) != 0) {      // already terminating
2225 <                if ((short)(c >>> TC_SHIFT) == -parallelism) {
2226 <                    synchronized(this) {
2227 <                        notifyAll();                // signal when 0 workers
2224 >            if (((c = ctl) & STOP_BIT) != 0) {     // already terminating
2225 >                if ((short)(c >>> TC_SHIFT) + parallelism <= 0) {
2226 >                    synchronized (this) {
2227 >                        notifyAll();               // signal when 0 workers
2228                      }
2229                  }
2230                  return true;
2231              }
2232 <            if (runState >= 0) {                    // not yet enabled
2233 <                if (!enable)
2234 <                    return false;
2288 <                while (!U.compareAndSwapInt(this, MAINLOCK, 0, 1))
2289 <                    tryAwaitMainLock();
2290 <                try {
2291 <                    runState |= SHUTDOWN;
2292 <                } finally {
2293 <                    if (!U.compareAndSwapInt(this, MAINLOCK, 1, 0)) {
2294 <                        mainLock = 0;
2295 <                        synchronized (this) { notifyAll(); };
2296 <                    }
2297 <                }
2298 <            }
2299 <            if (!now) {                             // check if idle & no tasks
2300 <                if ((int)(c >> AC_SHIFT) != -parallelism ||
2301 <                    hasQueuedSubmissions())
2232 >            if (!now) {                            // check if idle & no tasks
2233 >                WorkQueue[] ws; WorkQueue w;
2234 >                if ((int)(c >> AC_SHIFT) + parallelism > 0)
2235                      return false;
2236 <                // Check for unqueued inactive workers. One pass suffices.
2237 <                WorkQueue[] ws = workQueues; WorkQueue w;
2238 <                if (ws != null) {
2239 <                    for (int i = 1; i < ws.length; i += 2) {
2240 <                        if ((w = ws[i]) != null && w.eventCount >= 0)
2236 >                if ((ws = workQueues) != null) {
2237 >                    for (int i = 0; i < ws.length; ++i) {
2238 >                        if ((w = ws[i]) != null &&
2239 >                            (!w.isEmpty() ||
2240 >                             ((i & 1) != 0 && w.eventCount >= 0))) {
2241 >                            signalWork(ws, w);
2242                              return false;
2243 +                        }
2244                      }
2245                  }
2246              }
2247              if (U.compareAndSwapLong(this, CTL, c, c | STOP_BIT)) {
2248                  for (int pass = 0; pass < 3; ++pass) {
2249 <                    WorkQueue[] ws = workQueues;
2250 <                    if (ws != null) {
2316 <                        WorkQueue w;
2249 >                    WorkQueue[] ws; WorkQueue w; Thread wt;
2250 >                    if ((ws = workQueues) != null) {
2251                          int n = ws.length;
2252                          for (int i = 0; i < n; ++i) {
2253                              if ((w = ws[i]) != null) {
2254 <                                w.runState = -1;
2254 >                                w.qlock = -1;
2255                                  if (pass > 0) {
2256                                      w.cancelAll();
2257 <                                    if (pass > 1)
2258 <                                        w.interruptOwner();
2257 >                                    if (pass > 1 && (wt = w.owner) != null) {
2258 >                                        if (!wt.isInterrupted()) {
2259 >                                            try {
2260 >                                                wt.interrupt();
2261 >                                            } catch (Throwable ignore) {
2262 >                                            }
2263 >                                        }
2264 >                                        U.unpark(wt);
2265 >                                    }
2266                                  }
2267                              }
2268                          }
2269                          // Wake up workers parked on event queue
2270                          int i, e; long cc; Thread p;
2271                          while ((e = (int)(cc = ctl) & E_MASK) != 0 &&
2272 <                               (i = e & SMASK) < n &&
2272 >                               (i = e & SMASK) < n && i >= 0 &&
2273                                 (w = ws[i]) != null) {
2274                              long nc = ((long)(w.nextWait & E_MASK) |
2275                                         ((cc + AC_UNIT) & AC_MASK) |
# Line 2336 | Line 2277 | public class ForkJoinPool extends Abstra
2277                              if (w.eventCount == (e | INT_SIGN) &&
2278                                  U.compareAndSwapLong(this, CTL, cc, nc)) {
2279                                  w.eventCount = (e + E_SEQ) & E_MASK;
2280 <                                w.runState = -1;
2280 >                                w.qlock = -1;
2281                                  if ((p = w.parker) != null)
2282                                      U.unpark(p);
2283                              }
# Line 2347 | Line 2288 | public class ForkJoinPool extends Abstra
2288          }
2289      }
2290  
2291 +    // external operations on common pool
2292 +
2293 +    /**
2294 +     * Returns common pool queue for a thread that has submitted at
2295 +     * least one task.
2296 +     */
2297 +    static WorkQueue commonSubmitterQueue() {
2298 +        Submitter z; ForkJoinPool p; WorkQueue[] ws; int m, r;
2299 +        return ((z = submitters.get()) != null &&
2300 +                (p = common) != null &&
2301 +                (ws = p.workQueues) != null &&
2302 +                (m = ws.length - 1) >= 0) ?
2303 +            ws[m & z.seed & SQMASK] : null;
2304 +    }
2305 +
2306 +    /**
2307 +     * Tries to pop the given task from submitter's queue in common pool.
2308 +     */
2309 +    final boolean tryExternalUnpush(ForkJoinTask<?> task) {
2310 +        WorkQueue joiner; ForkJoinTask<?>[] a; int m, s;
2311 +        Submitter z = submitters.get();
2312 +        WorkQueue[] ws = workQueues;
2313 +        boolean popped = false;
2314 +        if (z != null && ws != null && (m = ws.length - 1) >= 0 &&
2315 +            (joiner = ws[z.seed & m & SQMASK]) != null &&
2316 +            joiner.base != (s = joiner.top) &&
2317 +            (a = joiner.array) != null) {
2318 +            long j = (((a.length - 1) & (s - 1)) << ASHIFT) + ABASE;
2319 +            if (U.getObject(a, j) == task &&
2320 +                U.compareAndSwapInt(joiner, QLOCK, 0, 1)) {
2321 +                if (joiner.top == s && joiner.array == a &&
2322 +                    U.compareAndSwapObject(a, j, task, null)) {
2323 +                    joiner.top = s - 1;
2324 +                    popped = true;
2325 +                }
2326 +                joiner.qlock = 0;
2327 +            }
2328 +        }
2329 +        return popped;
2330 +    }
2331 +
2332 +    final int externalHelpComplete(CountedCompleter<?> task) {
2333 +        WorkQueue joiner; int m, j;
2334 +        Submitter z = submitters.get();
2335 +        WorkQueue[] ws = workQueues;
2336 +        int s = 0;
2337 +        if (z != null && ws != null && (m = ws.length - 1) >= 0 &&
2338 +            (joiner = ws[(j = z.seed) & m & SQMASK]) != null && task != null) {
2339 +            int scans = m + m + 1;
2340 +            long c = 0L;             // for stability check
2341 +            j |= 1;                  // poll odd queues
2342 +            for (int k = scans; ; j += 2) {
2343 +                WorkQueue q;
2344 +                if ((s = task.status) < 0)
2345 +                    break;
2346 +                else if (joiner.externalPopAndExecCC(task))
2347 +                    k = scans;
2348 +                else if ((s = task.status) < 0)
2349 +                    break;
2350 +                else if ((q = ws[j & m]) != null && q.pollAndExecCC(task))
2351 +                    k = scans;
2352 +                else if (--k < 0) {
2353 +                    if (c == (c = ctl))
2354 +                        break;
2355 +                    k = scans;
2356 +                }
2357 +            }
2358 +        }
2359 +        return s;
2360 +    }
2361 +
2362      // Exported methods
2363  
2364      // Constructors
# Line 2363 | Line 2375 | public class ForkJoinPool extends Abstra
2375       *         java.lang.RuntimePermission}{@code ("modifyThread")}
2376       */
2377      public ForkJoinPool() {
2378 <        this(Runtime.getRuntime().availableProcessors(),
2378 >        this(Math.min(MAX_CAP, Runtime.getRuntime().availableProcessors()),
2379               defaultForkJoinWorkerThreadFactory, null, false);
2380      }
2381  
# Line 2411 | Line 2423 | public class ForkJoinPool extends Abstra
2423       */
2424      public ForkJoinPool(int parallelism,
2425                          ForkJoinWorkerThreadFactory factory,
2426 <                        Thread.UncaughtExceptionHandler handler,
2426 >                        UncaughtExceptionHandler handler,
2427                          boolean asyncMode) {
2428 +        this(checkParallelism(parallelism),
2429 +             checkFactory(factory),
2430 +             handler,
2431 +             (asyncMode ? FIFO_QUEUE : LIFO_QUEUE),
2432 +             "ForkJoinPool-" + nextPoolId() + "-worker-");
2433          checkPermission();
2434 <        if (factory == null)
2435 <            throw new NullPointerException();
2434 >    }
2435 >
2436 >    private static int checkParallelism(int parallelism) {
2437          if (parallelism <= 0 || parallelism > MAX_CAP)
2438              throw new IllegalArgumentException();
2439 <        this.parallelism = parallelism;
2440 <        this.factory = factory;
2441 <        this.ueh = handler;
2442 <        this.localMode = asyncMode ? FIFO_QUEUE : LIFO_QUEUE;
2443 <        long np = (long)(-parallelism); // offset ctl counts
2444 <        this.ctl = ((np << AC_SHIFT) & AC_MASK) | ((np << TC_SHIFT) & TC_MASK);
2445 <        // Use nearest power 2 for workQueues size. See Hackers Delight sec 3.2.
2446 <        int n = parallelism - 1;
2429 <        n |= n >>> 1; n |= n >>> 2; n |= n >>> 4; n |= n >>> 8; n |= n >>> 16;
2430 <        this.submitMask = ((n + 1) << 1) - 1;
2431 <        int pn = poolNumberGenerator.incrementAndGet();
2432 <        StringBuilder sb = new StringBuilder("ForkJoinPool-");
2433 <        sb.append(Integer.toString(pn));
2434 <        sb.append("-worker-");
2435 <        this.workerNamePrefix = sb.toString();
2436 <        this.runState = 1;              // set init flag
2439 >        return parallelism;
2440 >    }
2441 >
2442 >    private static ForkJoinWorkerThreadFactory checkFactory
2443 >        (ForkJoinWorkerThreadFactory factory) {
2444 >        if (factory == null)
2445 >            throw new NullPointerException();
2446 >        return factory;
2447      }
2448  
2449      /**
2450 <     * Constructor for common pool, suitable only for static initialization.
2451 <     * Basically the same as above, but uses smallest possible initial footprint.
2452 <     */
2453 <    ForkJoinPool(int parallelism, int submitMask,
2454 <                 ForkJoinWorkerThreadFactory factory,
2455 <                 Thread.UncaughtExceptionHandler handler) {
2450 >     * Creates a {@code ForkJoinPool} with the given parameters, without
2451 >     * any security checks or parameter validation.  Invoked directly by
2452 >     * makeCommonPool.
2453 >     */
2454 >    private ForkJoinPool(int parallelism,
2455 >                         ForkJoinWorkerThreadFactory factory,
2456 >                         UncaughtExceptionHandler handler,
2457 >                         int mode,
2458 >                         String workerNamePrefix) {
2459 >        this.workerNamePrefix = workerNamePrefix;
2460          this.factory = factory;
2461          this.ueh = handler;
2462 <        this.submitMask = submitMask;
2463 <        this.parallelism = parallelism;
2464 <        long np = (long)(-parallelism);
2462 >        this.mode = (short)mode;
2463 >        this.parallelism = (short)parallelism;
2464 >        long np = (long)(-parallelism); // offset ctl counts
2465          this.ctl = ((np << AC_SHIFT) & AC_MASK) | ((np << TC_SHIFT) & TC_MASK);
2452        this.localMode = LIFO_QUEUE;
2453        this.workerNamePrefix = "ForkJoinPool.commonPool-worker-";
2454        this.runState = 1;
2466      }
2467  
2468      /**
2469 <     * Returns the common pool instance.
2469 >     * Returns the common pool instance. This pool is statically
2470 >     * constructed; its run state is unaffected by attempts to {@link
2471 >     * #shutdown} or {@link #shutdownNow}. However this pool and any
2472 >     * ongoing processing are automatically terminated upon program
2473 >     * {@link System#exit}.  Any program that relies on asynchronous
2474 >     * task processing to complete before program termination should
2475 >     * invoke {@code commonPool().}{@link #awaitQuiescence awaitQuiescence},
2476 >     * before exit.
2477       *
2478       * @return the common pool instance
2479 +     * @since 1.8
2480       */
2481      public static ForkJoinPool commonPool() {
2482 <        ForkJoinPool p;
2483 <        if ((p = commonPool) == null)
2465 <            throw new Error("Common Pool Unavailable");
2466 <        return p;
2482 >        // assert common != null : "static init error";
2483 >        return common;
2484      }
2485  
2486      // Execution methods
# Line 2487 | Line 2504 | public class ForkJoinPool extends Abstra
2504      public <T> T invoke(ForkJoinTask<T> task) {
2505          if (task == null)
2506              throw new NullPointerException();
2507 <        doSubmit(task);
2507 >        externalPush(task);
2508          return task.join();
2509      }
2510  
# Line 2502 | Line 2519 | public class ForkJoinPool extends Abstra
2519      public void execute(ForkJoinTask<?> task) {
2520          if (task == null)
2521              throw new NullPointerException();
2522 <        doSubmit(task);
2522 >        externalPush(task);
2523      }
2524  
2525      // AbstractExecutorService methods
# Line 2519 | Line 2536 | public class ForkJoinPool extends Abstra
2536          if (task instanceof ForkJoinTask<?>) // avoid re-wrap
2537              job = (ForkJoinTask<?>) task;
2538          else
2539 <            job = new ForkJoinTask.AdaptedRunnableAction(task);
2540 <        doSubmit(job);
2539 >            job = new ForkJoinTask.RunnableExecuteAction(task);
2540 >        externalPush(job);
2541      }
2542  
2543      /**
# Line 2535 | Line 2552 | public class ForkJoinPool extends Abstra
2552      public <T> ForkJoinTask<T> submit(ForkJoinTask<T> task) {
2553          if (task == null)
2554              throw new NullPointerException();
2555 <        doSubmit(task);
2555 >        externalPush(task);
2556          return task;
2557      }
2558  
# Line 2546 | Line 2563 | public class ForkJoinPool extends Abstra
2563       */
2564      public <T> ForkJoinTask<T> submit(Callable<T> task) {
2565          ForkJoinTask<T> job = new ForkJoinTask.AdaptedCallable<T>(task);
2566 <        doSubmit(job);
2566 >        externalPush(job);
2567          return job;
2568      }
2569  
# Line 2557 | Line 2574 | public class ForkJoinPool extends Abstra
2574       */
2575      public <T> ForkJoinTask<T> submit(Runnable task, T result) {
2576          ForkJoinTask<T> job = new ForkJoinTask.AdaptedRunnable<T>(task, result);
2577 <        doSubmit(job);
2577 >        externalPush(job);
2578          return job;
2579      }
2580  
# Line 2574 | Line 2591 | public class ForkJoinPool extends Abstra
2591              job = (ForkJoinTask<?>) task;
2592          else
2593              job = new ForkJoinTask.AdaptedRunnableAction(task);
2594 <        doSubmit(job);
2594 >        externalPush(job);
2595          return job;
2596      }
2597  
# Line 2586 | Line 2603 | public class ForkJoinPool extends Abstra
2603          // In previous versions of this class, this method constructed
2604          // a task to run ForkJoinTask.invokeAll, but now external
2605          // invocation of multiple tasks is at least as efficient.
2606 <        List<ForkJoinTask<T>> fs = new ArrayList<ForkJoinTask<T>>(tasks.size());
2590 <        // Workaround needed because method wasn't declared with
2591 <        // wildcards in return type but should have been.
2592 <        @SuppressWarnings({"unchecked", "rawtypes"})
2593 <            List<Future<T>> futures = (List<Future<T>>) (List) fs;
2606 >        ArrayList<Future<T>> futures = new ArrayList<Future<T>>(tasks.size());
2607  
2608          boolean done = false;
2609          try {
2610              for (Callable<T> t : tasks) {
2611                  ForkJoinTask<T> f = new ForkJoinTask.AdaptedCallable<T>(t);
2612 <                doSubmit(f);
2613 <                fs.add(f);
2612 >                futures.add(f);
2613 >                externalPush(f);
2614              }
2615 <            for (ForkJoinTask<T> f : fs)
2616 <                f.quietlyJoin();
2615 >            for (int i = 0, size = futures.size(); i < size; i++)
2616 >                ((ForkJoinTask<?>)futures.get(i)).quietlyJoin();
2617              done = true;
2618              return futures;
2619          } finally {
2620              if (!done)
2621 <                for (ForkJoinTask<T> f : fs)
2622 <                    f.cancel(false);
2621 >                for (int i = 0, size = futures.size(); i < size; i++)
2622 >                    futures.get(i).cancel(false);
2623          }
2624      }
2625  
# Line 2625 | Line 2638 | public class ForkJoinPool extends Abstra
2638       *
2639       * @return the handler, or {@code null} if none
2640       */
2641 <    public Thread.UncaughtExceptionHandler getUncaughtExceptionHandler() {
2641 >    public UncaughtExceptionHandler getUncaughtExceptionHandler() {
2642          return ueh;
2643      }
2644  
# Line 2635 | Line 2648 | public class ForkJoinPool extends Abstra
2648       * @return the targeted parallelism level of this pool
2649       */
2650      public int getParallelism() {
2651 <        return parallelism;
2651 >        int par;
2652 >        return ((par = parallelism) > 0) ? par : 1;
2653      }
2654  
2655      /**
2656       * Returns the targeted parallelism level of the common pool.
2657       *
2658       * @return the targeted parallelism level of the common pool
2659 +     * @since 1.8
2660       */
2661      public static int getCommonPoolParallelism() {
2662 <        return commonPoolParallelism;
2662 >        return commonParallelism;
2663      }
2664  
2665      /**
# Line 2666 | Line 2681 | public class ForkJoinPool extends Abstra
2681       * @return {@code true} if this pool uses async mode
2682       */
2683      public boolean getAsyncMode() {
2684 <        return localMode != 0;
2684 >        return mode == FIFO_QUEUE;
2685      }
2686  
2687      /**
# Line 2713 | Line 2728 | public class ForkJoinPool extends Abstra
2728       * @return {@code true} if all threads are currently idle
2729       */
2730      public boolean isQuiescent() {
2731 <        return (int)(ctl >> AC_SHIFT) + parallelism == 0;
2731 >        return parallelism + (int)(ctl >> AC_SHIFT) <= 0;
2732      }
2733  
2734      /**
# Line 2733 | Line 2748 | public class ForkJoinPool extends Abstra
2748          if ((ws = workQueues) != null) {
2749              for (int i = 1; i < ws.length; i += 2) {
2750                  if ((w = ws[i]) != null)
2751 <                    count += w.totalSteals;
2751 >                    count += w.nsteals;
2752              }
2753          }
2754          return count;
# Line 2869 | Line 2884 | public class ForkJoinPool extends Abstra
2884                          qs += size;
2885                      else {
2886                          qt += size;
2887 <                        st += w.totalSteals;
2887 >                        st += w.nsteals;
2888                          if (w.isApparentlyUnblocked())
2889                              ++rc;
2890                      }
# Line 2885 | Line 2900 | public class ForkJoinPool extends Abstra
2900          if ((c & STOP_BIT) != 0)
2901              level = (tc == 0) ? "Terminated" : "Terminating";
2902          else
2903 <            level = runState < 0 ? "Shutting down" : "Running";
2903 >            level = plock < 0 ? "Shutting down" : "Running";
2904          return super.toString() +
2905              "[" + level +
2906              ", parallelism = " + pc +
# Line 2902 | Line 2917 | public class ForkJoinPool extends Abstra
2917       * Possibly initiates an orderly shutdown in which previously
2918       * submitted tasks are executed, but no new tasks will be
2919       * accepted. Invocation has no effect on execution state if this
2920 <     * is the {@link #commonPool}, and no additional effect if
2920 >     * is the {@link #commonPool()}, and no additional effect if
2921       * already shut down.  Tasks that are in the process of being
2922       * submitted concurrently during the course of this method may or
2923       * may not be rejected.
# Line 2914 | Line 2929 | public class ForkJoinPool extends Abstra
2929       */
2930      public void shutdown() {
2931          checkPermission();
2932 <        if (this != commonPool)
2918 <            tryTerminate(false, true);
2932 >        tryTerminate(false, true);
2933      }
2934  
2935      /**
2936       * Possibly attempts to cancel and/or stop all tasks, and reject
2937       * all subsequently submitted tasks.  Invocation has no effect on
2938 <     * execution state if this is the {@link #commonPool}, and no
2938 >     * execution state if this is the {@link #commonPool()}, and no
2939       * additional effect if already shut down. Otherwise, tasks that
2940       * are in the process of being submitted or executed concurrently
2941       * during the course of this method may or may not be
# Line 2938 | Line 2952 | public class ForkJoinPool extends Abstra
2952       */
2953      public List<Runnable> shutdownNow() {
2954          checkPermission();
2955 <        if (this != commonPool)
2942 <            tryTerminate(true, true);
2955 >        tryTerminate(true, true);
2956          return Collections.emptyList();
2957      }
2958  
# Line 2951 | Line 2964 | public class ForkJoinPool extends Abstra
2964      public boolean isTerminated() {
2965          long c = ctl;
2966          return ((c & STOP_BIT) != 0L &&
2967 <                (short)(c >>> TC_SHIFT) == -parallelism);
2967 >                (short)(c >>> TC_SHIFT) + parallelism <= 0);
2968      }
2969  
2970      /**
# Line 2959 | Line 2972 | public class ForkJoinPool extends Abstra
2972       * commenced but not yet completed.  This method may be useful for
2973       * debugging. A return of {@code true} reported a sufficient
2974       * period after shutdown may indicate that submitted tasks have
2975 <     * ignored or suppressed interruption, or are waiting for IO,
2975 >     * ignored or suppressed interruption, or are waiting for I/O,
2976       * causing this executor not to properly terminate. (See the
2977       * advisory notes for class {@link ForkJoinTask} stating that
2978       * tasks should not normally entail blocking operations.  But if
# Line 2970 | Line 2983 | public class ForkJoinPool extends Abstra
2983      public boolean isTerminating() {
2984          long c = ctl;
2985          return ((c & STOP_BIT) != 0L &&
2986 <                (short)(c >>> TC_SHIFT) != -parallelism);
2986 >                (short)(c >>> TC_SHIFT) + parallelism > 0);
2987      }
2988  
2989      /**
# Line 2979 | Line 2992 | public class ForkJoinPool extends Abstra
2992       * @return {@code true} if this pool has been shut down
2993       */
2994      public boolean isShutdown() {
2995 <        return runState < 0;
2995 >        return plock < 0;
2996      }
2997  
2998      /**
2999 <     * Blocks until all tasks have completed execution after a shutdown
3000 <     * request, or the timeout occurs, or the current thread is
3001 <     * interrupted, whichever happens first.
2999 >     * Blocks until all tasks have completed execution after a
3000 >     * shutdown request, or the timeout occurs, or the current thread
3001 >     * is interrupted, whichever happens first. Because the {@link
3002 >     * #commonPool()} never terminates until program shutdown, when
3003 >     * applied to the common pool, this method is equivalent to {@link
3004 >     * #awaitQuiescence(long, TimeUnit)} but always returns {@code false}.
3005       *
3006       * @param timeout the maximum time to wait
3007       * @param unit the time unit of the timeout argument
# Line 2995 | Line 3011 | public class ForkJoinPool extends Abstra
3011       */
3012      public boolean awaitTermination(long timeout, TimeUnit unit)
3013          throws InterruptedException {
3014 +        if (Thread.interrupted())
3015 +            throw new InterruptedException();
3016 +        if (this == common) {
3017 +            awaitQuiescence(timeout, unit);
3018 +            return false;
3019 +        }
3020          long nanos = unit.toNanos(timeout);
3021          if (isTerminated())
3022              return true;
3023 +        if (nanos <= 0L)
3024 +            return false;
3025 +        long deadline = System.nanoTime() + nanos;
3026 +        synchronized (this) {
3027 +            for (;;) {
3028 +                if (isTerminated())
3029 +                    return true;
3030 +                if (nanos <= 0L)
3031 +                    return false;
3032 +                long millis = TimeUnit.NANOSECONDS.toMillis(nanos);
3033 +                wait(millis > 0L ? millis : 1L);
3034 +                nanos = deadline - System.nanoTime();
3035 +            }
3036 +        }
3037 +    }
3038 +
3039 +    /**
3040 +     * If called by a ForkJoinTask operating in this pool, equivalent
3041 +     * in effect to {@link ForkJoinTask#helpQuiesce}. Otherwise,
3042 +     * waits and/or attempts to assist performing tasks until this
3043 +     * pool {@link #isQuiescent} or the indicated timeout elapses.
3044 +     *
3045 +     * @param timeout the maximum time to wait
3046 +     * @param unit the time unit of the timeout argument
3047 +     * @return {@code true} if quiescent; {@code false} if the
3048 +     * timeout elapsed.
3049 +     */
3050 +    public boolean awaitQuiescence(long timeout, TimeUnit unit) {
3051 +        long nanos = unit.toNanos(timeout);
3052 +        ForkJoinWorkerThread wt;
3053 +        Thread thread = Thread.currentThread();
3054 +        if ((thread instanceof ForkJoinWorkerThread) &&
3055 +            (wt = (ForkJoinWorkerThread)thread).pool == this) {
3056 +            helpQuiescePool(wt.workQueue);
3057 +            return true;
3058 +        }
3059          long startTime = System.nanoTime();
3060 <        boolean terminated = false;
3061 <        synchronized(this) {
3062 <            for (long waitTime = nanos, millis = 0L;;) {
3063 <                if (terminated = isTerminated() ||
3064 <                    waitTime <= 0L ||
3065 <                    (millis = unit.toMillis(waitTime)) <= 0L)
3060 >        WorkQueue[] ws;
3061 >        int r = 0, m;
3062 >        boolean found = true;
3063 >        while (!isQuiescent() && (ws = workQueues) != null &&
3064 >               (m = ws.length - 1) >= 0) {
3065 >            if (!found) {
3066 >                if ((System.nanoTime() - startTime) > nanos)
3067 >                    return false;
3068 >                Thread.yield(); // cannot block
3069 >            }
3070 >            found = false;
3071 >            for (int j = (m + 1) << 2; j >= 0; --j) {
3072 >                ForkJoinTask<?> t; WorkQueue q; int b;
3073 >                if ((q = ws[r++ & m]) != null && (b = q.base) - q.top < 0) {
3074 >                    found = true;
3075 >                    if ((t = q.pollAt(b)) != null)
3076 >                        t.doExec();
3077                      break;
3078 <                wait(millis);
3010 <                waitTime = nanos - (System.nanoTime() - startTime);
3078 >                }
3079              }
3080          }
3081 <        return terminated;
3081 >        return true;
3082 >    }
3083 >
3084 >    /**
3085 >     * Waits and/or attempts to assist performing tasks indefinitely
3086 >     * until the {@link #commonPool()} {@link #isQuiescent}.
3087 >     */
3088 >    static void quiesceCommonPool() {
3089 >        common.awaitQuiescence(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
3090      }
3091  
3092      /**
# Line 3022 | Line 3098 | public class ForkJoinPool extends Abstra
3098       * not necessary. Method {@code block} blocks the current thread
3099       * if necessary (perhaps internally invoking {@code isReleasable}
3100       * before actually blocking). These actions are performed by any
3101 <     * thread invoking {@link ForkJoinPool#managedBlock}.  The
3102 <     * unusual methods in this API accommodate synchronizers that may,
3103 <     * but don't usually, block for long periods. Similarly, they
3101 >     * thread invoking {@link ForkJoinPool#managedBlock(ManagedBlocker)}.
3102 >     * The unusual methods in this API accommodate synchronizers that
3103 >     * may, but don't usually, block for long periods. Similarly, they
3104       * allow more efficient internal handling of cases in which
3105       * additional workers may be, but usually are not, needed to
3106       * ensure sufficient parallelism.  Toward this end,
# Line 3082 | Line 3158 | public class ForkJoinPool extends Abstra
3158  
3159          /**
3160           * Returns {@code true} if blocking is unnecessary.
3161 +         * @return {@code true} if blocking is unnecessary
3162           */
3163          boolean isReleasable();
3164      }
# Line 3109 | Line 3186 | public class ForkJoinPool extends Abstra
3186      public static void managedBlock(ManagedBlocker blocker)
3187          throws InterruptedException {
3188          Thread t = Thread.currentThread();
3189 <        ForkJoinPool p = ((t instanceof ForkJoinWorkerThread) ?
3190 <                          ((ForkJoinWorkerThread)t).pool : null);
3191 <        while (!blocker.isReleasable()) {
3192 <            if (p == null || p.tryCompensate(null, blocker)) {
3193 <                try {
3194 <                    do {} while (!blocker.isReleasable() && !blocker.block());
3195 <                } finally {
3196 <                    if (p != null)
3189 >        if (t instanceof ForkJoinWorkerThread) {
3190 >            ForkJoinPool p = ((ForkJoinWorkerThread)t).pool;
3191 >            while (!blocker.isReleasable()) {
3192 >                if (p.tryCompensate(p.ctl)) {
3193 >                    try {
3194 >                        do {} while (!blocker.isReleasable() &&
3195 >                                     !blocker.block());
3196 >                    } finally {
3197                          p.incrementActiveCount();
3198 +                    }
3199 +                    break;
3200                  }
3122                break;
3201              }
3202          }
3203 +        else {
3204 +            do {} while (!blocker.isReleasable() &&
3205 +                         !blocker.block());
3206 +        }
3207      }
3208  
3209      // AbstractExecutorService overrides.  These rely on undocumented
# Line 3142 | Line 3224 | public class ForkJoinPool extends Abstra
3224      private static final long PARKBLOCKER;
3225      private static final int ABASE;
3226      private static final int ASHIFT;
3145    private static final long NEXTWORKERNUMBER;
3227      private static final long STEALCOUNT;
3228 <    private static final long MAINLOCK;
3228 >    private static final long PLOCK;
3229 >    private static final long INDEXSEED;
3230 >    private static final long QBASE;
3231 >    private static final long QLOCK;
3232  
3233      static {
3234 <        poolNumberGenerator = new AtomicInteger();
3151 <        nextSubmitterSeed = new AtomicInteger(0x55555555);
3152 <        modifyThreadPermission = new RuntimePermission("modifyThread");
3153 <        defaultForkJoinWorkerThreadFactory =
3154 <            new DefaultForkJoinWorkerThreadFactory();
3155 <        submitters = new ThreadSubmitter();
3156 <        int s;
3234 >        // initialize field offsets for CAS etc
3235          try {
3236              U = getUnsafe();
3237              Class<?> k = ForkJoinPool.class;
3160            Class<?> ak = ForkJoinTask[].class;
3238              CTL = U.objectFieldOffset
3239                  (k.getDeclaredField("ctl"));
3163            NEXTWORKERNUMBER = U.objectFieldOffset
3164                (k.getDeclaredField("nextWorkerNumber"));
3240              STEALCOUNT = U.objectFieldOffset
3241                  (k.getDeclaredField("stealCount"));
3242 <            MAINLOCK = U.objectFieldOffset
3243 <                (k.getDeclaredField("mainLock"));
3242 >            PLOCK = U.objectFieldOffset
3243 >                (k.getDeclaredField("plock"));
3244 >            INDEXSEED = U.objectFieldOffset
3245 >                (k.getDeclaredField("indexSeed"));
3246              Class<?> tk = Thread.class;
3247              PARKBLOCKER = U.objectFieldOffset
3248                  (tk.getDeclaredField("parkBlocker"));
3249 +            Class<?> wk = WorkQueue.class;
3250 +            QBASE = U.objectFieldOffset
3251 +                (wk.getDeclaredField("base"));
3252 +            QLOCK = U.objectFieldOffset
3253 +                (wk.getDeclaredField("qlock"));
3254 +            Class<?> ak = ForkJoinTask[].class;
3255              ABASE = U.arrayBaseOffset(ak);
3256 <            s = U.arrayIndexScale(ak);
3257 <            ASHIFT = 31 - Integer.numberOfLeadingZeros(s);
3258 <        } catch (Exception e) {
3259 <            throw new Error(e);
3177 <        }
3178 <        if ((s & (s-1)) != 0)
3179 <            throw new Error("data type scale not a power of two");
3180 <        try { // Establish common pool
3181 <            String pp = System.getProperty(propPrefix + "parallelism");
3182 <            String fp = System.getProperty(propPrefix + "threadFactory");
3183 <            String up = System.getProperty(propPrefix + "exceptionHandler");
3184 <            ForkJoinWorkerThreadFactory fac = (fp == null) ?
3185 <                defaultForkJoinWorkerThreadFactory :
3186 <                ((ForkJoinWorkerThreadFactory)ClassLoader.
3187 <                 getSystemClassLoader().loadClass(fp).newInstance());
3188 <            Thread.UncaughtExceptionHandler ueh = (up == null)? null :
3189 <                ((Thread.UncaughtExceptionHandler)ClassLoader.
3190 <                 getSystemClassLoader().loadClass(up).newInstance());
3191 <            int par;
3192 <            if ((pp == null || (par = Integer.parseInt(pp)) <= 0))
3193 <                par = Runtime.getRuntime().availableProcessors();
3194 <            if (par > MAX_CAP)
3195 <                par = MAX_CAP;
3196 <            commonPoolParallelism = par;
3197 <            int n = par - 1; // precompute submit mask
3198 <            n |= n >>> 1; n |= n >>> 2; n |= n >>> 4;
3199 <            n |= n >>> 8; n |= n >>> 16;
3200 <            int mask = ((n + 1) << 1) - 1;
3201 <            commonPool = new ForkJoinPool(par, mask, fac, ueh);
3256 >            int scale = U.arrayIndexScale(ak);
3257 >            if ((scale & (scale - 1)) != 0)
3258 >                throw new Error("data type scale not a power of two");
3259 >            ASHIFT = 31 - Integer.numberOfLeadingZeros(scale);
3260          } catch (Exception e) {
3261              throw new Error(e);
3262          }
3263 +
3264 +        submitters = new ThreadLocal<Submitter>();
3265 +        defaultForkJoinWorkerThreadFactory =
3266 +            new DefaultForkJoinWorkerThreadFactory();
3267 +        modifyThreadPermission = new RuntimePermission("modifyThread");
3268 +
3269 +        common = java.security.AccessController.doPrivileged
3270 +            (new java.security.PrivilegedAction<ForkJoinPool>() {
3271 +                public ForkJoinPool run() { return makeCommonPool(); }});
3272 +        int par = common.parallelism; // report 1 even if threads disabled
3273 +        commonParallelism = par > 0 ? par : 1;
3274 +    }
3275 +
3276 +    /**
3277 +     * Creates and returns the common pool, respecting user settings
3278 +     * specified via system properties.
3279 +     */
3280 +    private static ForkJoinPool makeCommonPool() {
3281 +        int parallelism = -1;
3282 +        ForkJoinWorkerThreadFactory factory
3283 +            = defaultForkJoinWorkerThreadFactory;
3284 +        UncaughtExceptionHandler handler = null;
3285 +        try {  // ignore exceptions in accessing/parsing properties
3286 +            String pp = System.getProperty
3287 +                ("java.util.concurrent.ForkJoinPool.common.parallelism");
3288 +            String fp = System.getProperty
3289 +                ("java.util.concurrent.ForkJoinPool.common.threadFactory");
3290 +            String hp = System.getProperty
3291 +                ("java.util.concurrent.ForkJoinPool.common.exceptionHandler");
3292 +            if (pp != null)
3293 +                parallelism = Integer.parseInt(pp);
3294 +            if (fp != null)
3295 +                factory = ((ForkJoinWorkerThreadFactory)ClassLoader.
3296 +                           getSystemClassLoader().loadClass(fp).newInstance());
3297 +            if (hp != null)
3298 +                handler = ((UncaughtExceptionHandler)ClassLoader.
3299 +                           getSystemClassLoader().loadClass(hp).newInstance());
3300 +        } catch (Exception ignore) {
3301 +        }
3302 +
3303 +        if (parallelism < 0 && // default 1 less than #cores
3304 +            (parallelism = Runtime.getRuntime().availableProcessors() - 1) < 0)
3305 +            parallelism = 0;
3306 +        if (parallelism > MAX_CAP)
3307 +            parallelism = MAX_CAP;
3308 +        return new ForkJoinPool(parallelism, factory, handler, LIFO_QUEUE,
3309 +                                "ForkJoinPool.commonPool-worker-");
3310      }
3311  
3312      /**
# Line 3214 | Line 3319 | public class ForkJoinPool extends Abstra
3319      private static sun.misc.Unsafe getUnsafe() {
3320          try {
3321              return sun.misc.Unsafe.getUnsafe();
3322 <        } catch (SecurityException se) {
3323 <            try {
3324 <                return java.security.AccessController.doPrivileged
3325 <                    (new java.security
3326 <                     .PrivilegedExceptionAction<sun.misc.Unsafe>() {
3327 <                        public sun.misc.Unsafe run() throws Exception {
3328 <                            java.lang.reflect.Field f = sun.misc
3329 <                                .Unsafe.class.getDeclaredField("theUnsafe");
3330 <                            f.setAccessible(true);
3331 <                            return (sun.misc.Unsafe) f.get(null);
3332 <                        }});
3333 <            } catch (java.security.PrivilegedActionException e) {
3334 <                throw new RuntimeException("Could not initialize intrinsics",
3335 <                                           e.getCause());
3336 <            }
3322 >        } catch (SecurityException tryReflectionInstead) {}
3323 >        try {
3324 >            return java.security.AccessController.doPrivileged
3325 >            (new java.security.PrivilegedExceptionAction<sun.misc.Unsafe>() {
3326 >                public sun.misc.Unsafe run() throws Exception {
3327 >                    Class<sun.misc.Unsafe> k = sun.misc.Unsafe.class;
3328 >                    for (java.lang.reflect.Field f : k.getDeclaredFields()) {
3329 >                        f.setAccessible(true);
3330 >                        Object x = f.get(null);
3331 >                        if (k.isInstance(x))
3332 >                            return k.cast(x);
3333 >                    }
3334 >                    throw new NoSuchFieldError("the Unsafe");
3335 >                }});
3336 >        } catch (java.security.PrivilegedActionException e) {
3337 >            throw new RuntimeException("Could not initialize intrinsics",
3338 >                                       e.getCause());
3339          }
3340      }
3234
3341   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines