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

Comparing jsr166/src/jsr166y/ForkJoinPool.java (file contents):
Revision 1.92 by dl, Tue Feb 22 10:50:51 2011 UTC vs.
Revision 1.131 by jsr166, Tue Aug 14 06:00:55 2012 UTC

# Line 1 | Line 1
1   /*
2   * Written by Doug Lea with assistance from members of JCP JSR-166
3   * Expert Group and released to the public domain, as explained at
4 < * http://creativecommons.org/licenses/publicdomain
4 > * http://creativecommons.org/publicdomain/zero/1.0/
5   */
6  
7   package jsr166y;
8
8   import java.util.ArrayList;
9   import java.util.Arrays;
10   import java.util.Collection;
# Line 19 | Line 18 | import java.util.concurrent.Future;
18   import java.util.concurrent.RejectedExecutionException;
19   import java.util.concurrent.RunnableFuture;
20   import java.util.concurrent.TimeUnit;
22 import java.util.concurrent.TimeoutException;
21   import java.util.concurrent.atomic.AtomicInteger;
22 < import java.util.concurrent.locks.LockSupport;
23 < import java.util.concurrent.locks.ReentrantLock;
22 > import java.util.concurrent.atomic.AtomicLong;
23 > import java.util.concurrent.locks.AbstractQueuedSynchronizer;
24   import java.util.concurrent.locks.Condition;
25  
26   /**
# Line 34 | Line 32 | import java.util.concurrent.locks.Condit
32   * <p>A {@code ForkJoinPool} differs from other kinds of {@link
33   * ExecutorService} mainly by virtue of employing
34   * <em>work-stealing</em>: all threads in the pool attempt to find and
35 < * execute subtasks created by other active tasks (eventually blocking
36 < * waiting for work if none exist). This enables efficient processing
37 < * when most tasks spawn other subtasks (as do most {@code
38 < * ForkJoinTask}s). When setting <em>asyncMode</em> to true in
39 < * constructors, {@code ForkJoinPool}s may also be appropriate for use
40 < * with event-style tasks that are never joined.
35 > * execute tasks submitted to the pool and/or created by other active
36 > * tasks (eventually blocking waiting for work if none exist). This
37 > * enables efficient processing when most tasks spawn other subtasks
38 > * (as do most {@code ForkJoinTask}s), as well as when many small
39 > * tasks are submitted to the pool from external clients.  Especially
40 > * when setting <em>asyncMode</em> to true in constructors, {@code
41 > * ForkJoinPool}s may also be appropriate for use with event-style
42 > * tasks that are never joined.
43   *
44   * <p>A {@code ForkJoinPool} is constructed with a given target
45   * parallelism level; by default, equal to the number of available
# Line 59 | Line 59 | import java.util.concurrent.locks.Condit
59   * convenient form for informal monitoring.
60   *
61   * <p> As is the case with other ExecutorServices, there are three
62 < * main task execution methods summarized in the following
63 < * table. These are designed to be used by clients not already engaged
64 < * in fork/join computations in the current pool.  The main forms of
65 < * these methods accept instances of {@code ForkJoinTask}, but
66 < * overloaded forms also allow mixed execution of plain {@code
62 > * main task execution methods summarized in the following table.
63 > * These are designed to be used primarily by clients not already
64 > * engaged in fork/join computations in the current pool.  The main
65 > * forms of these methods accept instances of {@code ForkJoinTask},
66 > * but overloaded forms also allow mixed execution of plain {@code
67   * Runnable}- or {@code Callable}- based activities as well.  However,
68 < * tasks that are already executing in a pool should normally
69 < * <em>NOT</em> use these pool execution methods, but instead use the
70 < * within-computation forms listed in the table.
68 > * tasks that are already executing in a pool should normally instead
69 > * use the within-computation forms listed in the table unless using
70 > * async event-style tasks that are not usually joined, in which case
71 > * there is little difference among choice of methods.
72   *
73   * <table BORDER CELLPADDING=3 CELLSPACING=1>
74   *  <tr>
# Line 102 | Line 103 | import java.util.concurrent.locks.Condit
103   * daemon} mode, there is typically no need to explicitly {@link
104   * #shutdown} such a pool upon program exit.
105   *
106 < * <pre>
106 > *  <pre> {@code
107   * static final ForkJoinPool mainPool = new ForkJoinPool();
108   * ...
109   * public void sort(long[] array) {
110   *   mainPool.invoke(new SortTask(array, 0, array.length));
111 < * }
111 < * </pre>
111 > * }}</pre>
112   *
113   * <p><b>Implementation notes</b>: This implementation restricts the
114   * maximum number of running threads to 32767. Attempts to create
# Line 127 | Line 127 | public class ForkJoinPool extends Abstra
127      /*
128       * Implementation Overview
129       *
130 <     * This class provides the central bookkeeping and control for a
131 <     * set of worker threads: Submissions from non-FJ threads enter
132 <     * into a submission queue. Workers take these tasks and typically
133 <     * split them into subtasks that may be stolen by other workers.
134 <     * Preference rules give first priority to processing tasks from
135 <     * their own queues (LIFO or FIFO, depending on mode), then to
136 <     * randomized FIFO steals of tasks in other worker queues, and
137 <     * lastly to new submissions.
130 >     * This class and its nested classes provide the main
131 >     * functionality and control for a set of worker threads:
132 >     * Submissions from non-FJ threads enter into submission queues.
133 >     * Workers take these tasks and typically split them into subtasks
134 >     * that may be stolen by other workers.  Preference rules give
135 >     * first priority to processing tasks from their own queues (LIFO
136 >     * or FIFO, depending on mode), then to randomized FIFO steals of
137 >     * tasks in other queues.
138 >     *
139 >     * WorkQueues
140 >     * ==========
141 >     *
142 >     * Most operations occur within work-stealing queues (in nested
143 >     * class WorkQueue).  These are special forms of Deques that
144 >     * support only three of the four possible end-operations -- push,
145 >     * pop, and poll (aka steal), under the further constraints that
146 >     * push and pop are called only from the owning thread (or, as
147 >     * extended here, under a lock), while poll may be called from
148 >     * other threads.  (If you are unfamiliar with them, you probably
149 >     * want to read Herlihy and Shavit's book "The Art of
150 >     * Multiprocessor programming", chapter 16 describing these in
151 >     * more detail before proceeding.)  The main work-stealing queue
152 >     * design is roughly similar to those in the papers "Dynamic
153 >     * Circular Work-Stealing Deque" by Chase and Lev, SPAA 2005
154 >     * (http://research.sun.com/scalable/pubs/index.html) and
155 >     * "Idempotent work stealing" by Michael, Saraswat, and Vechev,
156 >     * PPoPP 2009 (http://portal.acm.org/citation.cfm?id=1504186).
157 >     * The main differences ultimately stem from GC requirements that
158 >     * we null out taken slots as soon as we can, to maintain as small
159 >     * a footprint as possible even in programs generating huge
160 >     * numbers of tasks. To accomplish this, we shift the CAS
161 >     * arbitrating pop vs poll (steal) from being on the indices
162 >     * ("base" and "top") to the slots themselves.  So, both a
163 >     * successful pop and poll mainly entail a CAS of a slot from
164 >     * non-null to null.  Because we rely on CASes of references, we
165 >     * do not need tag bits on base or top.  They are simple ints as
166 >     * used in any circular array-based queue (see for example
167 >     * ArrayDeque).  Updates to the indices must still be ordered in a
168 >     * way that guarantees that top == base means the queue is empty,
169 >     * but otherwise may err on the side of possibly making the queue
170 >     * appear nonempty when a push, pop, or poll have not fully
171 >     * committed. Note that this means that the poll operation,
172 >     * considered individually, is not wait-free. One thief cannot
173 >     * successfully continue until another in-progress one (or, if
174 >     * previously empty, a push) completes.  However, in the
175 >     * aggregate, we ensure at least probabilistic non-blockingness.
176 >     * If an attempted steal fails, a thief always chooses a different
177 >     * random victim target to try next. So, in order for one thief to
178 >     * progress, it suffices for any in-progress poll or new push on
179 >     * any empty queue to complete. (This is why we normally use
180 >     * method pollAt and its variants that try once at the apparent
181 >     * base index, else consider alternative actions, rather than
182 >     * method poll.)
183 >     *
184 >     * This approach also enables support of a user mode in which local
185 >     * task processing is in FIFO, not LIFO order, simply by using
186 >     * poll rather than pop.  This can be useful in message-passing
187 >     * frameworks in which tasks are never joined.  However neither
188 >     * mode considers affinities, loads, cache localities, etc, so
189 >     * rarely provide the best possible performance on a given
190 >     * machine, but portably provide good throughput by averaging over
191 >     * these factors.  (Further, even if we did try to use such
192 >     * information, we do not usually have a basis for exploiting it.
193 >     * For example, some sets of tasks profit from cache affinities,
194 >     * but others are harmed by cache pollution effects.)
195 >     *
196 >     * WorkQueues are also used in a similar way for tasks submitted
197 >     * to the pool. We cannot mix these tasks in the same queues used
198 >     * for work-stealing (this would contaminate lifo/fifo
199 >     * processing). Instead, we loosely associate submission queues
200 >     * with submitting threads, using a form of hashing.  The
201 >     * ThreadLocal Submitter class contains a value initially used as
202 >     * a hash code for choosing existing queues, but may be randomly
203 >     * repositioned upon contention with other submitters.  In
204 >     * essence, submitters act like workers except that they never
205 >     * take tasks, and they are multiplexed on to a finite number of
206 >     * shared work queues. However, classes are set up so that future
207 >     * extensions could allow submitters to optionally help perform
208 >     * tasks as well. Insertion of tasks in shared mode requires a
209 >     * lock (mainly to protect in the case of resizing) but we use
210 >     * only a simple spinlock (using bits in field runState), because
211 >     * submitters encountering a busy queue move on to try or create
212 >     * other queues -- they block only when creating and registering
213 >     * new queues.
214 >     *
215 >     * Management
216 >     * ==========
217       *
218       * The main throughput advantages of work-stealing stem from
219       * decentralized control -- workers mostly take tasks from
220       * themselves or each other. We cannot negate this in the
221       * implementation of other management responsibilities. The main
222       * tactic for avoiding bottlenecks is packing nearly all
223 <     * essentially atomic control state into a single 64bit volatile
224 <     * variable ("ctl"). This variable is read on the order of 10-100
225 <     * times as often as it is modified (always via CAS). (There is
226 <     * some additional control state, for example variable "shutdown"
227 <     * for which we can cope with uncoordinated updates.)  This
228 <     * streamlines synchronization and control at the expense of messy
229 <     * constructions needed to repack status bits upon updates.
230 <     * Updates tend not to contend with each other except during
231 <     * bursts while submitted tasks begin or end.  In some cases when
232 <     * they do contend, threads can instead do something else
233 <     * (usually, scan for tesks) until contention subsides.
234 <     *
235 <     * To enable packing, we restrict maximum parallelism to (1<<15)-1
236 <     * (which is far in excess of normal operating range) to allow
237 <     * ids, counts, and their negations (used for thresholding) to fit
238 <     * into 16bit fields.
239 <     *
240 <     * Recording Workers.  Workers are recorded in the "workers" array
241 <     * that is created upon pool construction and expanded if (rarely)
242 <     * necessary.  This is an array as opposed to some other data
243 <     * structure to support index-based random steals by workers.
244 <     * Updates to the array recording new workers and unrecording
245 <     * terminated ones are protected from each other by a seqLock
246 <     * (scanGuard) but the array is otherwise concurrently readable,
168 <     * and accessed directly by workers. To simplify index-based
223 >     * essentially atomic control state into two volatile variables
224 >     * that are by far most often read (not written) as status and
225 >     * consistency checks.
226 >     *
227 >     * Field "ctl" contains 64 bits holding all the information needed
228 >     * to atomically decide to add, inactivate, enqueue (on an event
229 >     * queue), dequeue, and/or re-activate workers.  To enable this
230 >     * packing, we restrict maximum parallelism to (1<<15)-1 (which is
231 >     * far in excess of normal operating range) to allow ids, counts,
232 >     * and their negations (used for thresholding) to fit into 16bit
233 >     * fields.
234 >     *
235 >     * Field "runState" contains 32 bits needed to register and
236 >     * deregister WorkQueues, as well as to enable shutdown. It is
237 >     * only modified under a lock (normally briefly held, but
238 >     * occasionally protecting allocations and resizings) but even
239 >     * when locked remains available to check consistency.
240 >     *
241 >     * Recording WorkQueues.  WorkQueues are recorded in the
242 >     * "workQueues" array that is created upon pool construction and
243 >     * expanded if necessary.  Updates to the array while recording
244 >     * new workers and unrecording terminated ones are protected from
245 >     * each other by a lock but the array is otherwise concurrently
246 >     * readable, and accessed directly.  To simplify index-based
247       * operations, the array size is always a power of two, and all
248 <     * readers must tolerate null slots. To avoid flailing during
249 <     * start-up, the array is presized to hold twice #parallelism
250 <     * workers (which is unlikely to need further resizing during
251 <     * execution). But to avoid dealing with so many null slots,
252 <     * variable scanGuard includes a mask for the nearest power of two
253 <     * that contains all current workers.  All worker thread creation
254 <     * is on-demand, triggered by task submissions, replacement of
255 <     * terminated workers, and/or compensation for blocked
256 <     * workers. However, all other support code is set up to work with
257 <     * other policies.  To ensure that we do not hold on to worker
258 <     * references that would prevent GC, ALL accesses to workers are
259 <     * via indices into the workers array (which is one source of some
260 <     * of the messy code constructions here). In essence, the workers
261 <     * array serves as a weak reference mechanism. Thus for example
262 <     * the wait queue field of ctl stores worker indices, not worker
263 <     * references.  Access to the workers in associated methods (for
264 <     * example signalWork) must both index-check and null-check the
265 <     * IDs. All such accesses ignore bad IDs by returning out early
266 <     * from what they are doing, since this can only be associated
267 <     * with termination, in which case it is OK to give up.
268 <     *
269 <     * All uses of the workers array, as well as queue arrays, check
270 <     * that the array is non-null (even if previously non-null). This
271 <     * allows nulling during termination, which is currently not
272 <     * necessary, but remains an option for resource-revocation-based
273 <     * shutdown schemes.
274 <     *
275 <     * Wait Queuing. Unlike HPC work-stealing frameworks, we cannot
276 <     * let workers spin indefinitely scanning for tasks when none are
277 <     * can be immediately found, and we cannot start/resume workers
278 <     * unless there appear to be tasks available.  On the other hand,
279 <     * we must quickly prod them into action when new tasks are
280 <     * submitted or generated.  We park/unpark workers after placing
281 <     * in an event wait queue when they cannot find work. This "queue"
282 <     * is actually a simple Treiber stack, headed by the "id" field of
283 <     * ctl, plus a 15bit counter value to both wake up waiters (by
284 <     * advancing their count) and avoid ABA effects. Successors are
285 <     * held in worker field "nextWait".  Queuing deals with several
286 <     * intrinsic races, mainly that a task-producing thread can miss
287 <     * seeing (and signalling) another thread that gave up looking for
288 <     * work but has not yet entered the wait queue. We solve this by
289 <     * requiring a full sweep of all workers both before (in scan())
290 <     * and after (in awaitWork()) a newly waiting worker is added to
291 <     * the wait queue. During a rescan, the worker might release some
292 <     * other queued worker rather than itself, which has the same net
293 <     * effect.
248 >     * readers must tolerate null slots. Shared (submission) queues
249 >     * are at even indices, worker queues at odd indices. Grouping
250 >     * them together in this way simplifies and speeds up task
251 >     * scanning.
252 >     *
253 >     * All worker thread creation is on-demand, triggered by task
254 >     * submissions, replacement of terminated workers, and/or
255 >     * compensation for blocked workers. However, all other support
256 >     * code is set up to work with other policies.  To ensure that we
257 >     * do not hold on to worker references that would prevent GC, ALL
258 >     * accesses to workQueues are via indices into the workQueues
259 >     * array (which is one source of some of the messy code
260 >     * constructions here). In essence, the workQueues array serves as
261 >     * a weak reference mechanism. Thus for example the wait queue
262 >     * field of ctl stores indices, not references.  Access to the
263 >     * workQueues in associated methods (for example signalWork) must
264 >     * both index-check and null-check the IDs. All such accesses
265 >     * ignore bad IDs by returning out early from what they are doing,
266 >     * since this can only be associated with termination, in which
267 >     * case it is OK to give up.  All uses of the workQueues array
268 >     * also check that it is non-null (even if previously
269 >     * non-null). This allows nulling during termination, which is
270 >     * currently not necessary, but remains an option for
271 >     * resource-revocation-based shutdown schemes. It also helps
272 >     * reduce JIT issuance of uncommon-trap code, which tends to
273 >     * unnecessarily complicate control flow in some methods.
274 >     *
275 >     * Event Queuing. Unlike HPC work-stealing frameworks, we cannot
276 >     * let workers spin indefinitely scanning for tasks when none can
277 >     * be found immediately, and we cannot start/resume workers unless
278 >     * there appear to be tasks available.  On the other hand, we must
279 >     * quickly prod them into action when new tasks are submitted or
280 >     * generated. In many usages, ramp-up time to activate workers is
281 >     * the main limiting factor in overall performance (this is
282 >     * compounded at program start-up by JIT compilation and
283 >     * allocation). So we try to streamline this as much as possible.
284 >     * We park/unpark workers after placing in an event wait queue
285 >     * when they cannot find work. This "queue" is actually a simple
286 >     * Treiber stack, headed by the "id" field of ctl, plus a 15bit
287 >     * counter value (that reflects the number of times a worker has
288 >     * been inactivated) to avoid ABA effects (we need only as many
289 >     * version numbers as worker threads). Successors are held in
290 >     * field WorkQueue.nextWait.  Queuing deals with several intrinsic
291 >     * races, mainly that a task-producing thread can miss seeing (and
292 >     * signalling) another thread that gave up looking for work but
293 >     * has not yet entered the wait queue. We solve this by requiring
294 >     * a full sweep of all workers (via repeated calls to method
295 >     * scan()) both before and after a newly waiting worker is added
296 >     * to the wait queue. During a rescan, the worker might release
297 >     * some other queued worker rather than itself, which has the same
298 >     * net effect. Because enqueued workers may actually be rescanning
299 >     * rather than waiting, we set and clear the "parker" field of
300 >     * WorkQueues to reduce unnecessary calls to unpark.  (This
301 >     * requires a secondary recheck to avoid missed signals.)  Note
302 >     * the unusual conventions about Thread.interrupts surrounding
303 >     * parking and other blocking: Because interrupts are used solely
304 >     * to alert threads to check termination, which is checked anyway
305 >     * upon blocking, we clear status (using Thread.interrupted)
306 >     * 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.
309       *
310       * Signalling.  We create or wake up workers only when there
311       * appears to be at least one task they might be able to find and
312       * execute.  When a submission is added or another worker adds a
313 <     * task to a queue that previously had two or fewer tasks, they
313 >     * task to a queue that previously had fewer than two tasks, they
314       * signal waiting workers (or trigger creation of new ones if
315       * fewer than the given parallelism level -- see signalWork).
316 <     * These primary signals are buttressed by signals during rescans
317 <     * as well as those performed when a worker steals a task and
318 <     * notices that there are more tasks too; together these cover the
319 <     * signals needed in cases when more than two tasks are pushed
227 <     * but untaken.
316 >     * These primary signals are buttressed by signals during rescans;
317 >     * together these cover the signals needed in cases when more
318 >     * tasks are pushed but untaken, and improve performance compared
319 >     * to having one thread wake up all workers.
320       *
321       * Trimming workers. To release resources after periods of lack of
322       * use, a worker starting to wait when the pool is quiescent will
323       * time out and terminate if the pool has remained quiescent for
324 <     * SHRINK_RATE nanosecs.
324 >     * SHRINK_RATE nanosecs. This will slowly propagate, eventually
325 >     * terminating all workers after long periods of non-use.
326       *
327 <     * Submissions. External submissions are maintained in an
328 <     * array-based queue that is structured identically to
329 <     * ForkJoinWorkerThread queues (which see) except for the use of
330 <     * submissionLock in method addSubmission. Unlike worker queues,
331 <     * multiple external threads can add new submissions.
332 <     *
333 <     * Compensation. Beyond work-stealing support and lifecycle
334 <     * control, the main responsibility of this framework is to take
335 <     * actions when one worker is waiting to join a task stolen (or
336 <     * always held by) another.  Because we are multiplexing many
337 <     * tasks on to a pool of workers, we can't just let them block (as
338 <     * in Thread.join).  We also cannot just reassign the joiner's
339 <     * run-time stack with another and replace it later, which would
340 <     * be a form of "continuation", that even if possible is not
341 <     * necessarily a good idea since we sometimes need both an
342 <     * unblocked task and its continuation to progress. Instead we
343 <     * combine two tactics:
327 >     * Shutdown and Termination. A call to shutdownNow atomically sets
328 >     * a runState bit and then (non-atomically) sets each worker's
329 >     * runState status, cancels all unprocessed tasks, and wakes up
330 >     * all waiting workers.  Detecting whether termination should
331 >     * commence after a non-abrupt shutdown() call requires more work
332 >     * and bookkeeping. We need consensus about quiescence (i.e., that
333 >     * there is no more work). The active count provides a primary
334 >     * indication but non-abrupt shutdown still requires a rechecking
335 >     * scan for any workers that are inactive but not queued.
336 >     *
337 >     * Joining Tasks
338 >     * =============
339 >     *
340 >     * Any of several actions may be taken when one worker is waiting
341 >     * to join a task stolen (or always held) by another.  Because we
342 >     * are multiplexing many tasks on to a pool of workers, we can't
343 >     * just let them block (as in Thread.join).  We also cannot just
344 >     * reassign the joiner's run-time stack with another and replace
345 >     * it later, which would be a form of "continuation", that even if
346 >     * possible is not necessarily a good idea since we sometimes need
347 >     * both an unblocked task and its continuation to progress.
348 >     * Instead we combine two tactics:
349       *
350       *   Helping: Arranging for the joiner to execute some task that it
351 <     *      would be running if the steal had not occurred.  Method
254 <     *      ForkJoinWorkerThread.joinTask tracks joining->stealing
255 <     *      links to try to find such a task.
351 >     *      would be running if the steal had not occurred.
352       *
353       *   Compensating: Unless there are already enough live threads,
354 <     *      method tryPreBlock() may create or re-activate a spare
355 <     *      thread to compensate for blocked joiners until they
356 <     *      unblock.
354 >     *      method tryCompensate() may create or re-activate a spare
355 >     *      thread to compensate for blocked joiners until they unblock.
356 >     *
357 >     * A third form (implemented in tryRemoveAndExec and
358 >     * tryPollForAndExec) amounts to helping a hypothetical
359 >     * compensator: If we can readily tell that a possible action of a
360 >     * compensator is to steal and execute the task being joined, the
361 >     * joining thread can do so directly, without the need for a
362 >     * compensation thread (although at the expense of larger run-time
363 >     * stacks, but the tradeoff is typically worthwhile).
364       *
365       * The ManagedBlocker extension API can't use helping so relies
366       * only on compensation in method awaitBlocker.
367       *
368 +     * The algorithm in tryHelpStealer entails a form of "linear"
369 +     * helping: Each worker records (in field currentSteal) the most
370 +     * recent task it stole from some other worker. Plus, it records
371 +     * (in field currentJoin) the task it is currently actively
372 +     * joining. Method tryHelpStealer uses these markers to try to
373 +     * find a worker to help (i.e., steal back a task from and execute
374 +     * it) that could hasten completion of the actively joined task.
375 +     * In essence, the joiner executes a task that would be on its own
376 +     * local deque had the to-be-joined task not been stolen. This may
377 +     * be seen as a conservative variant of the approach in Wagner &
378 +     * Calder "Leapfrogging: a portable technique for implementing
379 +     * efficient futures" SIGPLAN Notices, 1993
380 +     * (http://portal.acm.org/citation.cfm?id=155354). It differs in
381 +     * that: (1) We only maintain dependency links across workers upon
382 +     * steals, rather than use per-task bookkeeping.  This sometimes
383 +     * requires a linear scan of workQueues array to locate stealers,
384 +     * but often doesn't because stealers leave hints (that may become
385 +     * stale/wrong) of where to locate them.  A stealHint is only a
386 +     * hint because a worker might have had multiple steals and the
387 +     * hint records only one of them (usually the most current).
388 +     * Hinting isolates cost to when it is needed, rather than adding
389 +     * to per-task overhead.  (2) It is "shallow", ignoring nesting
390 +     * and potentially cyclic mutual steals.  (3) It is intentionally
391 +     * racy: field currentJoin is updated only while actively joining,
392 +     * which means that we miss links in the chain during long-lived
393 +     * tasks, GC stalls etc (which is OK since blocking in such cases
394 +     * is usually a good idea).  (4) We bound the number of attempts
395 +     * to find work (see MAX_HELP) and fall back to suspending the
396 +     * worker and if necessary replacing it with another.
397 +     *
398       * It is impossible to keep exactly the target parallelism number
399       * of threads running at any given time.  Determining the
400       * existence of conservatively safe helping targets, the
401       * availability of already-created spares, and the apparent need
402 <     * to create new spares are all racy and require heuristic
403 <     * guidance, so we rely on multiple retries of each.  Currently,
404 <     * in keeping with on-demand signalling policy, we compensate only
405 <     * if blocking would leave less than one active (non-waiting,
406 <     * non-blocked) worker. Additionally, to avoid some false alarms
407 <     * due to GC, lagging counters, system activity, etc, compensated
408 <     * blocking for joins is only attempted after a number of rechecks
409 <     * proportional to the current apparent deficit (where retries are
410 <     * interspersed with Thread.yield, for good citizenship).  The
411 <     * variable blockedCount, incremented before blocking and
412 <     * decremented after, is sometimes needed to distinguish cases of
413 <     * waiting for work vs blocking on joins or other managed sync,
414 <     * but both the cases are equivalent for most pool control, so we
415 <     * can update non-atomically. (Additionally, contention on
416 <     * blockedCount alleviates some contention on ctl).
417 <     *
418 <     * Shutdown and Termination. A call to shutdownNow atomically sets
419 <     * the ctl stop bit and then (non-atomically) sets each workers
420 <     * "terminate" status, cancels all unprocessed tasks, and wakes up
421 <     * all waiting workers.  Detecting whether termination should
422 <     * commence after a non-abrupt shutdown() call requires more work
423 <     * and bookkeeping. We need consensus about quiesence (i.e., that
424 <     * there is no more work) which is reflected in active counts so
425 <     * long as there are no current blockers, as well as possible
426 <     * re-evaluations during independent changes in blocking or
427 <     * quiescing workers.
402 >     * to create new spares are all racy, so we rely on multiple
403 >     * retries of each.  Compensation in the apparent absence of
404 >     * helping opportunities is challenging to control on JVMs, where
405 >     * GC and other activities can stall progress of tasks that in
406 >     * turn stall out many other dependent tasks, without us being
407 >     * able to determine whether they will ever require compensation.
408 >     * Even though work-stealing otherwise encounters little
409 >     * degradation in the presence of more threads than cores,
410 >     * aggressively adding new threads in such cases entails risk of
411 >     * unwanted positive feedback control loops in which more threads
412 >     * cause more dependent stalls (as well as delayed progress of
413 >     * unblocked threads to the point that we know they are available)
414 >     * leading to more situations requiring more threads, and so
415 >     * on. This aspect of control can be seen as an (analytically
416 >     * intractable) game with an opponent that may choose the worst
417 >     * (for us) active thread to stall at any time.  We take several
418 >     * precautions to bound losses (and thus bound gains), mainly in
419 >     * methods tryCompensate and awaitJoin: (1) We only try
420 >     * compensation after attempting enough helping steps (measured
421 >     * via counting and timing) that we have already consumed the
422 >     * estimated cost of creating and activating a new thread.  (2) We
423 >     * allow up to 50% of threads to be blocked before initially
424 >     * adding any others, and unless completely saturated, check that
425 >     * some work is available for a new worker before adding. Also, we
426 >     * create up to only 50% more threads until entering a mode that
427 >     * only adds a thread if all others are possibly blocked.  All
428 >     * together, this means that we might be half as fast to react,
429 >     * and create half as many threads as possible in the ideal case,
430 >     * but present vastly fewer anomalies in all other cases compared
431 >     * to both more aggressive and more conservative alternatives.
432       *
433       * Style notes: There is a lot of representation-level coupling
434       * among classes ForkJoinPool, ForkJoinWorkerThread, and
435 <     * ForkJoinTask.  Most fields of ForkJoinWorkerThread maintain
436 <     * data structures managed by ForkJoinPool, so are directly
437 <     * accessed.  Conversely we allow access to "workers" array by
438 <     * workers, and direct access to ForkJoinTask.status by both
439 <     * ForkJoinPool and ForkJoinWorkerThread.  There is little point
440 <     * trying to reduce this, since any associated future changes in
441 <     * representations will need to be accompanied by algorithmic
442 <     * changes anyway. All together, these low-level implementation
443 <     * choices produce as much as a factor of 4 performance
444 <     * improvement compared to naive implementations, and enable the
445 <     * processing of billions of tasks per second, at the expense of
446 <     * some ugliness.
447 <     *
448 <     * Methods signalWork() and scan() are the main bottlenecks so are
449 <     * especially heavily micro-optimized/mangled.  There are lots of
450 <     * inline assignments (of form "while ((local = field) != 0)")
451 <     * which are usually the simplest way to ensure the required read
452 <     * orderings (which are sometimes critical). This leads to a
453 <     * "C"-like style of listing declarations of these locals at the
454 <     * heads of methods or blocks.  There are several occurrences of
455 <     * the unusual "do {} while (!cas...)"  which is the simplest way
456 <     * to force an update of a CAS'ed variable. There are also other
457 <     * coding oddities that help some methods perform reasonably even
458 <     * when interpreted (not compiled).
459 <     *
460 <     * The order of declarations in this file is: (1) declarations of
461 <     * statics (2) fields (along with constants used when unpacking
462 <     * some of them), listed in an order that tends to reduce
463 <     * contention among them a bit under most JVMs.  (3) internal
464 <     * control methods (4) callbacks and other support for
465 <     * ForkJoinTask and ForkJoinWorkerThread classes, (5) exported
466 <     * methods (plus a few little helpers). (6) static block
467 <     * initializing all statics in a minimally dependent order.
435 >     * ForkJoinTask.  The fields of WorkQueue maintain data structures
436 >     * managed by ForkJoinPool, so are directly accessed.  There is
437 >     * little point trying to reduce this, since any associated future
438 >     * changes in representations will need to be accompanied by
439 >     * algorithmic changes anyway. Several methods intrinsically
440 >     * sprawl because they must accumulate sets of consistent reads of
441 >     * volatiles held in local variables.  Methods signalWork() and
442 >     * scan() are the main bottlenecks, so are especially heavily
443 >     * micro-optimized/mangled.  There are lots of inline assignments
444 >     * (of form "while ((local = field) != 0)") which are usually the
445 >     * simplest way to ensure the required read orderings (which are
446 >     * sometimes critical). This leads to a "C"-like style of listing
447 >     * declarations of these locals at the heads of methods or blocks.
448 >     * There are several occurrences of the unusual "do {} while
449 >     * (!cas...)"  which is the simplest way to force an update of a
450 >     * CAS'ed variable. There are also other coding oddities that help
451 >     * some methods perform reasonably even when interpreted (not
452 >     * compiled).
453 >     *
454 >     * The order of declarations in this file is:
455 >     * (1) Static utility functions
456 >     * (2) Nested (static) classes
457 >     * (3) Static fields
458 >     * (4) Fields, along with constants used when unpacking some of them
459 >     * (5) Internal control methods
460 >     * (6) Callbacks and other support for ForkJoinTask methods
461 >     * (7) Exported methods
462 >     * (8) Static block initializing statics in minimally dependent order
463 >     */
464 >
465 >    // Static utilities
466 >
467 >    /**
468 >     * If there is a security manager, makes sure caller has
469 >     * permission to modify threads.
470       */
471 +    private static void checkPermission() {
472 +        SecurityManager security = System.getSecurityManager();
473 +        if (security != null)
474 +            security.checkPermission(modifyThreadPermission);
475 +    }
476 +
477 +    // Nested classes
478  
479      /**
480       * Factory for creating new {@link ForkJoinWorkerThread}s.
# Line 358 | Line 504 | public class ForkJoinPool extends Abstra
504      }
505  
506      /**
507 <     * Creates a new ForkJoinWorkerThread. This factory is used unless
508 <     * overridden in ForkJoinPool constructors.
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 >    /**
530 >     * Class for artificial tasks that are used to replace the target
531 >     * of local joins if they are removed from an interior queue slot
532 >     * in WorkQueue.tryRemoveAndExec. We don't need the proxy to
533 >     * actually do anything beyond having a unique identity.
534 >     */
535 >    static final class EmptyTask extends ForkJoinTask<Void> {
536 >        EmptyTask() { status = ForkJoinTask.NORMAL; } // force done
537 >        public final Void getRawResult() { return null; }
538 >        public final void setRawResult(Void x) {}
539 >        public final boolean exec() { return true; }
540 >    }
541 >
542 >    /**
543 >     * Queues supporting work-stealing as well as external task
544 >     * submission. See above for main rationale and algorithms.
545 >     * Implementation relies heavily on "Unsafe" intrinsics
546 >     * and selective use of "volatile":
547 >     *
548 >     * Field "base" is the index (mod array.length) of the least valid
549 >     * queue slot, which is always the next position to steal (poll)
550 >     * from if nonempty. Reads and writes require volatile orderings
551 >     * but not CAS, because updates are only performed after slot
552 >     * CASes.
553 >     *
554 >     * Field "top" is the index (mod array.length) of the next queue
555 >     * slot to push to or pop from. It is written only by owner thread
556 >     * for push, or under lock for trySharedPush, and accessed by
557 >     * other threads only after reading (volatile) base.  Both top and
558 >     * base are allowed to wrap around on overflow, but (top - base)
559 >     * (or more commonly -(base - top) to force volatile read of base
560 >     * before top) still estimates size.
561 >     *
562 >     * The array slots are read and written using the emulation of
563 >     * volatiles/atomics provided by Unsafe. Insertions must in
564 >     * general use putOrderedObject as a form of releasing store to
565 >     * ensure that all writes to the task object are ordered before
566 >     * its publication in the queue. (Although we can avoid one case
567 >     * of this when locked in trySharedPush.) All removals entail a
568 >     * CAS to null.  The array is always a power of two. To ensure
569 >     * safety of Unsafe array operations, all accesses perform
570 >     * explicit null checks and implicit bounds checks via
571 >     * power-of-two masking.
572 >     *
573 >     * In addition to basic queuing support, this class contains
574 >     * fields described elsewhere to control execution. It turns out
575 >     * to work better memory-layout-wise to include them in this
576 >     * class rather than a separate class.
577 >     *
578 >     * Performance on most platforms is very sensitive to placement of
579 >     * instances of both WorkQueues and their arrays -- we absolutely
580 >     * do not want multiple WorkQueue instances or multiple queue
581 >     * arrays sharing cache lines. (It would be best for queue objects
582 >     * and their arrays to share, but there is nothing available to
583 >     * help arrange that).  Unfortunately, because they are recorded
584 >     * 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.
594       */
595 <    public static final ForkJoinWorkerThreadFactory
596 <        defaultForkJoinWorkerThreadFactory;
595 >    static final class WorkQueue {
596 >        /**
597 >         * Capacity of work-stealing queue array upon initialization.
598 >         * Must be a power of two; at least 4, but should be larger to
599 >         * reduce or eliminate cacheline sharing among queues.
600 >         * Currently, it is much larger, as a partial workaround for
601 >         * the fact that JVMs often place arrays in locations that
602 >         * share GC bookkeeping (especially cardmarks) such that
603 >         * per-write accesses encounter serious memory contention.
604 >         */
605 >        static final int INITIAL_QUEUE_CAPACITY = 1 << 13;
606  
607 <    /**
608 <     * Permission required for callers of methods that may start or
609 <     * kill threads.
610 <     */
611 <    private static final RuntimePermission modifyThreadPermission;
607 >        /**
608 >         * Maximum size for queue arrays. Must be a power of two less
609 >         * than or equal to 1 << (31 - width of array entry) to ensure
610 >         * lack of wraparound of index calculations, but defined to a
611 >         * value a bit less than this to help users trap runaway
612 >         * programs before saturating systems.
613 >         */
614 >        static final int MAXIMUM_QUEUE_CAPACITY = 1 << 26; // 64M
615  
616 <    /**
617 <     * If there is a security manager, makes sure caller has
618 <     * permission to modify threads.
619 <     */
620 <    private static void checkPermission() {
621 <        SecurityManager security = System.getSecurityManager();
622 <        if (security != null)
623 <            security.checkPermission(modifyThreadPermission);
616 >        volatile long totalSteals; // cumulative number of steals
617 >        int seed;                  // for random scanning; initialize nonzero
618 >        volatile int eventCount;   // encoded inactivation count; < 0 if inactive
619 >        int nextWait;              // encoded record of next event waiter
620 >        int rescans;               // remaining scans until block
621 >        int nsteals;               // top-level task executions since last idle
622 >        final int mode;            // lifo, fifo, or shared
623 >        int poolIndex;             // index of this queue in pool (or 0)
624 >        int stealHint;             // index of most recent known stealer
625 >        volatile int runState;     // 1: locked, -1: terminate; else 0
626 >        volatile int base;         // index of next slot for poll
627 >        int top;                   // index of next slot for push
628 >        ForkJoinTask<?>[] array;   // the elements (initially unallocated)
629 >        final ForkJoinPool pool;   // the containing pool (may be null)
630 >        final ForkJoinWorkerThread owner; // owning thread or null if shared
631 >        volatile Thread parker;    // == owner during call to park; else null
632 >        volatile ForkJoinTask<?> currentJoin;  // task being joined in awaitJoin
633 >        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;
637 >
638 >        WorkQueue(ForkJoinPool pool, ForkJoinWorkerThread owner, int mode) {
639 >            this.mode = mode;
640 >            this.pool = pool;
641 >            this.owner = owner;
642 >            // Place indices in the center of array (that is not yet allocated)
643 >            base = top = INITIAL_QUEUE_CAPACITY >>> 1;
644 >        }
645 >
646 >        /**
647 >         * Returns the approximate number of tasks in the queue.
648 >         */
649 >        final int queueSize() {
650 >            int n = base - top;       // non-owner callers must read base first
651 >            return (n >= 0) ? 0 : -n; // ignore transient negative
652 >        }
653 >
654 >        /**
655 >         * Provides a more accurate estimate of whether this queue has
656 >         * any tasks than does queueSize, by checking whether a
657 >         * near-empty queue has at least one unclaimed task.
658 >         */
659 >        final boolean isEmpty() {
660 >            ForkJoinTask<?>[] a; int m, s;
661 >            int n = base - (s = top);
662 >            return (n >= 0 ||
663 >                    (n == -1 &&
664 >                     ((a = array) == null ||
665 >                      (m = a.length - 1) < 0 ||
666 >                      U.getObjectVolatile
667 >                      (a, ((m & (s - 1)) << ASHIFT) + ABASE) == null)));
668 >        }
669 >
670 >        /**
671 >         * Pushes a task. Call only by owner in unshared queues.
672 >         *
673 >         * @param task the task. Caller must ensure non-null.
674 >         * @throw RejectedExecutionException if array cannot be resized
675 >         */
676 >        final void push(ForkJoinTask<?> task) {
677 >            ForkJoinTask<?>[] a; ForkJoinPool p;
678 >            int s = top, m, n;
679 >            if ((a = array) != null) {    // ignore if queue removed
680 >                U.putOrderedObject
681 >                    (a, (((m = a.length - 1) & s) << ASHIFT) + ABASE, task);
682 >                if ((n = (top = s + 1) - base) <= 2) {
683 >                    if ((p = pool) != null)
684 >                        p.signalWork();
685 >                }
686 >                else if (n >= m)
687 >                    growArray(true);
688 >            }
689 >        }
690 >
691 >        /**
692 >         * Pushes a task if lock is free and array is either big
693 >         * enough or can be resized to be big enough.
694 >         *
695 >         * @param task the task. Caller must ensure non-null.
696 >         * @return true if submitted
697 >         */
698 >        final boolean trySharedPush(ForkJoinTask<?> task) {
699 >            boolean submitted = false;
700 >            if (runState == 0 && U.compareAndSwapInt(this, RUNSTATE, 0, 1)) {
701 >                ForkJoinTask<?>[] a = array;
702 >                int s = top;
703 >                try {
704 >                    if ((a != null && a.length > s + 1 - base) ||
705 >                        (a = growArray(false)) != null) { // must presize
706 >                        int j = (((a.length - 1) & s) << ASHIFT) + ABASE;
707 >                        U.putObject(a, (long)j, task);    // don't need "ordered"
708 >                        top = s + 1;
709 >                        submitted = true;
710 >                    }
711 >                } finally {
712 >                    runState = 0;                         // unlock
713 >                }
714 >            }
715 >            return submitted;
716 >        }
717 >
718 >        /**
719 >         * Takes next task, if one exists, in LIFO order.  Call only
720 >         * by owner in unshared queues. (We do not have a shared
721 >         * version of this method because it is never needed.)
722 >         */
723 >        final ForkJoinTask<?> pop() {
724 >            ForkJoinTask<?>[] a; ForkJoinTask<?> t; int m;
725 >            if ((a = array) != null && (m = a.length - 1) >= 0) {
726 >                for (int s; (s = top - 1) - base >= 0;) {
727 >                    long j = ((m & s) << ASHIFT) + ABASE;
728 >                    if ((t = (ForkJoinTask<?>)U.getObject(a, j)) == null)
729 >                        break;
730 >                    if (U.compareAndSwapObject(a, j, t, null)) {
731 >                        top = s;
732 >                        return t;
733 >                    }
734 >                }
735 >            }
736 >            return null;
737 >        }
738 >
739 >        /**
740 >         * Takes a task in FIFO order if b is base of queue and a task
741 >         * can be claimed without contention. Specialized versions
742 >         * appear in ForkJoinPool methods scan and tryHelpStealer.
743 >         */
744 >        final ForkJoinTask<?> pollAt(int b) {
745 >            ForkJoinTask<?> t; ForkJoinTask<?>[] a;
746 >            if ((a = array) != null) {
747 >                int j = (((a.length - 1) & b) << ASHIFT) + ABASE;
748 >                if ((t = (ForkJoinTask<?>)U.getObjectVolatile(a, j)) != null &&
749 >                    base == b &&
750 >                    U.compareAndSwapObject(a, j, t, null)) {
751 >                    base = b + 1;
752 >                    return t;
753 >                }
754 >            }
755 >            return null;
756 >        }
757 >
758 >        /**
759 >         * Takes next task, if one exists, in FIFO order.
760 >         */
761 >        final ForkJoinTask<?> poll() {
762 >            ForkJoinTask<?>[] a; int b; ForkJoinTask<?> t;
763 >            while ((b = base) - top < 0 && (a = array) != null) {
764 >                int j = (((a.length - 1) & b) << ASHIFT) + ABASE;
765 >                t = (ForkJoinTask<?>)U.getObjectVolatile(a, j);
766 >                if (t != null) {
767 >                    if (base == b &&
768 >                        U.compareAndSwapObject(a, j, t, null)) {
769 >                        base = b + 1;
770 >                        return t;
771 >                    }
772 >                }
773 >                else if (base == b) {
774 >                    if (b + 1 == top)
775 >                        break;
776 >                    Thread.yield(); // wait for lagging update
777 >                }
778 >            }
779 >            return null;
780 >        }
781 >
782 >        /**
783 >         * Takes next task, if one exists, in order specified by mode.
784 >         */
785 >        final ForkJoinTask<?> nextLocalTask() {
786 >            return mode == 0 ? pop() : poll();
787 >        }
788 >
789 >        /**
790 >         * Returns next task, if one exists, in order specified by mode.
791 >         */
792 >        final ForkJoinTask<?> peek() {
793 >            ForkJoinTask<?>[] a = array; int m;
794 >            if (a == null || (m = a.length - 1) < 0)
795 >                return null;
796 >            int i = mode == 0 ? top - 1 : base;
797 >            int j = ((i & m) << ASHIFT) + ABASE;
798 >            return (ForkJoinTask<?>)U.getObjectVolatile(a, j);
799 >        }
800 >
801 >        /**
802 >         * Pops the given task only if it is at the current top.
803 >         */
804 >        final boolean tryUnpush(ForkJoinTask<?> t) {
805 >            ForkJoinTask<?>[] a; int s;
806 >            if ((a = array) != null && (s = top) != base &&
807 >                U.compareAndSwapObject
808 >                (a, (((a.length - 1) & --s) << ASHIFT) + ABASE, t, null)) {
809 >                top = s;
810 >                return true;
811 >            }
812 >            return false;
813 >        }
814 >
815 >        /**
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 >        /**
867 >         * Removes and cancels all known tasks, ignoring any exceptions.
868 >         */
869 >        final void cancelAll() {
870 >            ForkJoinTask.cancelIgnoringExceptions(currentJoin);
871 >            ForkJoinTask.cancelIgnoringExceptions(currentSteal);
872 >            for (ForkJoinTask<?> t; (t = poll()) != null; )
873 >                ForkJoinTask.cancelIgnoringExceptions(t);
874 >        }
875 >
876 >        /**
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 >        }
909 >
910 >        /**
911 >         * Polls and runs tasks until empty.
912 >         */
913 >        private void pollAndExecAll() {
914 >            for (ForkJoinTask<?> t; (t = poll()) != null;)
915 >                t.doExec();
916 >        }
917 >
918 >        /**
919 >         * If present, removes from queue and executes the given task, or
920 >         * any other cancelled task. Returns (true) immediately on any CAS
921 >         * or consistency check failure so caller can retry.
922 >         *
923 >         * @return 0 if no progress can be made, else positive
924 >         * (this unusual convention simplifies use with tryHelpStealer.)
925 >         */
926 >        final int tryRemoveAndExec(ForkJoinTask<?> task) {
927 >            int stat = 1;
928 >            boolean removed = false, empty = true;
929 >            ForkJoinTask<?>[] a; int m, s, b, n;
930 >            if ((a = array) != null && (m = a.length - 1) >= 0 &&
931 >                (n = (s = top) - (b = base)) > 0) {
932 >                for (ForkJoinTask<?> t;;) {           // traverse from s to b
933 >                    int j = ((--s & m) << ASHIFT) + ABASE;
934 >                    t = (ForkJoinTask<?>)U.getObjectVolatile(a, j);
935 >                    if (t == null)                    // inconsistent length
936 >                        break;
937 >                    else if (t == task) {
938 >                        if (s + 1 == top) {           // pop
939 >                            if (!U.compareAndSwapObject(a, j, task, null))
940 >                                break;
941 >                            top = s;
942 >                            removed = true;
943 >                        }
944 >                        else if (base == b)           // replace with proxy
945 >                            removed = U.compareAndSwapObject(a, j, task,
946 >                                                             new EmptyTask());
947 >                        break;
948 >                    }
949 >                    else if (t.status >= 0)
950 >                        empty = false;
951 >                    else if (s + 1 == top) {          // pop and throw away
952 >                        if (U.compareAndSwapObject(a, j, t, null))
953 >                            top = s;
954 >                        break;
955 >                    }
956 >                    if (--n == 0) {
957 >                        if (!empty && base == b)
958 >                            stat = 0;
959 >                        break;
960 >                    }
961 >                }
962 >            }
963 >            if (removed)
964 >                task.doExec();
965 >            return stat;
966 >        }
967 >
968 >        /**
969 >         * Executes a top-level task and any local tasks remaining
970 >         * after execution.
971 >         */
972 >        final void runTask(ForkJoinTask<?> t) {
973 >            if (t != null) {
974 >                currentSteal = t;
975 >                t.doExec();
976 >                if (top != base) {       // process remaining local tasks
977 >                    if (mode == 0)
978 >                        popAndExecAll();
979 >                    else
980 >                        pollAndExecAll();
981 >                }
982 >                ++nsteals;
983 >                currentSteal = null;
984 >            }
985 >        }
986 >
987 >        /**
988 >         * Executes a non-top-level (stolen) task.
989 >         */
990 >        final void runSubtask(ForkJoinTask<?> t) {
991 >            if (t != null) {
992 >                ForkJoinTask<?> ps = currentSteal;
993 >                currentSteal = t;
994 >                t.doExec();
995 >                currentSteal = ps;
996 >            }
997 >        }
998 >
999 >        /**
1000 >         * Returns true if owned and not known to be blocked.
1001 >         */
1002 >        final boolean isApparentlyUnblocked() {
1003 >            Thread wt; Thread.State s;
1004 >            return (eventCount >= 0 &&
1005 >                    (wt = owner) != null &&
1006 >                    (s = wt.getState()) != Thread.State.BLOCKED &&
1007 >                    s != Thread.State.WAITING &&
1008 >                    s != Thread.State.TIMED_WAITING);
1009 >        }
1010 >
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 >
1027 >        // Unsafe mechanics
1028 >        private static final sun.misc.Unsafe U;
1029 >        private static final long RUNSTATE;
1030 >        private static final int ABASE;
1031 >        private static final int ASHIFT;
1032 >        static {
1033 >            int s;
1034 >            try {
1035 >                U = getUnsafe();
1036 >                Class<?> k = WorkQueue.class;
1037 >                Class<?> ak = ForkJoinTask[].class;
1038 >                RUNSTATE = U.objectFieldOffset
1039 >                    (k.getDeclaredField("runState"));
1040 >                ABASE = U.arrayBaseOffset(ak);
1041 >                s = U.arrayIndexScale(ak);
1042 >            } catch (Exception e) {
1043 >                throw new Error(e);
1044 >            }
1045 >            if ((s & (s-1)) != 0)
1046 >                throw new Error("data type scale not a power of two");
1047 >            ASHIFT = 31 - Integer.numberOfLeadingZeros(s);
1048 >        }
1049      }
1050  
1051      /**
1052 <     * Generator for assigning sequence numbers as pool names.
1052 >     * Per-thread records for threads that submit to pools. Currently
1053 >     * holds only pseudo-random seed / index that is used to choose
1054 >     * submission queues in method doSubmit. In the future, this may
1055 >     * also incorporate a means to implement different task rejection
1056 >     * and resubmission policies.
1057 >     *
1058 >     * Seeds for submitters and workers/workQueues work in basically
1059 >     * the same way but are initialized and updated using slightly
1060 >     * different mechanics. Both are initialized using the same
1061 >     * approach as in class ThreadLocal, where successive values are
1062 >     * unlikely to collide with previous values. This is done during
1063 >     * registration for workers, but requires a separate AtomicInteger
1064 >     * for submitters. Seeds are then randomly modified upon
1065 >     * collisions using xorshifts, which requires a non-zero seed.
1066       */
1067 <    private static final AtomicInteger poolNumberGenerator;
1067 >    static final class Submitter {
1068 >        int seed;
1069 >        Submitter() {
1070 >            int s = nextSubmitterSeed.getAndAdd(SEED_INCREMENT);
1071 >            seed = (s == 0) ? 1 : s; // ensure non-zero
1072 >        }
1073 >    }
1074  
1075 <    /**
1076 <     * Generator for initial random seeds for worker victim
1077 <     * selection. This is used only to create initial seeds. Random
1078 <     * steals use a cheaper xorshift generator per steal attempt. We
1079 <     * don't expect much contention on seedGenerator, so just use a
1080 <     * plain Random.
394 <     */
395 <    static final Random workerSeedGenerator;
1075 >    /** ThreadLocal class for Submitters */
1076 >    static final class ThreadSubmitter extends ThreadLocal<Submitter> {
1077 >        public Submitter initialValue() { return new Submitter(); }
1078 >    }
1079 >
1080 >    // static fields (initialized in static initializer below)
1081  
1082      /**
1083 <     * Array holding all worker threads in the pool.  Initialized upon
1084 <     * construction. Array size must be a power of two.  Updates and
400 <     * replacements are protected by scanGuard, but the array is
401 <     * always kept in a consistent enough state to be randomly
402 <     * accessed without locking by workers performing work-stealing,
403 <     * as well as other traversal-based methods in this class, so long
404 <     * as reads memory-acquire by first reading ctl. All readers must
405 <     * tolerate that some array slots may be null.
1083 >     * Creates a new ForkJoinWorkerThread. This factory is used unless
1084 >     * overridden in ForkJoinPool constructors.
1085       */
1086 <    ForkJoinWorkerThread[] workers;
1086 >    public static final ForkJoinWorkerThreadFactory
1087 >        defaultForkJoinWorkerThreadFactory;
1088  
1089      /**
1090 <     * Initial size for submission queue array. Must be a power of
411 <     * two.  In many applications, these always stay small so we use a
412 <     * small initial cap.
1090 >     * Generator for assigning sequence numbers as pool names.
1091       */
1092 <    private static final int INITIAL_QUEUE_CAPACITY = 8;
1092 >    private static final AtomicInteger poolNumberGenerator;
1093  
1094      /**
1095 <     * Maximum size for submission queue array. Must be a power of two
1096 <     * less than or equal to 1 << (31 - width of array entry) to
419 <     * ensure lack of index wraparound, but is capped at a lower
420 <     * value to help users trap runaway computations.
1095 >     * Generator for initial hashes/seeds for submitters. Accessed by
1096 >     * Submitter class constructor.
1097       */
1098 <    private static final int MAXIMUM_QUEUE_CAPACITY = 1 << 24; // 16M
1098 >    static final AtomicInteger nextSubmitterSeed;
1099  
1100      /**
1101 <     * Array serving as submission queue. Initialized upon construction.
1101 >     * Permission required for callers of methods that may start or
1102 >     * kill threads.
1103       */
1104 <    private ForkJoinTask<?>[] submissionQueue;
1104 >    private static final RuntimePermission modifyThreadPermission;
1105  
1106      /**
1107 <     * Lock protecting submissions array for addSubmission
1107 >     * Per-thread submission bookkeeping. Shared across all pools
1108 >     * to reduce ThreadLocal pollution and because random motion
1109 >     * to avoid contention in one pool is likely to hold for others.
1110       */
1111 <    private final ReentrantLock submissionLock;
1111 >    private static final ThreadSubmitter submitters;
1112 >
1113 >    // static constants
1114  
1115      /**
1116 <     * Condition for awaitTermination, using submissionLock for
1117 <     * convenience.
1116 >     * The wakeup interval (in nanoseconds) for a worker waiting for a
1117 >     * task when the pool is quiescent to instead try to shrink the
1118 >     * number of workers.  The exact value does not matter too
1119 >     * much. It must be short enough to release resources during
1120 >     * sustained periods of idleness, but not so short that threads
1121 >     * are continually re-created.
1122       */
1123 <    private final Condition termination;
1123 >    private static final long SHRINK_RATE =
1124 >        4L * 1000L * 1000L * 1000L; // 4 seconds
1125  
1126      /**
1127 <     * Creation factory for worker threads.
1127 >     * The timeout value for attempted shrinkage, includes
1128 >     * some slop to cope with system timer imprecision.
1129       */
1130 <    private final ForkJoinWorkerThreadFactory factory;
1130 >    private static final long SHRINK_TIMEOUT = SHRINK_RATE - (SHRINK_RATE / 10);
1131  
1132      /**
1133 <     * The uncaught exception handler used when any worker abruptly
1134 <     * terminates.
1133 >     * The maximum stolen->joining link depth allowed in method
1134 >     * tryHelpStealer.  Must be a power of two. This value also
1135 >     * controls the maximum number of times to try to help join a task
1136 >     * without any apparent progress or change in pool state before
1137 >     * giving up and blocking (see awaitJoin).  Depths for legitimate
1138 >     * chains are unbounded, but we use a fixed constant to avoid
1139 >     * (otherwise unchecked) cycles and to bound staleness of
1140 >     * traversal parameters at the expense of sometimes blocking when
1141 >     * we could be helping.
1142       */
1143 <    final Thread.UncaughtExceptionHandler ueh;
1143 >    private static final int MAX_HELP = 64;
1144  
1145      /**
1146 <     * Prefix for assigning names to worker threads
1146 >     * Secondary time-based bound (in nanosecs) for helping attempts
1147 >     * before trying compensated blocking in awaitJoin. Used in
1148 >     * conjunction with MAX_HELP to reduce variance due to different
1149 >     * polling rates associated with different helping options. The
1150 >     * value should roughly approximate the time required to create
1151 >     * and/or activate a worker thread.
1152       */
1153 <    private final String workerNamePrefix;
1153 >    private static final long COMPENSATION_DELAY = 1L << 18; // ~0.25 millisec
1154  
1155      /**
1156 <     * Sum of per-thread steal counts, updated only when threads are
1157 <     * idle or terminating.
1156 >     * Increment for seed generators. See class ThreadLocal for
1157 >     * explanation.
1158       */
1159 <    private volatile long stealCount;
1159 >    private static final int SEED_INCREMENT = 0x61c88647;
1160  
1161      /**
1162 <     * Main pool control -- a long packed with:
1162 >     * Bits and masks for control variables
1163 >     *
1164 >     * Field ctl is a long packed with:
1165       * AC: Number of active running workers minus target parallelism (16 bits)
1166 <     * TC: Number of total workers minus target parallelism (16bits)
1166 >     * TC: Number of total workers minus target parallelism (16 bits)
1167       * ST: true if pool is terminating (1 bit)
1168       * EC: the wait count of top waiting thread (15 bits)
1169 <     * ID: ~poolIndex of top of Treiber stack of waiting threads (16 bits)
1169 >     * ID: poolIndex of top of Treiber stack of waiters (16 bits)
1170       *
1171       * When convenient, we can extract the upper 32 bits of counts and
1172       * the lower 32 bits of queue state, u = (int)(ctl >>> 32) and e =
# Line 474 | Line 1175 | public class ForkJoinPool extends Abstra
1175       * parallelism and the positionings of fields makes it possible to
1176       * perform the most common checks via sign tests of fields: When
1177       * ac is negative, there are not enough active workers, when tc is
1178 <     * negative, there are not enough total workers, when id is
478 <     * negative, there is at least one waiting worker, and when e is
1178 >     * negative, there are not enough total workers, and when e is
1179       * negative, the pool is terminating.  To deal with these possibly
1180       * negative fields, we use casts in and out of "short" and/or
1181 <     * signed shifts to maintain signedness.  Note: AC_SHIFT is
1182 <     * redundantly declared in ForkJoinWorkerThread in order to
1183 <     * integrate a surplus-threads check.
1181 >     * signed shifts to maintain signedness.
1182 >     *
1183 >     * When a thread is queued (inactivated), its eventCount field is
1184 >     * set negative, which is the only way to tell if a worker is
1185 >     * prevented from executing tasks, even though it must continue to
1186 >     * scan for them to avoid queuing races. Note however that
1187 >     * eventCount updates lag releases so usage requires care.
1188 >     *
1189 >     * Field runState is an int packed with:
1190 >     * SHUTDOWN: true if shutdown is enabled (1 bit)
1191 >     * SEQ:  a sequence number updated upon (de)registering workers (30 bits)
1192 >     * INIT: set true after workQueues array construction (1 bit)
1193 >     *
1194 >     * The sequence number enables simple consistency checks:
1195 >     * Staleness of read-only operations on the workQueues array can
1196 >     * be checked by comparing runState before vs after the reads.
1197       */
485    volatile long ctl;
1198  
1199      // bit positions/shifts for fields
1200      private static final int  AC_SHIFT   = 48;
# Line 491 | Line 1203 | public class ForkJoinPool extends Abstra
1203      private static final int  EC_SHIFT   = 16;
1204  
1205      // bounds
1206 <    private static final int  MAX_ID     = 0x7fff;  // max poolIndex
1207 <    private static final int  SMASK      = 0xffff;  // mask short bits
1206 >    private static final int  SMASK      = 0xffff;  // short bits
1207 >    private static final int  MAX_CAP    = 0x7fff;  // max #workers - 1
1208 >    private static final int  SQMASK     = 0xfffe;  // even short bits
1209      private static final int  SHORT_SIGN = 1 << 15;
1210      private static final int  INT_SIGN   = 1 << 31;
1211  
# Line 514 | Line 1227 | public class ForkJoinPool extends Abstra
1227      private static final int  UTC_UNIT   = 1 << UTC_SHIFT;
1228  
1229      // masks and units for dealing with e = (int)ctl
1230 <    private static final int  E_MASK     = 0x7fffffff; // no STOP_BIT
1231 <    private static final int  EC_UNIT    = 1 << EC_SHIFT;
1230 >    private static final int E_MASK      = 0x7fffffff; // no STOP_BIT
1231 >    private static final int E_SEQ       = 1 << EC_SHIFT;
1232  
1233 <    /**
1234 <     * The target parallelism level.
522 <     */
523 <    final int parallelism;
1233 >    // runState bits
1234 >    private static final int SHUTDOWN    = 1 << 31;
1235  
1236 <    /**
1237 <     * Index (mod submission queue length) of next element to take
1238 <     * from submission queue.
1239 <     */
529 <    volatile int queueBase;
1236 >    // access mode for WorkQueue
1237 >    static final int LIFO_QUEUE          =  0;
1238 >    static final int FIFO_QUEUE          =  1;
1239 >    static final int SHARED_QUEUE        = -1;
1240  
1241 <    /**
532 <     * Index (mod submission queue length) of next element to add
533 <     * in submission queue.
534 <     */
535 <    int queueTop;
1241 >    // Instance fields
1242  
1243 <    /**
1244 <     * True when shutdown() has been called.
1245 <     */
1246 <    volatile boolean shutdown;
1243 >    /*
1244 >     * Field layout order in this class tends to matter more than one
1245 >     * would like. Runtime layout order is only loosely related to
1246 >     * declaration order and may differ across JVMs, but the following
1247 >     * empirically works OK on current JVMs.
1248 >     */
1249 >
1250 >    volatile long ctl;                         // main pool control
1251 >    final int parallelism;                     // parallelism level
1252 >    final int localMode;                       // per-worker scheduling mode
1253 >    final int submitMask;                      // submit queue index bound
1254 >    int nextSeed;                              // for initializing worker seeds
1255 >    volatile int runState;                     // shutdown status and seq
1256 >    WorkQueue[] workQueues;                    // main registry
1257 >    final Mutex lock;                          // for registration
1258 >    final Condition termination;               // for awaitTermination
1259 >    final ForkJoinWorkerThreadFactory factory; // factory for new workers
1260 >    final Thread.UncaughtExceptionHandler ueh; // per-worker UEH
1261 >    final AtomicLong stealCount;               // collect counts when terminated
1262 >    final AtomicInteger nextWorkerNumber;      // to create worker name string
1263 >    final String workerNamePrefix;             // to create worker name string
1264  
1265 <    /**
543 <     * True if use local fifo, not default lifo, for local polling
544 <     * Read by, and replicated by ForkJoinWorkerThreads
545 <     */
546 <    final boolean locallyFifo;
1265 >    //  Creating, registering, and deregistering workers
1266  
1267      /**
1268 <     * The number of threads in ForkJoinWorkerThreads.helpQuiescePool.
550 <     * When non-zero, suppresses automatic shutdown when active
551 <     * counts become zero.
1268 >     * Tries to create and start a worker
1269       */
1270 <    volatile int quiescerCount;
1270 >    private void addWorker() {
1271 >        Throwable ex = null;
1272 >        ForkJoinWorkerThread wt = null;
1273 >        try {
1274 >            if ((wt = factory.newThread(this)) != null) {
1275 >                wt.start();
1276 >                return;
1277 >            }
1278 >        } catch (Throwable e) {
1279 >            ex = e;
1280 >        }
1281 >        deregisterWorker(wt, ex); // adjust counts etc on failure
1282 >    }
1283  
1284      /**
1285 <     * The number of threads blocked in join.
1285 >     * Callback from ForkJoinWorkerThread constructor to assign a
1286 >     * public name. This must be separate from registerWorker because
1287 >     * it is called during the "super" constructor call in
1288 >     * ForkJoinWorkerThread.
1289       */
1290 <    volatile int blockedCount;
1290 >    final String nextWorkerName() {
1291 >        return workerNamePrefix.concat
1292 >            (Integer.toString(nextWorkerNumber.addAndGet(1)));
1293 >    }
1294  
1295      /**
1296 <     * Counter for worker Thread names (unrelated to their poolIndex)
1296 >     * Callback from ForkJoinWorkerThread constructor to establish its
1297 >     * poolIndex and record its WorkQueue. To avoid scanning bias due
1298 >     * to packing entries in front of the workQueues array, we treat
1299 >     * the array as a simple power-of-two hash table using per-thread
1300 >     * seed as hash, expanding as needed.
1301 >     *
1302 >     * @param w the worker's queue
1303       */
563    private volatile int nextWorkerNumber;
1304  
1305 <    /**
1306 <     * The index for the next created worker. Accessed under scanGuard.
1307 <     */
1308 <    private int nextWorkerIndex;
1305 >    final void registerWorker(WorkQueue w) {
1306 >        Mutex lock = this.lock;
1307 >        lock.lock();
1308 >        try {
1309 >            WorkQueue[] ws = workQueues;
1310 >            if (w != null && ws != null) {          // skip on shutdown/failure
1311 >                int rs, n =  ws.length, m = n - 1;
1312 >                int s = nextSeed += SEED_INCREMENT; // rarely-colliding sequence
1313 >                w.seed = (s == 0) ? 1 : s;          // ensure non-zero seed
1314 >                int r = (s << 1) | 1;               // use odd-numbered indices
1315 >                if (ws[r &= m] != null) {           // collision
1316 >                    int probes = 0;                 // step by approx half size
1317 >                    int step = (n <= 4) ? 2 : ((n >>> 1) & SQMASK) + 2;
1318 >                    while (ws[r = (r + step) & m] != null) {
1319 >                        if (++probes >= n) {
1320 >                            workQueues = ws = Arrays.copyOf(ws, n <<= 1);
1321 >                            m = n - 1;
1322 >                            probes = 0;
1323 >                        }
1324 >                    }
1325 >                }
1326 >                w.eventCount = w.poolIndex = r;     // establish before recording
1327 >                ws[r] = w;                          // also update seq
1328 >                runState = ((rs = runState) & SHUTDOWN) | ((rs + 2) & ~SHUTDOWN);
1329 >            }
1330 >        } finally {
1331 >            lock.unlock();
1332 >        }
1333 >    }
1334  
1335      /**
1336 <     * SeqLock and index masking for for updates to workers array.
1337 <     * Locked when SG_UNIT is set. Unlocking clears bit by adding
1338 <     * SG_UNIT. Staleness of read-only operations can be checked by
1339 <     * comparing scanGuard to value before the reads. The low 16 bits
1340 <     * (i.e, anding with SMASK) hold (the smallest power of two
1341 <     * covering all worker indices, minus one, and is used to avoid
1342 <     * dealing with large numbers of null slots when the workers array
578 <     * is overallocated.
1336 >     * Final callback from terminating worker, as well as upon failure
1337 >     * to construct or start a worker in addWorker.  Removes record of
1338 >     * worker from array, and adjusts counts. If pool is shutting
1339 >     * down, tries to complete termination.
1340 >     *
1341 >     * @param wt the worker thread or null if addWorker failed
1342 >     * @param ex the exception causing failure, or null if none
1343       */
1344 <    volatile int scanGuard;
1345 <
1346 <    private static final int SG_UNIT = 1 << 16;
1344 >    final void deregisterWorker(ForkJoinWorkerThread wt, Throwable ex) {
1345 >        Mutex lock = this.lock;
1346 >        WorkQueue w = null;
1347 >        if (wt != null && (w = wt.workQueue) != null) {
1348 >            w.runState = -1;                // ensure runState is set
1349 >            stealCount.getAndAdd(w.totalSteals + w.nsteals);
1350 >            int idx = w.poolIndex;
1351 >            lock.lock();
1352 >            try {                           // remove record from array
1353 >                WorkQueue[] ws = workQueues;
1354 >                if (ws != null && idx >= 0 && idx < ws.length && ws[idx] == w)
1355 >                    ws[idx] = null;
1356 >            } finally {
1357 >                lock.unlock();
1358 >            }
1359 >        }
1360  
1361 <    /**
1362 <     * The wakeup interval (in nanoseconds) for a worker waiting for a
1363 <     * task when the pool is quiescent to instead try to shrink the
1364 <     * number of workers.  The exact value does not matter too
1365 <     * much. It must be short enough to release resources during
589 <     * sustained periods of idleness, but not so short that threads
590 <     * are continually re-created.
591 <     */
592 <    private static final long SHRINK_RATE =
593 <        4L * 1000L * 1000L * 1000L; // 4 seconds
1361 >        long c;                             // adjust ctl counts
1362 >        do {} while (!U.compareAndSwapLong
1363 >                     (this, CTL, c = ctl, (((c - AC_UNIT) & AC_MASK) |
1364 >                                           ((c - TC_UNIT) & TC_MASK) |
1365 >                                           (c & ~(AC_MASK|TC_MASK)))));
1366  
1367 <    /**
1368 <     * Top-level loop for worker threads: On each step: if the
1369 <     * previous step swept through all queues and found no tasks, or
1370 <     * there are excess threads, then possibly blocks. Otherwise,
1371 <     * scans for and, if found, executes a task. Returns when pool
1372 <     * and/or worker terminate.
601 <     *
602 <     * @param w the worker
603 <     */
604 <    final void work(ForkJoinWorkerThread w) {
605 <        boolean swept = false;                // true on empty scans
606 <        long c;
607 <        while (!w.terminate && (int)(c = ctl) >= 0) {
608 <            int a;                            // active count
609 <            if (!swept && (a = (int)(c >> AC_SHIFT)) <= 0)
610 <                swept = scan(w, a);
611 <            else if (tryAwaitWork(w, c))
612 <                swept = false;
1367 >        if (!tryTerminate(false, false) && w != null) {
1368 >            w.cancelAll();                  // cancel remaining tasks
1369 >            if (w.array != null)            // suppress signal if never ran
1370 >                signalWork();               // wake up or create replacement
1371 >            if (ex == null)                 // help clean refs on way out
1372 >                ForkJoinTask.helpExpungeStaleExceptions();
1373          }
1374 +
1375 +        if (ex != null)                     // rethrow
1376 +            U.throwException(ex);
1377      }
1378  
1379 <    // Signalling
1379 >
1380 >    // Submissions
1381  
1382      /**
1383 <     * Wakes up or creates a worker.
1384 <     */
1385 <    final void signalWork() {
1386 <        /*
1387 <         * The while condition is true if: (there is are too few total
1388 <         * workers OR there is at least one waiter) AND (there are too
1389 <         * few active workers OR the pool is terminating).  The value
1390 <         * of e distinguishes the remaining cases: zero (no waiters)
1391 <         * for create, negative if terminating (in which case do
1392 <         * nothing), else release a waiter. The secondary checks for
1393 <         * release (non-null array etc) can fail if the pool begins
1394 <         * terminating after the test, and don't impose any added cost
1395 <         * because JVMs must perform null and bounds checks anyway.
1396 <         */
1397 <        long c; int e, u;
1398 <        while ((((e = (int)(c = ctl)) | (u = (int)(c >>> 32))) &
1399 <                (INT_SIGN|SHORT_SIGN)) == (INT_SIGN|SHORT_SIGN) && e >= 0) {
1400 <            if (e > 0) {                         // release a waiting worker
1401 <                int i; ForkJoinWorkerThread w; ForkJoinWorkerThread[] ws;
1402 <                if ((ws = workers) == null ||
1403 <                    (i = ~e & SMASK) >= ws.length ||
1404 <                    (w = ws[i]) == null)
1405 <                    break;
1406 <                long nc = (((long)(w.nextWait & E_MASK)) |
1407 <                           ((long)(u + UAC_UNIT) << 32));
1408 <                if (w.eventCount == e &&
1409 <                    UNSAFE.compareAndSwapLong(this, ctlOffset, c, nc)) {
1410 <                    w.eventCount = (e + EC_UNIT) & E_MASK;
647 <                    if (w.parked)
648 <                        UNSAFE.unpark(w);
649 <                    break;
1383 >     * Unless shutting down, adds the given task to a submission queue
1384 >     * at submitter's current queue index (modulo submission
1385 >     * range). If no queue exists at the index, one is created.  If
1386 >     * the queue is busy, another index is randomly chosen. The
1387 >     * submitMask bounds the effective number of queues to the
1388 >     * (nearest power of two for) parallelism level.
1389 >     *
1390 >     * @param task the task. Caller must ensure non-null.
1391 >     */
1392 >    private void doSubmit(ForkJoinTask<?> task) {
1393 >        Submitter s = submitters.get();
1394 >        for (int r = s.seed, m = submitMask;;) {
1395 >            WorkQueue[] ws; WorkQueue q;
1396 >            int k = r & m & SQMASK;          // use only even indices
1397 >            if (runState < 0 || (ws = workQueues) == null || ws.length <= k)
1398 >                throw new RejectedExecutionException(); // shutting down
1399 >            else if ((q = ws[k]) == null) {  // create new queue
1400 >                WorkQueue nq = new WorkQueue(this, null, SHARED_QUEUE);
1401 >                Mutex lock = this.lock;      // construct outside lock
1402 >                lock.lock();
1403 >                try {                        // recheck under lock
1404 >                    int rs = runState;       // to update seq
1405 >                    if (ws == workQueues && ws[k] == null) {
1406 >                        ws[k] = nq;
1407 >                        runState = ((rs & SHUTDOWN) | ((rs + 2) & ~SHUTDOWN));
1408 >                    }
1409 >                } finally {
1410 >                    lock.unlock();
1411                  }
1412              }
1413 <            else if (UNSAFE.compareAndSwapLong
1414 <                     (this, ctlOffset, c,
1415 <                      (long)(((u + UTC_UNIT) & UTC_MASK) |
1416 <                             ((u + UAC_UNIT) & UAC_MASK)) << 32)) {
1417 <                addWorker();
1418 <                break;
1413 >            else if (q.trySharedPush(task)) {
1414 >                signalWork();
1415 >                return;
1416 >            }
1417 >            else if (m > 1) {                // move to a different index
1418 >                r ^= r << 13;                // same xorshift as WorkQueues
1419 >                r ^= r >>> 17;
1420 >                s.seed = r ^= r << 5;
1421              }
1422 +            else
1423 +                Thread.yield();              // yield if no alternatives
1424          }
1425      }
1426  
1427 +    // Maintaining ctl counts
1428 +
1429      /**
1430 <     * Variant of signalWork to help release waiters on rescans.
664 <     * Tries once to release a waiter if active count < 0.
665 <     *
666 <     * @return false if failed due to contention, else true
1430 >     * Increments active count; mainly called upon return from blocking.
1431       */
1432 <    private boolean tryReleaseWaiter() {
1433 <        long c; int e, i; ForkJoinWorkerThread w; ForkJoinWorkerThread[] ws;
1434 <        if ((e = (int)(c = ctl)) > 0 &&
671 <            (int)(c >> AC_SHIFT) < 0 &&
672 <            (ws = workers) != null &&
673 <            (i = ~e & SMASK) < ws.length &&
674 <            (w = ws[i]) != null) {
675 <            long nc = ((long)(w.nextWait & E_MASK) |
676 <                       ((c + AC_UNIT) & (AC_MASK|TC_MASK)));
677 <            if (w.eventCount != e ||
678 <                !UNSAFE.compareAndSwapLong(this, ctlOffset, c, nc))
679 <                return false;
680 <            w.eventCount = (e + EC_UNIT) & E_MASK;
681 <            if (w.parked)
682 <                UNSAFE.unpark(w);
683 <        }
684 <        return true;
1432 >    final void incrementActiveCount() {
1433 >        long c;
1434 >        do {} while (!U.compareAndSwapLong(this, CTL, c = ctl, c + AC_UNIT));
1435      }
1436  
687    // Scanning for tasks
688
1437      /**
1438 <     * Scans for and, if found, executes one task. Scans start at a
1439 <     * random index of workers array, and randomly select the first
1440 <     * (2*#workers)-1 probes, and then, if all empty, resort to 2
1441 <     * circular sweeps, which is necessary to check quiescence. and
1442 <     * taking a submission only if no stealable tasks were found.  The
1443 <     * steal code inside the loop is a specialized form of
1444 <     * ForkJoinWorkerThread.deqTask, followed bookkeeping to support
1445 <     * helpJoinTask and signal propagation. The code for submission
1446 <     * queues is almost identical. On each steal, the worker completes
1447 <     * not only the task, but also all local tasks that this task may
1448 <     * have generated. On detecting staleness or contention when
1449 <     * trying to take a task, this method returns without finishing
1450 <     * sweep, which allows global state rechecks before retry.
1451 <     *
1452 <     * @param w the worker
1453 <     * @param a the number of active workers
1454 <     * @return true if swept all queues without finding a task
707 <     */
708 <    private boolean scan(ForkJoinWorkerThread w, int a) {
709 <        int g = scanGuard; // mask 0 avoids useless scans if only one active
710 <        int m = parallelism == 1 - a? 0 : g & SMASK;
711 <        ForkJoinWorkerThread[] ws = workers;
712 <        if (ws == null || ws.length <= m)         // staleness check
713 <            return false;
714 <        for (int r = w.seed, k = r, j = -(m + m); j <= m + m; ++j) {
715 <            ForkJoinTask<?> t; ForkJoinTask<?>[] q; int b, i;
716 <            ForkJoinWorkerThread v = ws[k & m];
717 <            if (v != null && (b = v.queueBase) != v.queueTop &&
718 <                (q = v.queue) != null && (i = (q.length - 1) & b) >= 0) {
719 <                long u = (i << ASHIFT) + ABASE;
720 <                if ((t = q[i]) != null && v.queueBase == b &&
721 <                    UNSAFE.compareAndSwapObject(q, u, t, null)) {
722 <                    int d = (v.queueBase = b + 1) - v.queueTop;
723 <                    v.stealHint = w.poolIndex;
724 <                    if (d != 0)
725 <                        signalWork();             // propagate if nonempty
726 <                    w.execTask(t);
1438 >     * Tries to activate or create a worker if too few are active.
1439 >     */
1440 >    final void signalWork() {
1441 >        long c; int u;
1442 >        while ((u = (int)((c = ctl) >>> 32)) < 0) {     // too few active
1443 >            WorkQueue[] ws = workQueues; int e, i; WorkQueue w; Thread p;
1444 >            if ((e = (int)c) > 0) {                     // at least one waiting
1445 >                if (ws != null && (i = e & SMASK) < ws.length &&
1446 >                    (w = ws[i]) != null && w.eventCount == (e | INT_SIGN)) {
1447 >                    long nc = (((long)(w.nextWait & E_MASK)) |
1448 >                               ((long)(u + UAC_UNIT) << 32));
1449 >                    if (U.compareAndSwapLong(this, CTL, c, nc)) {
1450 >                        w.eventCount = (e + E_SEQ) & E_MASK;
1451 >                        if ((p = w.parker) != null)
1452 >                            U.unpark(p);                // activate and release
1453 >                        break;
1454 >                    }
1455                  }
1456 <                r ^= r << 13; r ^= r >>> 17; w.seed = r ^ (r << 5);
1457 <                return false;                     // store next seed
730 <            }
731 <            else if (j < 0) {                     // xorshift
732 <                r ^= r << 13; r ^= r >>> 17; k = r ^= r << 5;
1456 >                else
1457 >                    break;
1458              }
1459 <            else
1460 <                ++k;
1461 <        }
1462 <        if (scanGuard != g)                       // staleness check
1463 <            return false;
1464 <        else {                                    // try to take submission
740 <            ForkJoinTask<?> t; ForkJoinTask<?>[] q; int b, i;
741 <            if ((b = queueBase) != queueTop &&
742 <                (q = submissionQueue) != null &&
743 <                (i = (q.length - 1) & b) >= 0) {
744 <                long u = (i << ASHIFT) + ABASE;
745 <                if ((t = q[i]) != null && queueBase == b &&
746 <                    UNSAFE.compareAndSwapObject(q, u, t, null)) {
747 <                    queueBase = b + 1;
748 <                    w.execTask(t);
1459 >            else if (e == 0 && (u & SHORT_SIGN) != 0) { // too few total
1460 >                long nc = (long)(((u + UTC_UNIT) & UTC_MASK) |
1461 >                                 ((u + UAC_UNIT) & UAC_MASK)) << 32;
1462 >                if (U.compareAndSwapLong(this, CTL, c, nc)) {
1463 >                    addWorker();
1464 >                    break;
1465                  }
750                return false;
1466              }
1467 <            return true;                         // all queues empty
1467 >            else
1468 >                break;
1469          }
1470      }
1471  
1472 +    // Scanning for tasks
1473 +
1474      /**
1475 <     * Tries to enqueue worker in wait queue and await change in
758 <     * worker's eventCount.  Before blocking, rescans queues to avoid
759 <     * missed signals.  If the pool is quiescent, possibly terminates
760 <     * worker upon exit.
761 <     *
762 <     * @param w the calling worker
763 <     * @param c the ctl value on entry
764 <     * @return true if waited or another thread was released upon enq
1475 >     * Top-level runloop for workers, called by ForkJoinWorkerThread.run.
1476       */
1477 <    private boolean tryAwaitWork(ForkJoinWorkerThread w, long c) {
1478 <        int v = w.eventCount;
1479 <        w.nextWait = (int)c;                       // w's successor record
1480 <        long nc = (long)(v & E_MASK) | ((c - AC_UNIT) & (AC_MASK|TC_MASK));
1481 <        if (ctl != c || !UNSAFE.compareAndSwapLong(this, ctlOffset, c, nc)) {
1482 <            long d = ctl; // return true if lost to a deq, to force rescan
1483 <            return (int)d != (int)c && ((d - c) & AC_MASK) >= 0L;
1484 <        }
1485 <        if (parallelism + (int)(c >> AC_SHIFT) == 1 &&
1486 <            blockedCount == 0 && quiescerCount == 0)
1487 <            idleAwaitWork(w, v);               // quiescent -- maybe shrink
1488 <
1489 <        boolean rescanned = false;
1490 <        for (int sc;;) {
1491 <            if (w.eventCount != v)
1492 <                return true;
1493 <            if ((sc = w.stealCount) != 0) {
1494 <                long s = stealCount;               // accumulate stealCount
1495 <                if (UNSAFE.compareAndSwapLong(this, stealCountOffset, s, s+sc))
1496 <                    w.stealCount = 0;
1497 <            }
1498 <            else if (!rescanned) {
1499 <                int g = scanGuard, m = g & SMASK;
1500 <                ForkJoinWorkerThread[] ws = workers;
1501 <                if (ws != null && m < ws.length) {
1502 <                    rescanned = true;
1503 <                    for (int i = 0; i <= m; ++i) {
1504 <                        ForkJoinWorkerThread u = ws[i];
1505 <                        if (u != null) {
1506 <                            if (u.queueBase != u.queueTop &&
1507 <                                !tryReleaseWaiter())
1508 <                                rescanned = false; // contended
1509 <                            if (w.eventCount != v)
1510 <                                return true;
1511 <                        }
1477 >    final void runWorker(WorkQueue w) {
1478 >        w.growArray(false);         // initialize queue array in this thread
1479 >        do { w.runTask(scan(w)); } while (w.runState >= 0);
1480 >    }
1481 >
1482 >    /**
1483 >     * Scans for and, if found, returns one task, else possibly
1484 >     * inactivates the worker. This method operates on single reads of
1485 >     * volatile state and is designed to be re-invoked continuously,
1486 >     * in part because it returns upon detecting inconsistencies,
1487 >     * contention, or state changes that indicate possible success on
1488 >     * re-invocation.
1489 >     *
1490 >     * The scan searches for tasks across a random permutation of
1491 >     * queues (starting at a random index and stepping by a random
1492 >     * relative prime, checking each at least once).  The scan
1493 >     * terminates upon either finding a non-empty queue, or completing
1494 >     * the sweep. If the worker is not inactivated, it takes and
1495 >     * returns a task from this queue.  On failure to find a task, we
1496 >     * take one of the following actions, after which the caller will
1497 >     * retry calling this method unless terminated.
1498 >     *
1499 >     * * If pool is terminating, terminate the worker.
1500 >     *
1501 >     * * If not a complete sweep, try to release a waiting worker.  If
1502 >     * the scan terminated because the worker is inactivated, then the
1503 >     * released worker will often be the calling worker, and it can
1504 >     * succeed obtaining a task on the next call. Or maybe it is
1505 >     * another worker, but with same net effect. Releasing in other
1506 >     * cases as well ensures that we have enough workers running.
1507 >     *
1508 >     * * If not already enqueued, try to inactivate and enqueue the
1509 >     * worker on wait queue. Or, if inactivating has caused the pool
1510 >     * to be quiescent, relay to idleAwaitWork to check for
1511 >     * termination and possibly shrink pool.
1512 >     *
1513 >     * * If already inactive, and the caller has run a task since the
1514 >     * last empty scan, return (to allow rescan) unless others are
1515 >     * also inactivated.  Field WorkQueue.rescans counts down on each
1516 >     * scan to ensure eventual inactivation and blocking.
1517 >     *
1518 >     * * If already enqueued and none of the above apply, park
1519 >     * awaiting signal,
1520 >     *
1521 >     * @param w the worker (via its WorkQueue)
1522 >     * @return a task or null of none found
1523 >     */
1524 >    private final ForkJoinTask<?> scan(WorkQueue w) {
1525 >        WorkQueue[] ws;                       // first update random seed
1526 >        int r = w.seed; r ^= r << 13; r ^= r >>> 17; w.seed = r ^= r << 5;
1527 >        int rs = runState, m;                 // volatile read order matters
1528 >        if ((ws = workQueues) != null && (m = ws.length - 1) > 0) {
1529 >            int ec = w.eventCount;            // ec is negative if inactive
1530 >            int step = (r >>> 16) | 1;        // relative prime
1531 >            for (int j = (m + 1) << 2; ; r += step) {
1532 >                WorkQueue q; ForkJoinTask<?> t; ForkJoinTask<?>[] a; int b;
1533 >                if ((q = ws[r & m]) != null && (b = q.base) - q.top < 0 &&
1534 >                    (a = q.array) != null) {  // probably nonempty
1535 >                    int i = (((a.length - 1) & b) << ASHIFT) + ABASE;
1536 >                    t = (ForkJoinTask<?>)U.getObjectVolatile(a, i);
1537 >                    if (q.base == b && ec >= 0 && t != null &&
1538 >                        U.compareAndSwapObject(a, i, t, null)) {
1539 >                        if (q.top - (q.base = b + 1) > 1)
1540 >                            signalWork();    // help pushes signal
1541 >                        return t;
1542 >                    }
1543 >                    else if (ec < 0 || j <= m) {
1544 >                        rs = 0;               // mark scan as imcomplete
1545 >                        break;                // caller can retry after release
1546                      }
1547                  }
1548 <                if (scanGuard != g ||              // stale
1549 <                    (queueBase != queueTop && !tryReleaseWaiter()))
805 <                    rescanned = false;
806 <                if (!rescanned)
807 <                    Thread.yield();                // reduce contention
808 <                else
809 <                    Thread.interrupted();          // clear before park
1548 >                if (--j < 0)
1549 >                    break;
1550              }
1551 <            else {
1552 <                w.parked = true;                   // must recheck
1553 <                if (w.eventCount != v) {
1554 <                    w.parked = false;
1555 <                    return true;
1551 >
1552 >            long c = ctl; int e = (int)c, a = (int)(c >> AC_SHIFT), nr, ns;
1553 >            if (e < 0)                        // decode ctl on empty scan
1554 >                w.runState = -1;              // pool is terminating
1555 >            else if (rs == 0 || rs != runState) { // incomplete scan
1556 >                WorkQueue v; Thread p;        // try to release a waiter
1557 >                if (e > 0 && a < 0 && w.eventCount == ec &&
1558 >                    (v = ws[e & m]) != null && v.eventCount == (e | INT_SIGN)) {
1559 >                    long nc = ((long)(v.nextWait & E_MASK) |
1560 >                               ((c + AC_UNIT) & (AC_MASK|TC_MASK)));
1561 >                    if (ctl == c && U.compareAndSwapLong(this, CTL, c, nc)) {
1562 >                        v.eventCount = (e + E_SEQ) & E_MASK;
1563 >                        if ((p = v.parker) != null)
1564 >                            U.unpark(p);
1565 >                    }
1566 >                }
1567 >            }
1568 >            else if (ec >= 0) {               // try to enqueue/inactivate
1569 >                long nc = (long)ec | ((c - AC_UNIT) & (AC_MASK|TC_MASK));
1570 >                w.nextWait = e;
1571 >                w.eventCount = ec | INT_SIGN; // mark as inactive
1572 >                if (ctl != c || !U.compareAndSwapLong(this, CTL, c, nc))
1573 >                    w.eventCount = ec;        // unmark on CAS failure
1574 >                else {
1575 >                    if ((ns = w.nsteals) != 0) {
1576 >                        w.nsteals = 0;        // set rescans if ran task
1577 >                        w.rescans = (a > 0) ? 0 : a + parallelism;
1578 >                        w.totalSteals += ns;
1579 >                    }
1580 >                    if (a == 1 - parallelism) // quiescent
1581 >                        idleAwaitWork(w, nc, c);
1582 >                }
1583 >            }
1584 >            else if (w.eventCount < 0) {      // already queued
1585 >                if ((nr = w.rescans) > 0) {   // continue rescanning
1586 >                    int ac = a + parallelism;
1587 >                    if (((w.rescans = (ac < nr) ? ac : nr - 1) & 3) == 0)
1588 >                        Thread.yield();       // yield before block
1589 >                }
1590 >                else {
1591 >                    Thread.interrupted();     // clear status
1592 >                    Thread wt = Thread.currentThread();
1593 >                    U.putObject(wt, PARKBLOCKER, this);
1594 >                    w.parker = wt;            // emulate LockSupport.park
1595 >                    if (w.eventCount < 0)     // recheck
1596 >                        U.park(false, 0L);
1597 >                    w.parker = null;
1598 >                    U.putObject(wt, PARKBLOCKER, null);
1599                  }
817                LockSupport.park(this);
818                rescanned = w.parked = false;
1600              }
1601          }
1602 +        return null;
1603      }
1604  
1605      /**
1606 <     * If pool is quiescent, checks for termination, and waits for
1607 <     * event signal for up to SHRINK_RATE nanosecs. On timeout, if ctl
1608 <     * has not changed, terminates the worker. Upon its termination
1609 <     * (see deregisterWorker), it may wake up another worker to
1610 <     * possibly repeat this process.
1606 >     * If inactivating worker w has caused the pool to become
1607 >     * quiescent, checks for pool termination, and, so long as this is
1608 >     * not the only worker, waits for event for up to SHRINK_RATE
1609 >     * nanosecs.  On timeout, if ctl has not changed, terminates the
1610 >     * worker, which will in turn wake up another worker to possibly
1611 >     * repeat this process.
1612       *
1613       * @param w the calling worker
1614 <     * @param v the eventCount w must wait until changed
1614 >     * @param currentCtl the ctl value triggering possible quiescence
1615 >     * @param prevCtl the ctl value to restore if thread is terminated
1616       */
1617 <    private void idleAwaitWork(ForkJoinWorkerThread w, int v) {
1618 <        ForkJoinTask.helpExpungeStaleExceptions(); // help clean weak refs
1619 <        if (shutdown)
1620 <            tryTerminate(false);
1621 <        long c = ctl;
1622 <        long nc = (((c & (AC_MASK|TC_MASK)) + AC_UNIT) |
1623 <                   (long)(w.nextWait & E_MASK)); // ctl value to release w
1624 <        if (w.eventCount == v &&
1625 <            parallelism + (int)(c >> AC_SHIFT) == 0 &&
1626 <            blockedCount == 0 && quiescerCount == 0) {
1627 <            long startTime = System.nanoTime();
1628 <            Thread.interrupted();
1629 <            if (w.eventCount == v) {
1630 <                w.parked = true;
1631 <                if (w.eventCount == v)
1632 <                    LockSupport.parkNanos(this, SHRINK_RATE);
1633 <                w.parked = false;
1634 <                if (w.eventCount == v && ctl == c &&
1635 <                    System.nanoTime() - startTime >= SHRINK_RATE &&
1636 <                    UNSAFE.compareAndSwapLong(this, ctlOffset, c, nc)) {
1637 <                    w.terminate = true;
854 <                    w.eventCount = ((int)c + EC_UNIT) & E_MASK;
1617 >    private void idleAwaitWork(WorkQueue w, long currentCtl, long prevCtl) {
1618 >        if (w.eventCount < 0 && !tryTerminate(false, false) &&
1619 >            (int)prevCtl != 0 && !hasQueuedSubmissions() && ctl == currentCtl) {
1620 >            Thread wt = Thread.currentThread();
1621 >            Thread.yield();            // yield before block
1622 >            while (ctl == currentCtl) {
1623 >                long startTime = System.nanoTime();
1624 >                Thread.interrupted();  // timed variant of version in scan()
1625 >                U.putObject(wt, PARKBLOCKER, this);
1626 >                w.parker = wt;
1627 >                if (ctl == currentCtl)
1628 >                    U.park(false, SHRINK_RATE);
1629 >                w.parker = null;
1630 >                U.putObject(wt, PARKBLOCKER, null);
1631 >                if (ctl != currentCtl)
1632 >                    break;
1633 >                if (System.nanoTime() - startTime >= SHRINK_TIMEOUT &&
1634 >                    U.compareAndSwapLong(this, CTL, currentCtl, prevCtl)) {
1635 >                    w.eventCount = (w.eventCount + E_SEQ) | E_MASK;
1636 >                    w.runState = -1;   // shrink
1637 >                    break;
1638                  }
1639              }
1640          }
1641      }
1642  
860    // Submissions
861
1643      /**
1644 <     * Enqueues the given task in the submissionQueue.  Same idea as
1645 <     * ForkJoinWorkerThread.pushTask except for use of submissionLock.
1646 <     *
1647 <     * @param t the task
1648 <     */
1649 <    private void addSubmission(ForkJoinTask<?> t) {
1650 <        final ReentrantLock lock = this.submissionLock;
1651 <        lock.lock();
1652 <        try {
1653 <            ForkJoinTask<?>[] q; int s, m;
1654 <            if ((q = submissionQueue) != null) {    // ignore if queue removed
1655 <                long u = (((s = queueTop) & (m = q.length-1)) << ASHIFT)+ABASE;
1656 <                UNSAFE.putOrderedObject(q, u, t);
1657 <                queueTop = s + 1;
1658 <                if (s - queueBase == m)
1659 <                    growSubmissionQueue();
1644 >     * Tries to locate and execute tasks for a stealer of the given
1645 >     * task, or in turn one of its stealers, Traces currentSteal ->
1646 >     * currentJoin links looking for a thread working on a descendant
1647 >     * of the given task and with a non-empty queue to steal back and
1648 >     * execute tasks from. The first call to this method upon a
1649 >     * waiting join will often entail scanning/search, (which is OK
1650 >     * because the joiner has nothing better to do), but this method
1651 >     * leaves hints in workers to speed up subsequent calls. The
1652 >     * implementation is very branchy to cope with potential
1653 >     * inconsistencies or loops encountering chains that are stale,
1654 >     * unknown, or so long that they are likely cyclic.
1655 >     *
1656 >     * @param joiner the joining worker
1657 >     * @param task the task to join
1658 >     * @return 0 if no progress can be made, negative if task
1659 >     * known complete, else positive
1660 >     */
1661 >    private int tryHelpStealer(WorkQueue joiner, ForkJoinTask<?> task) {
1662 >        int stat = 0, steps = 0;                    // bound to avoid cycles
1663 >        if (joiner != null && task != null) {       // hoist null checks
1664 >            restart: for (;;) {
1665 >                ForkJoinTask<?> subtask = task;     // current target
1666 >                for (WorkQueue j = joiner, v;;) {   // v is stealer of subtask
1667 >                    WorkQueue[] ws; int m, s, h;
1668 >                    if ((s = task.status) < 0) {
1669 >                        stat = s;
1670 >                        break restart;
1671 >                    }
1672 >                    if ((ws = workQueues) == null || (m = ws.length - 1) <= 0)
1673 >                        break restart;              // shutting down
1674 >                    if ((v = ws[h = (j.stealHint | 1) & m]) == null ||
1675 >                        v.currentSteal != subtask) {
1676 >                        for (int origin = h;;) {    // find stealer
1677 >                            if (((h = (h + 2) & m) & 15) == 1 &&
1678 >                                (subtask.status < 0 || j.currentJoin != subtask))
1679 >                                continue restart;   // occasional staleness check
1680 >                            if ((v = ws[h]) != null &&
1681 >                                v.currentSteal == subtask) {
1682 >                                j.stealHint = h;    // save hint
1683 >                                break;
1684 >                            }
1685 >                            if (h == origin)
1686 >                                break restart;      // cannot find stealer
1687 >                        }
1688 >                    }
1689 >                    for (;;) { // help stealer or descend to its stealer
1690 >                        ForkJoinTask[] a;  int b;
1691 >                        if (subtask.status < 0)     // surround probes with
1692 >                            continue restart;       //   consistency checks
1693 >                        if ((b = v.base) - v.top < 0 && (a = v.array) != null) {
1694 >                            int i = (((a.length - 1) & b) << ASHIFT) + ABASE;
1695 >                            ForkJoinTask<?> t =
1696 >                                (ForkJoinTask<?>)U.getObjectVolatile(a, i);
1697 >                            if (subtask.status < 0 || j.currentJoin != subtask ||
1698 >                                v.currentSteal != subtask)
1699 >                                continue restart;   // stale
1700 >                            stat = 1;               // apparent progress
1701 >                            if (t != null && v.base == b &&
1702 >                                U.compareAndSwapObject(a, i, t, null)) {
1703 >                                v.base = b + 1;     // help stealer
1704 >                                joiner.runSubtask(t);
1705 >                            }
1706 >                            else if (v.base == b && ++steps == MAX_HELP)
1707 >                                break restart;      // v apparently stalled
1708 >                        }
1709 >                        else {                      // empty -- try to descend
1710 >                            ForkJoinTask<?> next = v.currentJoin;
1711 >                            if (subtask.status < 0 || j.currentJoin != subtask ||
1712 >                                v.currentSteal != subtask)
1713 >                                continue restart;   // stale
1714 >                            else if (next == null || ++steps == MAX_HELP)
1715 >                                break restart;      // dead-end or maybe cyclic
1716 >                            else {
1717 >                                subtask = next;
1718 >                                j = v;
1719 >                                break;
1720 >                            }
1721 >                        }
1722 >                    }
1723 >                }
1724              }
880        } finally {
881            lock.unlock();
1725          }
1726 <        signalWork();
1726 >        return stat;
1727      }
1728  
886    //  (pollSubmission is defined below with exported methods)
887
1729      /**
1730 <     * Creates or doubles submissionQueue array.
1731 <     * Basically identical to ForkJoinWorkerThread version
1730 >     * If task is at base of some steal queue, steals and executes it.
1731 >     *
1732 >     * @param joiner the joining worker
1733 >     * @param task the task
1734       */
1735 <    private void growSubmissionQueue() {
1736 <        ForkJoinTask<?>[] oldQ = submissionQueue;
1737 <        int size = oldQ != null ? oldQ.length << 1 : INITIAL_QUEUE_CAPACITY;
1738 <        if (size > MAXIMUM_QUEUE_CAPACITY)
1739 <            throw new RejectedExecutionException("Queue capacity exceeded");
1740 <        if (size < INITIAL_QUEUE_CAPACITY)
1741 <            size = INITIAL_QUEUE_CAPACITY;
1742 <        ForkJoinTask<?>[] q = submissionQueue = new ForkJoinTask<?>[size];
1743 <        int mask = size - 1;
901 <        int top = queueTop;
902 <        int oldMask;
903 <        if (oldQ != null && (oldMask = oldQ.length - 1) >= 0) {
904 <            for (int b = queueBase; b != top; ++b) {
905 <                long u = ((b & oldMask) << ASHIFT) + ABASE;
906 <                Object x = UNSAFE.getObjectVolatile(oldQ, u);
907 <                if (x != null && UNSAFE.compareAndSwapObject(oldQ, u, x, null))
908 <                    UNSAFE.putObjectVolatile
909 <                        (q, ((b & mask) << ASHIFT) + ABASE, x);
1735 >    private void tryPollForAndExec(WorkQueue joiner, ForkJoinTask<?> task) {
1736 >        WorkQueue[] ws;
1737 >        if ((ws = workQueues) != null) {
1738 >            for (int j = 1; j < ws.length && task.status >= 0; j += 2) {
1739 >                WorkQueue q = ws[j];
1740 >                if (q != null && q.pollFor(task)) {
1741 >                    joiner.runSubtask(task);
1742 >                    break;
1743 >                }
1744              }
1745          }
1746      }
1747  
914    // Blocking support
915
1748      /**
1749 <     * Tries to increment blockedCount, decrement active count
1750 <     * (sometimes implicitly) and possibly release or create a
1751 <     * compensating worker in preparation for blocking. Fails
1752 <     * on contention or termination.
1749 >     * Tries to decrement active count (sometimes implicitly) and
1750 >     * possibly release or create a compensating worker in preparation
1751 >     * for blocking. Fails on contention or termination. Otherwise,
1752 >     * adds a new thread if no idle workers are available and either
1753 >     * pool would become completely starved or: (at least half
1754 >     * starved, and fewer than 50% spares exist, and there is at least
1755 >     * one task apparently available). Even though the availability
1756 >     * check requires a full scan, it is worthwhile in reducing false
1757 >     * alarms.
1758       *
1759 +     * @param task if non-null, a task being waited for
1760 +     * @param blocker if non-null, a blocker being waited for
1761       * @return true if the caller can block, else should recheck and retry
1762       */
1763 <    private boolean tryPreBlock() {
1764 <        int b = blockedCount;
1765 <        if (UNSAFE.compareAndSwapInt(this, blockedCountOffset, b, b + 1)) {
1766 <            int pc = parallelism;
1767 <            do {
1768 <                ForkJoinWorkerThread[] ws; ForkJoinWorkerThread w;
1769 <                int e, ac, tc, rc, i;
1770 <                long c = ctl;
1771 <                int u = (int)(c >>> 32);
1772 <                if ((e = (int)c) < 0) {
1773 <                                                 // skip -- terminating
1774 <                }
1775 <                else if ((ac = (u >> UAC_SHIFT)) <= 0 && e != 0 &&
1776 <                         (ws = workers) != null &&
1777 <                         (i = ~e & SMASK) < ws.length &&
1778 <                         (w = ws[i]) != null) {
1779 <                    long nc = ((long)(w.nextWait & E_MASK) |
1780 <                               (c & (AC_MASK|TC_MASK)));
1781 <                    if (w.eventCount == e &&
943 <                        UNSAFE.compareAndSwapLong(this, ctlOffset, c, nc)) {
944 <                        w.eventCount = (e + EC_UNIT) & E_MASK;
945 <                        if (w.parked)
946 <                            UNSAFE.unpark(w);
947 <                        return true;             // release an idle worker
1763 >    final boolean tryCompensate(ForkJoinTask<?> task, ManagedBlocker blocker) {
1764 >        int pc = parallelism, e;
1765 >        long c = ctl;
1766 >        WorkQueue[] ws = workQueues;
1767 >        if ((e = (int)c) >= 0 && ws != null) {
1768 >            int u, a, ac, hc;
1769 >            int tc = (short)((u = (int)(c >>> 32)) >>> UTC_SHIFT) + pc;
1770 >            boolean replace = false;
1771 >            if ((a = u >> UAC_SHIFT) <= 0) {
1772 >                if ((ac = a + pc) <= 1)
1773 >                    replace = true;
1774 >                else if ((e > 0 || (task != null &&
1775 >                                    ac <= (hc = pc >>> 1) && tc < pc + hc))) {
1776 >                    WorkQueue w;
1777 >                    for (int j = 0; j < ws.length; ++j) {
1778 >                        if ((w = ws[j]) != null && !w.isEmpty()) {
1779 >                            replace = true;
1780 >                            break;   // in compensation range and tasks available
1781 >                        }
1782                      }
1783                  }
1784 <                else if ((tc = (short)(u >>> UTC_SHIFT)) >= 0 && ac + pc > 1) {
1784 >            }
1785 >            if ((task == null || task.status >= 0) && // recheck need to block
1786 >                (blocker == null || !blocker.isReleasable()) && ctl == c) {
1787 >                if (!replace) {          // no compensation
1788                      long nc = ((c - AC_UNIT) & AC_MASK) | (c & ~AC_MASK);
1789 <                    if (UNSAFE.compareAndSwapLong(this, ctlOffset, c, nc))
1790 <                        return true;             // no compensation needed
1789 >                    if (U.compareAndSwapLong(this, CTL, c, nc))
1790 >                        return true;
1791 >                }
1792 >                else if (e != 0) {       // release an idle worker
1793 >                    WorkQueue w; Thread p; int i;
1794 >                    if ((i = e & SMASK) < ws.length && (w = ws[i]) != null) {
1795 >                        long nc = ((long)(w.nextWait & E_MASK) |
1796 >                                   (c & (AC_MASK|TC_MASK)));
1797 >                        if (w.eventCount == (e | INT_SIGN) &&
1798 >                            U.compareAndSwapLong(this, CTL, c, nc)) {
1799 >                            w.eventCount = (e + E_SEQ) & E_MASK;
1800 >                            if ((p = w.parker) != null)
1801 >                                U.unpark(p);
1802 >                            return true;
1803 >                        }
1804 >                    }
1805                  }
1806 <                else if (tc + pc < MAX_ID) {
1806 >                else if (tc < MAX_CAP) { // create replacement
1807                      long nc = ((c + TC_UNIT) & TC_MASK) | (c & ~TC_MASK);
1808 <                    if (UNSAFE.compareAndSwapLong(this, ctlOffset, c, nc)) {
1808 >                    if (U.compareAndSwapLong(this, CTL, c, nc)) {
1809                          addWorker();
1810 <                        return true;            // create a replacement
1810 >                        return true;
1811                      }
1812                  }
1813 <                // try to back out on any failure and let caller retry
963 <            } while (!UNSAFE.compareAndSwapInt(this, blockedCountOffset,
964 <                                               b = blockedCount, b - 1));
1813 >            }
1814          }
1815          return false;
1816      }
1817  
1818      /**
1819 <     * Decrements blockedCount and increments active count
971 <     */
972 <    private void postBlock() {
973 <        long c;
974 <        do {} while (!UNSAFE.compareAndSwapLong(this, ctlOffset,  // no mask
975 <                                                c = ctl, c + AC_UNIT));
976 <        int b;
977 <        do {} while(!UNSAFE.compareAndSwapInt(this, blockedCountOffset,
978 <                                              b = blockedCount, b - 1));
979 <    }
980 <
981 <    /**
982 <     * Possibly blocks waiting for the given task to complete, or
983 <     * cancels the task if terminating.  Fails to wait if contended.
1819 >     * Helps and/or blocks until the given task is done.
1820       *
1821 <     * @param joinMe the task
1821 >     * @param joiner the joining worker
1822 >     * @param task the task
1823 >     * @return task status on exit
1824       */
1825 <    final void tryAwaitJoin(ForkJoinTask<?> joinMe) {
1825 >    final int awaitJoin(WorkQueue joiner, ForkJoinTask<?> task) {
1826          int s;
1827 <        Thread.interrupted(); // clear interrupts before checking termination
1828 <        if (joinMe.status >= 0) {
1829 <            if (tryPreBlock()) {
1830 <                joinMe.tryAwaitDone(0L);
1831 <                postBlock();
1827 >        if ((s = task.status) >= 0) {
1828 >            ForkJoinTask<?> prevJoin = joiner.currentJoin;
1829 >            joiner.currentJoin = task;
1830 >            long startTime = 0L;
1831 >            for (int k = 0;;) {
1832 >                if ((s = (joiner.isEmpty() ?           // try to help
1833 >                          tryHelpStealer(joiner, task) :
1834 >                          joiner.tryRemoveAndExec(task))) == 0 &&
1835 >                    (s = task.status) >= 0) {
1836 >                    if (k == 0) {
1837 >                        startTime = System.nanoTime();
1838 >                        tryPollForAndExec(joiner, task); // check uncommon case
1839 >                    }
1840 >                    else if ((k & (MAX_HELP - 1)) == 0 &&
1841 >                             System.nanoTime() - startTime >=
1842 >                             COMPENSATION_DELAY &&
1843 >                             tryCompensate(task, null)) {
1844 >                        if (task.trySetSignal()) {
1845 >                            synchronized (task) {
1846 >                                if (task.status >= 0) {
1847 >                                    try {                // see ForkJoinTask
1848 >                                        task.wait();     //  for explanation
1849 >                                    } catch (InterruptedException ie) {
1850 >                                    }
1851 >                                }
1852 >                                else
1853 >                                    task.notifyAll();
1854 >                            }
1855 >                        }
1856 >                        long c;                          // re-activate
1857 >                        do {} while (!U.compareAndSwapLong
1858 >                                     (this, CTL, c = ctl, c + AC_UNIT));
1859 >                    }
1860 >                }
1861 >                if (s < 0 || (s = task.status) < 0) {
1862 >                    joiner.currentJoin = prevJoin;
1863 >                    break;
1864 >                }
1865 >                else if ((k++ & (MAX_HELP - 1)) == MAX_HELP >>> 1)
1866 >                    Thread.yield();                     // for politeness
1867              }
995            if ((ctl & STOP_BIT) != 0L)
996                joinMe.cancelIgnoringExceptions();
1868          }
1869 +        return s;
1870      }
1871  
1872      /**
1873 <     * Possibly blocks the given worker waiting for joinMe to
1874 <     * complete or timeout
1873 >     * Stripped-down variant of awaitJoin used by timed joins. Tries
1874 >     * to help join only while there is continuous progress. (Caller
1875 >     * will then enter a timed wait.)
1876       *
1877 <     * @param joinMe the task
1878 <     * @param millis the wait time for underlying Object.wait
1877 >     * @param joiner the joining worker
1878 >     * @param task the task
1879 >     * @return task status on exit
1880       */
1881 <    final void timedAwaitJoin(ForkJoinTask<?> joinMe, long nanos) {
1882 <        while (joinMe.status >= 0) {
1883 <            Thread.interrupted();
1884 <            if ((ctl & STOP_BIT) != 0L) {
1885 <                joinMe.cancelIgnoringExceptions();
1886 <                break;
1887 <            }
1888 <            if (tryPreBlock()) {
1015 <                long last = System.nanoTime();
1016 <                while (joinMe.status >= 0) {
1017 <                    long millis = TimeUnit.NANOSECONDS.toMillis(nanos);
1018 <                    if (millis <= 0)
1019 <                        break;
1020 <                    joinMe.tryAwaitDone(millis);
1021 <                    if (joinMe.status < 0)
1022 <                        break;
1023 <                    if ((ctl & STOP_BIT) != 0L) {
1024 <                        joinMe.cancelIgnoringExceptions();
1025 <                        break;
1026 <                    }
1027 <                    long now = System.nanoTime();
1028 <                    nanos -= now - last;
1029 <                    last = now;
1030 <                }
1031 <                postBlock();
1032 <                break;
1033 <            }
1034 <        }
1881 >    final int helpJoinOnce(WorkQueue joiner, ForkJoinTask<?> task) {
1882 >        int s;
1883 >        while ((s = task.status) >= 0 &&
1884 >               (joiner.isEmpty() ?
1885 >                tryHelpStealer(joiner, task) :
1886 >                joiner.tryRemoveAndExec(task)) != 0)
1887 >            ;
1888 >        return s;
1889      }
1890  
1891      /**
1892 <     * If necessary, compensates for blocker, and blocks
1893 <     */
1894 <    private void awaitBlocker(ManagedBlocker blocker)
1895 <        throws InterruptedException {
1896 <        while (!blocker.isReleasable()) {
1897 <            if (tryPreBlock()) {
1898 <                try {
1899 <                    do {} while (!blocker.isReleasable() && !blocker.block());
1900 <                } finally {
1901 <                    postBlock();
1892 >     * Returns a (probably) non-empty steal queue, if one is found
1893 >     * during a random, then cyclic scan, else null.  This method must
1894 >     * be retried by caller if, by the time it tries to use the queue,
1895 >     * it is empty.
1896 >     */
1897 >    private WorkQueue findNonEmptyStealQueue(WorkQueue w) {
1898 >        // Similar to loop in scan(), but ignoring submissions
1899 >        int r = w.seed; r ^= r << 13; r ^= r >>> 17; w.seed = r ^= r << 5;
1900 >        int step = (r >>> 16) | 1;
1901 >        for (WorkQueue[] ws;;) {
1902 >            int rs = runState, m;
1903 >            if ((ws = workQueues) == null || (m = ws.length - 1) < 1)
1904 >                return null;
1905 >            for (int j = (m + 1) << 2; ; r += step) {
1906 >                WorkQueue q = ws[((r << 1) | 1) & m];
1907 >                if (q != null && !q.isEmpty())
1908 >                    return q;
1909 >                else if (--j < 0) {
1910 >                    if (runState == rs)
1911 >                        return null;
1912 >                    break;
1913                  }
1049                break;
1914              }
1915          }
1916      }
1917  
1054    // Creating, registering and deregistring workers
1055
1056    /**
1057     * Tries to create and start a worker; minimally rolls back counts
1058     * on failure.
1059     */
1060    private void addWorker() {
1061        Throwable ex = null;
1062        ForkJoinWorkerThread t = null;
1063        try {
1064            t = factory.newThread(this);
1065        } catch (Throwable e) {
1066            ex = e;
1067        }
1068        if (t == null) {  // null or exceptional factory return
1069            long c;       // adjust counts
1070            do {} while (!UNSAFE.compareAndSwapLong
1071                         (this, ctlOffset, c = ctl,
1072                          (((c - AC_UNIT) & AC_MASK) |
1073                           ((c - TC_UNIT) & TC_MASK) |
1074                           (c & ~(AC_MASK|TC_MASK)))));
1075            // Propagate exception if originating from an external caller
1076            if (!tryTerminate(false) && ex != null &&
1077                !(Thread.currentThread() instanceof ForkJoinWorkerThread))
1078                UNSAFE.throwException(ex);
1079        }
1080        else
1081            t.start();
1082    }
1083
1084    /**
1085     * Callback from ForkJoinWorkerThread constructor to assign a
1086     * public name
1087     */
1088    final String nextWorkerName() {
1089        for (int n;;) {
1090            if (UNSAFE.compareAndSwapInt(this, nextWorkerNumberOffset,
1091                                         n = nextWorkerNumber, ++n))
1092                return workerNamePrefix + n;
1093        }
1094    }
1918  
1919      /**
1920 <     * Callback from ForkJoinWorkerThread constructor to
1921 <     * determine its poolIndex and record in workers array.
1922 <     *
1923 <     * @param w the worker
1924 <     * @return the worker's pool index
1925 <     */
1926 <    final int registerWorker(ForkJoinWorkerThread w) {
1927 <        /*
1928 <         * In the typical case, a new worker acquires the lock, uses
1929 <         * next available index and returns quickly.  Since we should
1930 <         * not block callers (ultimately from signalWork or
1931 <         * tryPreBlock) waiting for the lock needed to do this, we
1932 <         * instead help release other workers while waiting for the
1933 <         * lock.
1934 <         */
1935 <        for (int g;;) {
1936 <            ForkJoinWorkerThread[] ws;
1937 <            if (((g = scanGuard) & SG_UNIT) == 0 &&
1115 <                UNSAFE.compareAndSwapInt(this, scanGuardOffset,
1116 <                                         g, g | SG_UNIT)) {
1117 <                int k = nextWorkerIndex;
1118 <                try {
1119 <                    if ((ws = workers) != null) { // ignore on shutdown
1120 <                        int n = ws.length;
1121 <                        if (k < 0 || k >= n || ws[k] != null) {
1122 <                            for (k = 0; k < n && ws[k] != null; ++k)
1123 <                                ;
1124 <                            if (k == n)
1125 <                                ws = workers = Arrays.copyOf(ws, n << 1);
1126 <                        }
1127 <                        ws[k] = w;
1128 <                        nextWorkerIndex = k + 1;
1129 <                        int m = g & SMASK;
1130 <                        g = k >= m? ((m << 1) + 1) & SMASK : g + (SG_UNIT<<1);
1131 <                    }
1132 <                } finally {
1133 <                    scanGuard = g;
1920 >     * Runs tasks until {@code isQuiescent()}. We piggyback on
1921 >     * active count ctl maintenance, but rather than blocking
1922 >     * when tasks cannot be found, we rescan until all others cannot
1923 >     * find tasks either.
1924 >     */
1925 >    final void helpQuiescePool(WorkQueue w) {
1926 >        for (boolean active = true;;) {
1927 >            ForkJoinTask<?> localTask; // exhaust local queue
1928 >            while ((localTask = w.nextLocalTask()) != null)
1929 >                localTask.doExec();
1930 >            WorkQueue q = findNonEmptyStealQueue(w);
1931 >            if (q != null) {
1932 >                ForkJoinTask<?> t; int b;
1933 >                if (!active) {      // re-establish active count
1934 >                    long c;
1935 >                    active = true;
1936 >                    do {} while (!U.compareAndSwapLong
1937 >                                 (this, CTL, c = ctl, c + AC_UNIT));
1938                  }
1939 <                return k;
1939 >                if ((b = q.base) - q.top < 0 && (t = q.pollAt(b)) != null)
1940 >                    w.runSubtask(t);
1941              }
1942 <            else if ((ws = workers) != null) { // help release others
1943 <                for (ForkJoinWorkerThread u : ws) {
1944 <                    if (u != null && u.queueBase != u.queueTop) {
1945 <                        if (tryReleaseWaiter())
1946 <                            break;
1947 <                    }
1942 >            else {
1943 >                long c;
1944 >                if (active) {       // decrement active count without queuing
1945 >                    active = false;
1946 >                    do {} while (!U.compareAndSwapLong
1947 >                                 (this, CTL, c = ctl, c -= AC_UNIT));
1948 >                }
1949 >                else
1950 >                    c = ctl;        // re-increment on exit
1951 >                if ((int)(c >> AC_SHIFT) + parallelism == 0) {
1952 >                    do {} while (!U.compareAndSwapLong
1953 >                                 (this, CTL, c = ctl, c + AC_UNIT));
1954 >                    break;
1955                  }
1956              }
1957          }
1958      }
1959  
1960      /**
1961 <     * Final callback from terminating worker.  Removes record of
1150 <     * worker from array, and adjusts counts. If pool is shutting
1151 <     * down, tries to complete termination.
1961 >     * Gets and removes a local or stolen task for the given worker.
1962       *
1963 <     * @param w the worker
1963 >     * @return a task, if available
1964       */
1965 <    final void deregisterWorker(ForkJoinWorkerThread w, Throwable ex) {
1966 <        int idx = w.poolIndex;
1967 <        int sc = w.stealCount;
1968 <        int steps = 0;
1969 <        // Remove from array, adjust worker counts and collect steal count.
1970 <        // We can intermix failed removes or adjusts with steal updates
1971 <        do {
1972 <            long s, c;
1973 <            int g;
1164 <            if (steps == 0 && ((g = scanGuard) & SG_UNIT) == 0 &&
1165 <                UNSAFE.compareAndSwapInt(this, scanGuardOffset,
1166 <                                         g, g |= SG_UNIT)) {
1167 <                ForkJoinWorkerThread[] ws = workers;
1168 <                if (ws != null && idx >= 0 &&
1169 <                    idx < ws.length && ws[idx] == w)
1170 <                    ws[idx] = null;    // verify
1171 <                nextWorkerIndex = idx;
1172 <                scanGuard = g + SG_UNIT;
1173 <                steps = 1;
1174 <            }
1175 <            if (steps == 1 &&
1176 <                UNSAFE.compareAndSwapLong(this, ctlOffset, c = ctl,
1177 <                                          (((c - AC_UNIT) & AC_MASK) |
1178 <                                           ((c - TC_UNIT) & TC_MASK) |
1179 <                                           (c & ~(AC_MASK|TC_MASK)))))
1180 <                steps = 2;
1181 <            if (sc != 0 &&
1182 <                UNSAFE.compareAndSwapLong(this, stealCountOffset,
1183 <                                          s = stealCount, s + sc))
1184 <                sc = 0;
1185 <        } while (steps != 2 || sc != 0);
1186 <        if (!tryTerminate(false)) {
1187 <            if (ex != null)   // possibly replace if died abnormally
1188 <                signalWork();
1189 <            else
1190 <                tryReleaseWaiter();
1965 >    final ForkJoinTask<?> nextTaskFor(WorkQueue w) {
1966 >        for (ForkJoinTask<?> t;;) {
1967 >            WorkQueue q; int b;
1968 >            if ((t = w.nextLocalTask()) != null)
1969 >                return t;
1970 >            if ((q = findNonEmptyStealQueue(w)) == null)
1971 >                return null;
1972 >            if ((b = q.base) - q.top < 0 && (t = q.pollAt(b)) != null)
1973 >                return t;
1974          }
1975      }
1976  
1194    // Shutdown and termination
1195
1977      /**
1978 <     * Possibly initiates and/or completes termination.
1978 >     * Returns the approximate (non-atomic) number of idle threads per
1979 >     * active thread to offset steal queue size for method
1980 >     * ForkJoinTask.getSurplusQueuedTaskCount().
1981 >     */
1982 >    final int idlePerActive() {
1983 >        // Approximate at powers of two for small values, saturate past 4
1984 >        int p = parallelism;
1985 >        int a = p + (int)(ctl >> AC_SHIFT);
1986 >        return (a > (p >>>= 1) ? 0 :
1987 >                a > (p >>>= 1) ? 1 :
1988 >                a > (p >>>= 1) ? 2 :
1989 >                a > (p >>>= 1) ? 4 :
1990 >                8);
1991 >    }
1992 >
1993 >    //  Termination
1994 >
1995 >    /**
1996 >     * Possibly initiates and/or completes termination.  The caller
1997 >     * triggering termination runs three passes through workQueues:
1998 >     * (0) Setting termination status, followed by wakeups of queued
1999 >     * workers; (1) cancelling all tasks; (2) interrupting lagging
2000 >     * threads (likely in external tasks, but possibly also blocked in
2001 >     * joins).  Each pass repeats previous steps because of potential
2002 >     * lagging thread creation.
2003       *
2004       * @param now if true, unconditionally terminate, else only
2005 <     * if shutdown and empty queue and no active workers
2005 >     * if no work and no active workers
2006 >     * @param enable if true, enable shutdown when next possible
2007       * @return true if now terminating or terminated
2008       */
2009 <    private boolean tryTerminate(boolean now) {
2010 <        long c;
2011 <        while (((c = ctl) & STOP_BIT) == 0) {
2012 <            if (!now) {
2013 <                if ((int)(c >> AC_SHIFT) != -parallelism)
2009 >    private boolean tryTerminate(boolean now, boolean enable) {
2010 >        Mutex lock = this.lock;
2011 >        for (long c;;) {
2012 >            if (((c = ctl) & STOP_BIT) != 0) {      // already terminating
2013 >                if ((short)(c >>> TC_SHIFT) == -parallelism) {
2014 >                    lock.lock();                    // don't need try/finally
2015 >                    termination.signalAll();        // signal when 0 workers
2016 >                    lock.unlock();
2017 >                }
2018 >                return true;
2019 >            }
2020 >            if (runState >= 0) {                    // not yet enabled
2021 >                if (!enable)
2022                      return false;
2023 <                if (!shutdown || blockedCount != 0 || quiescerCount != 0 ||
2024 <                    queueTop - queueBase > 0) {
2025 <                    if (ctl == c) // staleness check
2026 <                        return false;
2027 <                    continue;
2028 <                }
2029 <            }
2030 <            if (UNSAFE.compareAndSwapLong(this, ctlOffset, c, c | STOP_BIT))
2031 <                startTerminating();
2032 <        }
2033 <        if ((short)(c >>> TC_SHIFT) == -parallelism) {
2034 <            submissionLock.lock();
2035 <            termination.signalAll();
2036 <            submissionLock.unlock();
2037 <        }
2038 <        return true;
2039 <    }
2040 <
2041 <    /**
2042 <     * Runs up to three passes through workers: (0) Setting
2043 <     * termination status for each worker, followed by wakeups up
2044 <     * queued workers (1) helping cancel tasks (2) interrupting
2045 <     * lagging threads (likely in external tasks, but possibly also
2046 <     * blocked in joins).  Each pass repeats previous steps because of
2047 <     * potential lagging thread creation.
2048 <     */
2049 <    private void startTerminating() {
2050 <        cancelSubmissions();
2051 <        for (int pass = 0; pass < 3; ++pass) {
2052 <            ForkJoinWorkerThread[] ws = workers;
1239 <            if (ws != null) {
1240 <                for (ForkJoinWorkerThread w : ws) {
1241 <                    if (w != null) {
1242 <                        w.terminate = true;
1243 <                        if (pass > 0) {
1244 <                            w.cancelTasks();
1245 <                            if (pass > 1 && !w.isInterrupted()) {
1246 <                                try {
1247 <                                    w.interrupt();
1248 <                                } catch (SecurityException ignore) {
2023 >                lock.lock();
2024 >                runState |= SHUTDOWN;
2025 >                lock.unlock();
2026 >            }
2027 >            if (!now) {                             // check if idle & no tasks
2028 >                if ((int)(c >> AC_SHIFT) != -parallelism ||
2029 >                    hasQueuedSubmissions())
2030 >                    return false;
2031 >                // Check for unqueued inactive workers. One pass suffices.
2032 >                WorkQueue[] ws = workQueues; WorkQueue w;
2033 >                if (ws != null) {
2034 >                    for (int i = 1; i < ws.length; i += 2) {
2035 >                        if ((w = ws[i]) != null && w.eventCount >= 0)
2036 >                            return false;
2037 >                    }
2038 >                }
2039 >            }
2040 >            if (U.compareAndSwapLong(this, CTL, c, c | STOP_BIT)) {
2041 >                for (int pass = 0; pass < 3; ++pass) {
2042 >                    WorkQueue[] ws = workQueues;
2043 >                    if (ws != null) {
2044 >                        WorkQueue w;
2045 >                        int n = ws.length;
2046 >                        for (int i = 0; i < n; ++i) {
2047 >                            if ((w = ws[i]) != null) {
2048 >                                w.runState = -1;
2049 >                                if (pass > 0) {
2050 >                                    w.cancelAll();
2051 >                                    if (pass > 1)
2052 >                                        w.interruptOwner();
2053                                  }
2054                              }
2055                          }
2056 +                        // Wake up workers parked on event queue
2057 +                        int i, e; long cc; Thread p;
2058 +                        while ((e = (int)(cc = ctl) & E_MASK) != 0 &&
2059 +                               (i = e & SMASK) < n &&
2060 +                               (w = ws[i]) != null) {
2061 +                            long nc = ((long)(w.nextWait & E_MASK) |
2062 +                                       ((cc + AC_UNIT) & AC_MASK) |
2063 +                                       (cc & (TC_MASK|STOP_BIT)));
2064 +                            if (w.eventCount == (e | INT_SIGN) &&
2065 +                                U.compareAndSwapLong(this, CTL, cc, nc)) {
2066 +                                w.eventCount = (e + E_SEQ) & E_MASK;
2067 +                                w.runState = -1;
2068 +                                if ((p = w.parker) != null)
2069 +                                    U.unpark(p);
2070 +                            }
2071 +                        }
2072                      }
2073                  }
1254                terminateWaiters();
1255            }
1256        }
1257    }
1258
1259    /**
1260     * Polls and cancels all submissions. Called only during termination.
1261     */
1262    private void cancelSubmissions() {
1263        while (queueBase != queueTop) {
1264            ForkJoinTask<?> task = pollSubmission();
1265            if (task != null) {
1266                try {
1267                    task.cancel(false);
1268                } catch (Throwable ignore) {
1269                }
2074              }
2075          }
2076      }
2077  
1274    /**
1275     * Tries to set the termination status of waiting workers, and
1276     * then wake them up (after which they will terminate).
1277     */
1278    private void terminateWaiters() {
1279        ForkJoinWorkerThread[] ws = workers;
1280        if (ws != null) {
1281            ForkJoinWorkerThread w; long c; int i, e;
1282            int n = ws.length;
1283            while ((i = ~(e = (int)(c = ctl)) & SMASK) < n &&
1284                   (w = ws[i]) != null && w.eventCount == (e & E_MASK)) {
1285                if (UNSAFE.compareAndSwapLong(this, ctlOffset, c,
1286                                              (long)(w.nextWait & E_MASK) |
1287                                              ((c + AC_UNIT) & AC_MASK) |
1288                                              (c & (TC_MASK|STOP_BIT)))) {
1289                    w.terminate = true;
1290                    w.eventCount = e + EC_UNIT;
1291                    if (w.parked)
1292                        UNSAFE.unpark(w);
1293                }
1294            }
1295        }
1296    }
1297
1298    // misc ForkJoinWorkerThread support
1299
1300    /**
1301     * Increment or decrement quiescerCount. Needed only to prevent
1302     * triggering shutdown if a worker is transiently inactive while
1303     * checking quiescence.
1304     *
1305     * @param delta 1 for increment, -1 for decrement
1306     */
1307    final void addQuiescerCount(int delta) {
1308        int c;
1309        do {} while(!UNSAFE.compareAndSwapInt(this, quiescerCountOffset,
1310                                              c = quiescerCount, c + delta));
1311    }
1312
1313    /**
1314     * Directly increment or decrement active count without
1315     * queuing. This method is used to transiently assert inactivation
1316     * while checking quiescence.
1317     *
1318     * @param delta 1 for increment, -1 for decrement
1319     */
1320    final void addActiveCount(int delta) {
1321        long d = delta < 0 ? -AC_UNIT : AC_UNIT;
1322        long c;
1323        do {} while (!UNSAFE.compareAndSwapLong(this, ctlOffset, c = ctl,
1324                                                ((c + d) & AC_MASK) |
1325                                                (c & ~AC_MASK)));
1326    }
1327
1328    /**
1329     * Returns the approximate (non-atomic) number of idle threads per
1330     * active thread.
1331     */
1332    final int idlePerActive() {
1333        // Approximate at powers of two for small values, saturate past 4
1334        int p = parallelism;
1335        int a = p + (int)(ctl >> AC_SHIFT);
1336        return (a > (p >>>= 1) ? 0 :
1337                a > (p >>>= 1) ? 1 :
1338                a > (p >>>= 1) ? 2 :
1339                a > (p >>>= 1) ? 4 :
1340                8);
1341    }
1342
2078      // Exported methods
2079  
2080      // Constructors
# Line 1409 | Line 2144 | public class ForkJoinPool extends Abstra
2144          checkPermission();
2145          if (factory == null)
2146              throw new NullPointerException();
2147 <        if (parallelism <= 0 || parallelism > MAX_ID)
2147 >        if (parallelism <= 0 || parallelism > MAX_CAP)
2148              throw new IllegalArgumentException();
2149          this.parallelism = parallelism;
2150          this.factory = factory;
2151          this.ueh = handler;
2152 <        this.locallyFifo = asyncMode;
2152 >        this.localMode = asyncMode ? FIFO_QUEUE : LIFO_QUEUE;
2153          long np = (long)(-parallelism); // offset ctl counts
2154          this.ctl = ((np << AC_SHIFT) & AC_MASK) | ((np << TC_SHIFT) & TC_MASK);
2155 <        this.submissionQueue = new ForkJoinTask<?>[INITIAL_QUEUE_CAPACITY];
2156 <        // initialize workers array with room for 2*parallelism if possible
2157 <        int n = parallelism << 1;
2158 <        if (n >= MAX_ID)
2159 <            n = MAX_ID;
2160 <        else { // See Hackers Delight, sec 3.2, where n < (1 << 16)
2161 <            n |= n >>> 1; n |= n >>> 2; n |= n >>> 4; n |= n >>> 8;
2162 <        }
2163 <        workers = new ForkJoinWorkerThread[n + 1];
2164 <        this.submissionLock = new ReentrantLock();
1430 <        this.termination = submissionLock.newCondition();
2155 >        // Use nearest power 2 for workQueues size. See Hackers Delight sec 3.2.
2156 >        int n = parallelism - 1;
2157 >        n |= n >>> 1; n |= n >>> 2; n |= n >>> 4; n |= n >>> 8; n |= n >>> 16;
2158 >        int size = (n + 1) << 1;        // #slots = 2*#workers
2159 >        this.submitMask = size - 1;     // room for max # of submit queues
2160 >        this.workQueues = new WorkQueue[size];
2161 >        this.termination = (this.lock = new Mutex()).newCondition();
2162 >        this.stealCount = new AtomicLong();
2163 >        this.nextWorkerNumber = new AtomicInteger();
2164 >        int pn = poolNumberGenerator.incrementAndGet();
2165          StringBuilder sb = new StringBuilder("ForkJoinPool-");
2166 <        sb.append(poolNumberGenerator.incrementAndGet());
2166 >        sb.append(Integer.toString(pn));
2167          sb.append("-worker-");
2168          this.workerNamePrefix = sb.toString();
2169 +        lock.lock();
2170 +        this.runState = 1;              // set init flag
2171 +        lock.unlock();
2172      }
2173  
2174      // Execution methods
# Line 1453 | Line 2190 | public class ForkJoinPool extends Abstra
2190       *         scheduled for execution
2191       */
2192      public <T> T invoke(ForkJoinTask<T> task) {
1456        Thread t = Thread.currentThread();
2193          if (task == null)
2194              throw new NullPointerException();
2195 <        if (shutdown)
2196 <            throw new RejectedExecutionException();
1461 <        if ((t instanceof ForkJoinWorkerThread) &&
1462 <            ((ForkJoinWorkerThread)t).pool == this)
1463 <            return task.invoke();  // bypass submit if in same pool
1464 <        else {
1465 <            addSubmission(task);
1466 <            return task.join();
1467 <        }
1468 <    }
1469 <
1470 <    /**
1471 <     * Unless terminating, forks task if within an ongoing FJ
1472 <     * computation in the current pool, else submits as external task.
1473 <     */
1474 <    private <T> void forkOrSubmit(ForkJoinTask<T> task) {
1475 <        ForkJoinWorkerThread w;
1476 <        Thread t = Thread.currentThread();
1477 <        if (shutdown)
1478 <            throw new RejectedExecutionException();
1479 <        if ((t instanceof ForkJoinWorkerThread) &&
1480 <            (w = (ForkJoinWorkerThread)t).pool == this)
1481 <            w.pushTask(task);
1482 <        else
1483 <            addSubmission(task);
2195 >        doSubmit(task);
2196 >        return task.join();
2197      }
2198  
2199      /**
# Line 1494 | Line 2207 | public class ForkJoinPool extends Abstra
2207      public void execute(ForkJoinTask<?> task) {
2208          if (task == null)
2209              throw new NullPointerException();
2210 <        forkOrSubmit(task);
2210 >        doSubmit(task);
2211      }
2212  
2213      // AbstractExecutorService methods
# Line 1511 | Line 2224 | public class ForkJoinPool extends Abstra
2224          if (task instanceof ForkJoinTask<?>) // avoid re-wrap
2225              job = (ForkJoinTask<?>) task;
2226          else
2227 <            job = ForkJoinTask.adapt(task, null);
2228 <        forkOrSubmit(job);
2227 >            job = new ForkJoinTask.AdaptedRunnableAction(task);
2228 >        doSubmit(job);
2229      }
2230  
2231      /**
# Line 1527 | Line 2240 | public class ForkJoinPool extends Abstra
2240      public <T> ForkJoinTask<T> submit(ForkJoinTask<T> task) {
2241          if (task == null)
2242              throw new NullPointerException();
2243 <        forkOrSubmit(task);
2243 >        doSubmit(task);
2244          return task;
2245      }
2246  
# Line 1537 | Line 2250 | public class ForkJoinPool extends Abstra
2250       *         scheduled for execution
2251       */
2252      public <T> ForkJoinTask<T> submit(Callable<T> task) {
2253 <        if (task == null)
2254 <            throw new NullPointerException();
1542 <        ForkJoinTask<T> job = ForkJoinTask.adapt(task);
1543 <        forkOrSubmit(job);
2253 >        ForkJoinTask<T> job = new ForkJoinTask.AdaptedCallable<T>(task);
2254 >        doSubmit(job);
2255          return job;
2256      }
2257  
# Line 1550 | Line 2261 | public class ForkJoinPool extends Abstra
2261       *         scheduled for execution
2262       */
2263      public <T> ForkJoinTask<T> submit(Runnable task, T result) {
2264 <        if (task == null)
2265 <            throw new NullPointerException();
1555 <        ForkJoinTask<T> job = ForkJoinTask.adapt(task, result);
1556 <        forkOrSubmit(job);
2264 >        ForkJoinTask<T> job = new ForkJoinTask.AdaptedRunnable<T>(task, result);
2265 >        doSubmit(job);
2266          return job;
2267      }
2268  
# Line 1569 | Line 2278 | public class ForkJoinPool extends Abstra
2278          if (task instanceof ForkJoinTask<?>) // avoid re-wrap
2279              job = (ForkJoinTask<?>) task;
2280          else
2281 <            job = ForkJoinTask.adapt(task, null);
2282 <        forkOrSubmit(job);
2281 >            job = new ForkJoinTask.AdaptedRunnableAction(task);
2282 >        doSubmit(job);
2283          return job;
2284      }
2285  
# Line 1579 | Line 2288 | public class ForkJoinPool extends Abstra
2288       * @throws RejectedExecutionException {@inheritDoc}
2289       */
2290      public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) {
2291 <        ArrayList<ForkJoinTask<T>> forkJoinTasks =
2292 <            new ArrayList<ForkJoinTask<T>>(tasks.size());
2293 <        for (Callable<T> task : tasks)
2294 <            forkJoinTasks.add(ForkJoinTask.adapt(task));
2295 <        invoke(new InvokeAll<T>(forkJoinTasks));
2296 <
2291 >        // In previous versions of this class, this method constructed
2292 >        // a task to run ForkJoinTask.invokeAll, but now external
2293 >        // invocation of multiple tasks is at least as efficient.
2294 >        List<ForkJoinTask<T>> fs = new ArrayList<ForkJoinTask<T>>(tasks.size());
2295 >        // Workaround needed because method wasn't declared with
2296 >        // wildcards in return type but should have been.
2297          @SuppressWarnings({"unchecked", "rawtypes"})
2298 <            List<Future<T>> futures = (List<Future<T>>) (List) forkJoinTasks;
1590 <        return futures;
1591 <    }
2298 >            List<Future<T>> futures = (List<Future<T>>) (List) fs;
2299  
2300 <    static final class InvokeAll<T> extends RecursiveAction {
2301 <        final ArrayList<ForkJoinTask<T>> tasks;
2302 <        InvokeAll(ArrayList<ForkJoinTask<T>> tasks) { this.tasks = tasks; }
2303 <        public void compute() {
2304 <            try { invokeAll(tasks); }
2305 <            catch (Exception ignore) {}
2300 >        boolean done = false;
2301 >        try {
2302 >            for (Callable<T> t : tasks) {
2303 >                ForkJoinTask<T> f = new ForkJoinTask.AdaptedCallable<T>(t);
2304 >                doSubmit(f);
2305 >                fs.add(f);
2306 >            }
2307 >            for (ForkJoinTask<T> f : fs)
2308 >                f.quietlyJoin();
2309 >            done = true;
2310 >            return futures;
2311 >        } finally {
2312 >            if (!done)
2313 >                for (ForkJoinTask<T> f : fs)
2314 >                    f.cancel(false);
2315          }
1600        private static final long serialVersionUID = -7914297376763021607L;
2316      }
2317  
2318      /**
# Line 1647 | Line 2362 | public class ForkJoinPool extends Abstra
2362       * @return {@code true} if this pool uses async mode
2363       */
2364      public boolean getAsyncMode() {
2365 <        return locallyFifo;
2365 >        return localMode != 0;
2366      }
2367  
2368      /**
# Line 1659 | Line 2374 | public class ForkJoinPool extends Abstra
2374       * @return the number of worker threads
2375       */
2376      public int getRunningThreadCount() {
2377 <        int r = parallelism + (int)(ctl >> AC_SHIFT);
2378 <        return r <= 0? 0 : r; // suppress momentarily negative values
2377 >        int rc = 0;
2378 >        WorkQueue[] ws; WorkQueue w;
2379 >        if ((ws = workQueues) != null) {
2380 >            for (int i = 1; i < ws.length; i += 2) {
2381 >                if ((w = ws[i]) != null && w.isApparentlyUnblocked())
2382 >                    ++rc;
2383 >            }
2384 >        }
2385 >        return rc;
2386      }
2387  
2388      /**
# Line 1671 | Line 2393 | public class ForkJoinPool extends Abstra
2393       * @return the number of active threads
2394       */
2395      public int getActiveThreadCount() {
2396 <        int r = parallelism + (int)(ctl >> AC_SHIFT) + blockedCount;
2397 <        return r <= 0? 0 : r; // suppress momentarily negative values
2396 >        int r = parallelism + (int)(ctl >> AC_SHIFT);
2397 >        return (r <= 0) ? 0 : r; // suppress momentarily negative values
2398      }
2399  
2400      /**
# Line 1687 | Line 2409 | public class ForkJoinPool extends Abstra
2409       * @return {@code true} if all threads are currently idle
2410       */
2411      public boolean isQuiescent() {
2412 <        return parallelism + (int)(ctl >> AC_SHIFT) + blockedCount == 0;
2412 >        return (int)(ctl >> AC_SHIFT) + parallelism == 0;
2413      }
2414  
2415      /**
# Line 1702 | Line 2424 | public class ForkJoinPool extends Abstra
2424       * @return the number of steals
2425       */
2426      public long getStealCount() {
2427 <        return stealCount;
2427 >        long count = stealCount.get();
2428 >        WorkQueue[] ws; WorkQueue w;
2429 >        if ((ws = workQueues) != null) {
2430 >            for (int i = 1; i < ws.length; i += 2) {
2431 >                if ((w = ws[i]) != null)
2432 >                    count += w.totalSteals;
2433 >            }
2434 >        }
2435 >        return count;
2436      }
2437  
2438      /**
# Line 1717 | Line 2447 | public class ForkJoinPool extends Abstra
2447       */
2448      public long getQueuedTaskCount() {
2449          long count = 0;
2450 <        ForkJoinWorkerThread[] ws;
2451 <        if ((short)(ctl >>> TC_SHIFT) > -parallelism &&
2452 <            (ws = workers) != null) {
2453 <            for (ForkJoinWorkerThread w : ws)
2454 <                if (w != null)
2455 <                    count -= w.queueBase - w.queueTop; // must read base first
2450 >        WorkQueue[] ws; WorkQueue w;
2451 >        if ((ws = workQueues) != null) {
2452 >            for (int i = 1; i < ws.length; i += 2) {
2453 >                if ((w = ws[i]) != null)
2454 >                    count += w.queueSize();
2455 >            }
2456          }
2457          return count;
2458      }
2459  
2460      /**
2461       * Returns an estimate of the number of tasks submitted to this
2462 <     * pool that have not yet begun executing.  This meThod may take
2462 >     * pool that have not yet begun executing.  This method may take
2463       * time proportional to the number of submissions.
2464       *
2465       * @return the number of queued submissions
2466       */
2467      public int getQueuedSubmissionCount() {
2468 <        return -queueBase + queueTop;
2468 >        int count = 0;
2469 >        WorkQueue[] ws; WorkQueue w;
2470 >        if ((ws = workQueues) != null) {
2471 >            for (int i = 0; i < ws.length; i += 2) {
2472 >                if ((w = ws[i]) != null)
2473 >                    count += w.queueSize();
2474 >            }
2475 >        }
2476 >        return count;
2477      }
2478  
2479      /**
# Line 1745 | Line 2483 | public class ForkJoinPool extends Abstra
2483       * @return {@code true} if there are any queued submissions
2484       */
2485      public boolean hasQueuedSubmissions() {
2486 <        return queueBase != queueTop;
2486 >        WorkQueue[] ws; WorkQueue w;
2487 >        if ((ws = workQueues) != null) {
2488 >            for (int i = 0; i < ws.length; i += 2) {
2489 >                if ((w = ws[i]) != null && !w.isEmpty())
2490 >                    return true;
2491 >            }
2492 >        }
2493 >        return false;
2494      }
2495  
2496      /**
# Line 1756 | Line 2501 | public class ForkJoinPool extends Abstra
2501       * @return the next submission, or {@code null} if none
2502       */
2503      protected ForkJoinTask<?> pollSubmission() {
2504 <        ForkJoinTask<?> t; ForkJoinTask<?>[] q; int b, i;
2505 <        while ((b = queueBase) != queueTop &&
2506 <               (q = submissionQueue) != null &&
2507 <               (i = (q.length - 1) & b) >= 0) {
2508 <            long u = (i << ASHIFT) + ABASE;
1764 <            if ((t = q[i]) != null &&
1765 <                queueBase == b &&
1766 <                UNSAFE.compareAndSwapObject(q, u, t, null)) {
1767 <                queueBase = b + 1;
1768 <                return t;
2504 >        WorkQueue[] ws; WorkQueue w; ForkJoinTask<?> t;
2505 >        if ((ws = workQueues) != null) {
2506 >            for (int i = 0; i < ws.length; i += 2) {
2507 >                if ((w = ws[i]) != null && (t = w.poll()) != null)
2508 >                    return t;
2509              }
2510          }
2511          return null;
# Line 1790 | Line 2530 | public class ForkJoinPool extends Abstra
2530       */
2531      protected int drainTasksTo(Collection<? super ForkJoinTask<?>> c) {
2532          int count = 0;
2533 <        while (queueBase != queueTop) {
2534 <            ForkJoinTask<?> t = pollSubmission();
2535 <            if (t != null) {
2536 <                c.add(t);
2537 <                ++count;
2533 >        WorkQueue[] ws; WorkQueue w; ForkJoinTask<?> t;
2534 >        if ((ws = workQueues) != null) {
2535 >            for (int i = 0; i < ws.length; ++i) {
2536 >                if ((w = ws[i]) != null) {
2537 >                    while ((t = w.poll()) != null) {
2538 >                        c.add(t);
2539 >                        ++count;
2540 >                    }
2541 >                }
2542              }
2543          }
1800        ForkJoinWorkerThread[] ws;
1801        if ((short)(ctl >>> TC_SHIFT) > -parallelism &&
1802            (ws = workers) != null) {
1803            for (ForkJoinWorkerThread w : ws)
1804                if (w != null)
1805                    count += w.drainTasksTo(c);
1806        }
2544          return count;
2545      }
2546  
# Line 1815 | Line 2552 | public class ForkJoinPool extends Abstra
2552       * @return a string identifying this pool, as well as its state
2553       */
2554      public String toString() {
2555 <        long st = getStealCount();
2556 <        long qt = getQueuedTaskCount();
2557 <        long qs = getQueuedSubmissionCount();
1821 <        int pc = parallelism;
2555 >        // Use a single pass through workQueues to collect counts
2556 >        long qt = 0L, qs = 0L; int rc = 0;
2557 >        long st = stealCount.get();
2558          long c = ctl;
2559 +        WorkQueue[] ws; WorkQueue w;
2560 +        if ((ws = workQueues) != null) {
2561 +            for (int i = 0; i < ws.length; ++i) {
2562 +                if ((w = ws[i]) != null) {
2563 +                    int size = w.queueSize();
2564 +                    if ((i & 1) == 0)
2565 +                        qs += size;
2566 +                    else {
2567 +                        qt += size;
2568 +                        st += w.totalSteals;
2569 +                        if (w.isApparentlyUnblocked())
2570 +                            ++rc;
2571 +                    }
2572 +                }
2573 +            }
2574 +        }
2575 +        int pc = parallelism;
2576          int tc = pc + (short)(c >>> TC_SHIFT);
2577 <        int rc = pc + (int)(c >> AC_SHIFT);
2578 <        if (rc < 0) // ignore transient negative
2579 <            rc = 0;
1827 <        int ac = rc + blockedCount;
2577 >        int ac = pc + (int)(c >> AC_SHIFT);
2578 >        if (ac < 0) // ignore transient negative
2579 >            ac = 0;
2580          String level;
2581          if ((c & STOP_BIT) != 0)
2582 <            level = (tc == 0)? "Terminated" : "Terminating";
2582 >            level = (tc == 0) ? "Terminated" : "Terminating";
2583          else
2584 <            level = shutdown? "Shutting down" : "Running";
2584 >            level = runState < 0 ? "Shutting down" : "Running";
2585          return super.toString() +
2586              "[" + level +
2587              ", parallelism = " + pc +
# Line 1856 | Line 2608 | public class ForkJoinPool extends Abstra
2608       */
2609      public void shutdown() {
2610          checkPermission();
2611 <        shutdown = true;
1860 <        tryTerminate(false);
2611 >        tryTerminate(false, true);
2612      }
2613  
2614      /**
# Line 1878 | Line 2629 | public class ForkJoinPool extends Abstra
2629       */
2630      public List<Runnable> shutdownNow() {
2631          checkPermission();
2632 <        shutdown = true;
1882 <        tryTerminate(true);
2632 >        tryTerminate(true, true);
2633          return Collections.emptyList();
2634      }
2635  
# Line 1914 | Line 2664 | public class ForkJoinPool extends Abstra
2664      }
2665  
2666      /**
1917     * Returns true if terminating or terminated. Used by ForkJoinWorkerThread.
1918     */
1919    final boolean isAtLeastTerminating() {
1920        return (ctl & STOP_BIT) != 0L;
1921    }
1922
1923    /**
2667       * Returns {@code true} if this pool has been shut down.
2668       *
2669       * @return {@code true} if this pool has been shut down
2670       */
2671      public boolean isShutdown() {
2672 <        return shutdown;
2672 >        return runState < 0;
2673      }
2674  
2675      /**
# Line 1943 | Line 2686 | public class ForkJoinPool extends Abstra
2686      public boolean awaitTermination(long timeout, TimeUnit unit)
2687          throws InterruptedException {
2688          long nanos = unit.toNanos(timeout);
2689 <        final ReentrantLock lock = this.submissionLock;
2689 >        final Mutex lock = this.lock;
2690          lock.lock();
2691          try {
2692              for (;;) {
# Line 1966 | Line 2709 | public class ForkJoinPool extends Abstra
2709       * {@code isReleasable} must return {@code true} if blocking is
2710       * not necessary. Method {@code block} blocks the current thread
2711       * if necessary (perhaps internally invoking {@code isReleasable}
2712 <     * before actually blocking). The unusual methods in this API
2713 <     * accommodate synchronizers that may, but don't usually, block
2714 <     * for long periods. Similarly, they allow more efficient internal
2715 <     * handling of cases in which additional workers may be, but
2716 <     * usually are not, needed to ensure sufficient parallelism.
2717 <     * Toward this end, implementations of method {@code isReleasable}
2718 <     * must be amenable to repeated invocation.
2712 >     * before actually blocking). These actions are performed by any
2713 >     * thread invoking {@link ForkJoinPool#managedBlock}.  The
2714 >     * unusual methods in this API accommodate synchronizers that may,
2715 >     * but don't usually, block for long periods. Similarly, they
2716 >     * allow more efficient internal handling of cases in which
2717 >     * additional workers may be, but usually are not, needed to
2718 >     * ensure sufficient parallelism.  Toward this end,
2719 >     * implementations of method {@code isReleasable} must be amenable
2720 >     * to repeated invocation.
2721       *
2722       * <p>For example, here is a ManagedBlocker based on a
2723       * ReentrantLock:
# Line 2052 | Line 2797 | public class ForkJoinPool extends Abstra
2797      public static void managedBlock(ManagedBlocker blocker)
2798          throws InterruptedException {
2799          Thread t = Thread.currentThread();
2800 <        if (t instanceof ForkJoinWorkerThread) {
2801 <            ForkJoinWorkerThread w = (ForkJoinWorkerThread) t;
2802 <            w.pool.awaitBlocker(blocker);
2803 <        }
2804 <        else {
2805 <            do {} while (!blocker.isReleasable() && !blocker.block());
2800 >        ForkJoinPool p = ((t instanceof ForkJoinWorkerThread) ?
2801 >                          ((ForkJoinWorkerThread)t).pool : null);
2802 >        while (!blocker.isReleasable()) {
2803 >            if (p == null || p.tryCompensate(null, blocker)) {
2804 >                try {
2805 >                    do {} while (!blocker.isReleasable() && !blocker.block());
2806 >                } finally {
2807 >                    if (p != null)
2808 >                        p.incrementActiveCount();
2809 >                }
2810 >                break;
2811 >            }
2812          }
2813      }
2814  
# Line 2066 | Line 2817 | public class ForkJoinPool extends Abstra
2817      // implement RunnableFuture.
2818  
2819      protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
2820 <        return (RunnableFuture<T>) ForkJoinTask.adapt(runnable, value);
2820 >        return new ForkJoinTask.AdaptedRunnable<T>(runnable, value);
2821      }
2822  
2823      protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
2824 <        return (RunnableFuture<T>) ForkJoinTask.adapt(callable);
2824 >        return new ForkJoinTask.AdaptedCallable<T>(callable);
2825      }
2826  
2827      // Unsafe mechanics
2828 <    private static final sun.misc.Unsafe UNSAFE;
2829 <    private static final long ctlOffset;
2830 <    private static final long stealCountOffset;
2831 <    private static final long blockedCountOffset;
2081 <    private static final long quiescerCountOffset;
2082 <    private static final long scanGuardOffset;
2083 <    private static final long nextWorkerNumberOffset;
2084 <    private static final long ABASE;
2828 >    private static final sun.misc.Unsafe U;
2829 >    private static final long CTL;
2830 >    private static final long PARKBLOCKER;
2831 >    private static final int ABASE;
2832      private static final int ASHIFT;
2833  
2834      static {
2835          poolNumberGenerator = new AtomicInteger();
2836 <        workerSeedGenerator = new Random();
2836 >        nextSubmitterSeed = new AtomicInteger(0x55555555);
2837          modifyThreadPermission = new RuntimePermission("modifyThread");
2838          defaultForkJoinWorkerThreadFactory =
2839              new DefaultForkJoinWorkerThreadFactory();
2840 +        submitters = new ThreadSubmitter();
2841          int s;
2842          try {
2843 <            UNSAFE = getUnsafe();
2844 <            Class k = ForkJoinPool.class;
2845 <            ctlOffset = UNSAFE.objectFieldOffset
2843 >            U = getUnsafe();
2844 >            Class<?> k = ForkJoinPool.class;
2845 >            Class<?> ak = ForkJoinTask[].class;
2846 >            CTL = U.objectFieldOffset
2847                  (k.getDeclaredField("ctl"));
2848 <            stealCountOffset = UNSAFE.objectFieldOffset
2849 <                (k.getDeclaredField("stealCount"));
2850 <            blockedCountOffset = UNSAFE.objectFieldOffset
2851 <                (k.getDeclaredField("blockedCount"));
2852 <            quiescerCountOffset = UNSAFE.objectFieldOffset
2104 <                (k.getDeclaredField("quiescerCount"));
2105 <            scanGuardOffset = UNSAFE.objectFieldOffset
2106 <                (k.getDeclaredField("scanGuard"));
2107 <            nextWorkerNumberOffset = UNSAFE.objectFieldOffset
2108 <                (k.getDeclaredField("nextWorkerNumber"));
2109 <            Class a = ForkJoinTask[].class;
2110 <            ABASE = UNSAFE.arrayBaseOffset(a);
2111 <            s = UNSAFE.arrayIndexScale(a);
2848 >            Class<?> tk = Thread.class;
2849 >            PARKBLOCKER = U.objectFieldOffset
2850 >                (tk.getDeclaredField("parkBlocker"));
2851 >            ABASE = U.arrayBaseOffset(ak);
2852 >            s = U.arrayIndexScale(ak);
2853          } catch (Exception e) {
2854              throw new Error(e);
2855          }
# Line 2144 | Line 2885 | public class ForkJoinPool extends Abstra
2885              }
2886          }
2887      }
2888 +
2889   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines