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.2 by jsr166, Mon Aug 13 18:25:53 2012 UTC vs.
Revision 1.61 by jsr166, Sun Jul 14 19:55:05 2013 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines