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.105 by jsr166, Fri Jun 10 18:10:53 2011 UTC vs.
Revision 1.115 by jsr166, Thu Jan 26 19:10:27 2012 UTC

# Line 20 | Line 20 | import java.util.concurrent.RejectedExec
20   import java.util.concurrent.RunnableFuture;
21   import java.util.concurrent.TimeUnit;
22   import java.util.concurrent.atomic.AtomicInteger;
23 < import java.util.concurrent.locks.LockSupport;
23 > import java.util.concurrent.atomic.AtomicLong;
24   import java.util.concurrent.locks.ReentrantLock;
25   import java.util.concurrent.locks.Condition;
26  
# Line 33 | Line 33 | import java.util.concurrent.locks.Condit
33   * <p>A {@code ForkJoinPool} differs from other kinds of {@link
34   * ExecutorService} mainly by virtue of employing
35   * <em>work-stealing</em>: all threads in the pool attempt to find and
36 < * execute subtasks created by other active tasks (eventually blocking
37 < * waiting for work if none exist). This enables efficient processing
38 < * when most tasks spawn other subtasks (as do most {@code
39 < * ForkJoinTask}s). When setting <em>asyncMode</em> to true in
40 < * constructors, {@code ForkJoinPool}s may also be appropriate for use
41 < * with event-style tasks that are never joined.
36 > * execute tasks submitted to the pool and/or created by other active
37 > * tasks (eventually blocking waiting for work if none exist). This
38 > * enables efficient processing when most tasks spawn other subtasks
39 > * (as do most {@code ForkJoinTask}s), as well as when many small
40 > * tasks are submitted to the pool from external clients.  Especially
41 > * when setting <em>asyncMode</em> to true in constructors, {@code
42 > * ForkJoinPool}s may also be appropriate for use with event-style
43 > * tasks that are never joined.
44   *
45   * <p>A {@code ForkJoinPool} is constructed with a given target
46   * parallelism level; by default, equal to the number of available
# Line 59 | Line 61 | import java.util.concurrent.locks.Condit
61   *
62   * <p> As is the case with other ExecutorServices, there are three
63   * main task execution methods summarized in the following
64 < * table. These are designed to be used by clients not already engaged
65 < * in fork/join computations in the current pool.  The main forms of
66 < * these methods accept instances of {@code ForkJoinTask}, but
67 < * overloaded forms also allow mixed execution of plain {@code
68 < * Runnable}- or {@code Callable}- based activities as well.  However,
69 < * tasks that are already executing in a pool should normally
70 < * <em>NOT</em> use these pool execution methods, but instead use the
71 < * within-computation forms listed in the table.
64 > * table. These are designed to be used primarily by clients not
65 > * already engaged in fork/join computations in the current pool.  The
66 > * main forms of these methods accept instances of {@code
67 > * ForkJoinTask}, but overloaded forms also allow mixed execution of
68 > * plain {@code Runnable}- or {@code Callable}- based activities as
69 > * well.  However, tasks that are already executing in a pool should
70 > * normally instead use the within-computation forms listed in the
71 > * table unless using async event-style tasks that are not usually
72 > * joined, in which case there is little difference among choice of
73 > * methods.
74   *
75   * <table BORDER CELLPADDING=3 CELLSPACING=1>
76   *  <tr>
# Line 125 | Line 129 | public class ForkJoinPool extends Abstra
129      /*
130       * Implementation Overview
131       *
132 <     * This class provides the central bookkeeping and control for a
133 <     * set of worker threads: Submissions from non-FJ threads enter
134 <     * into a submission queue. Workers take these tasks and typically
135 <     * split them into subtasks that may be stolen by other workers.
136 <     * Preference rules give first priority to processing tasks from
137 <     * their own queues (LIFO or FIFO, depending on mode), then to
138 <     * randomized FIFO steals of tasks in other worker queues, and
139 <     * lastly to new submissions.
132 >     * This class and its nested classes provide the main
133 >     * functionality and control for a set of worker threads:
134 >     * Submissions from non-FJ threads enter into submission
135 >     * queues. Workers take these tasks and typically split them into
136 >     * subtasks that may be stolen by other workers.  Preference rules
137 >     * give first priority to processing tasks from their own queues
138 >     * (LIFO or FIFO, depending on mode), then to randomized FIFO
139 >     * steals of tasks in other queues.
140 >     *
141 >     * WorkQueues.
142 >     * ==========
143 >     *
144 >     * Most operations occur within work-stealing queues (in nested
145 >     * class WorkQueue).  These are special forms of Deques that
146 >     * support only three of the four possible end-operations -- push,
147 >     * pop, and poll (aka steal), under the further constraints that
148 >     * push and pop are called only from the owning thread (or, as
149 >     * extended here, under a lock), while poll may be called from
150 >     * other threads.  (If you are unfamiliar with them, you probably
151 >     * want to read Herlihy and Shavit's book "The Art of
152 >     * Multiprocessor programming", chapter 16 describing these in
153 >     * more detail before proceeding.)  The main work-stealing queue
154 >     * design is roughly similar to those in the papers "Dynamic
155 >     * Circular Work-Stealing Deque" by Chase and Lev, SPAA 2005
156 >     * (http://research.sun.com/scalable/pubs/index.html) and
157 >     * "Idempotent work stealing" by Michael, Saraswat, and Vechev,
158 >     * PPoPP 2009 (http://portal.acm.org/citation.cfm?id=1504186).
159 >     * The main differences ultimately stem from gc requirements that
160 >     * we null out taken slots as soon as we can, to maintain as small
161 >     * a footprint as possible even in programs generating huge
162 >     * numbers of tasks. To accomplish this, we shift the CAS
163 >     * arbitrating pop vs poll (steal) from being on the indices
164 >     * ("base" and "top") to the slots themselves.  So, both a
165 >     * successful pop and poll mainly entail a CAS of a slot from
166 >     * non-null to null.  Because we rely on CASes of references, we
167 >     * do not need tag bits on base or top.  They are simple ints as
168 >     * used in any circular array-based queue (see for example
169 >     * ArrayDeque).  Updates to the indices must still be ordered in a
170 >     * way that guarantees that top == base means the queue is empty,
171 >     * but otherwise may err on the side of possibly making the queue
172 >     * appear nonempty when a push, pop, or poll have not fully
173 >     * committed. Note that this means that the poll operation,
174 >     * considered individually, is not wait-free. One thief cannot
175 >     * successfully continue until another in-progress one (or, if
176 >     * previously empty, a push) completes.  However, in the
177 >     * aggregate, we ensure at least probabilistic non-blockingness.
178 >     * If an attempted steal fails, a thief always chooses a different
179 >     * random victim target to try next. So, in order for one thief to
180 >     * progress, it suffices for any in-progress poll or new push on
181 >     * any empty queue to complete.
182 >     *
183 >     * This approach also enables support of a user mode in which local
184 >     * task processing is in FIFO, not LIFO order, simply by using
185 >     * poll rather than pop.  This can be useful in message-passing
186 >     * frameworks in which tasks are never joined.  However neither
187 >     * mode considers affinities, loads, cache localities, etc, so
188 >     * rarely provide the best possible performance on a given
189 >     * machine, but portably provide good throughput by averaging over
190 >     * these factors.  (Further, even if we did try to use such
191 >     * information, we do not usually have a basis for exploiting
192 >     * it. For example, some sets of tasks profit from cache
193 >     * affinities, but others are harmed by cache pollution effects.)
194 >     *
195 >     * WorkQueues are also used in a similar way for tasks submitted
196 >     * to the pool. We cannot mix these tasks in the same queues used
197 >     * for work-stealing (this would contaminate lifo/fifo
198 >     * processing). Instead, we loosely associate (via hashing)
199 >     * submission queues with submitting threads, and randomly scan
200 >     * these queues as well when looking for work. In essence,
201 >     * submitters act like workers except that they never take tasks,
202 >     * and they are multiplexed on to a finite number of shared work
203 >     * queues. However, classes are set up so that future extensions
204 >     * could allow submitters to optionally help perform tasks as
205 >     * well. Pool submissions from internal workers are also allowed,
206 >     * but use randomized rather than thread-hashed queue indices to
207 >     * avoid imbalance.  Insertion of tasks in shared mode requires a
208 >     * lock (mainly to protect in the case of resizing) but we use
209 >     * only a simple spinlock (using bits in field runState), because
210 >     * submitters encountering a busy queue try or create others so
211 >     * never block.
212 >     *
213 >     * Management.
214 >     * ==========
215       *
216       * The main throughput advantages of work-stealing stem from
217       * decentralized control -- workers mostly take tasks from
218       * themselves or each other. We cannot negate this in the
219       * implementation of other management responsibilities. The main
220       * tactic for avoiding bottlenecks is packing nearly all
221 <     * essentially atomic control state into a single 64bit volatile
222 <     * variable ("ctl"). This variable is read on the order of 10-100
223 <     * times as often as it is modified (always via CAS). (There is
224 <     * some additional control state, for example variable "shutdown"
225 <     * for which we can cope with uncoordinated updates.)  This
226 <     * streamlines synchronization and control at the expense of messy
227 <     * constructions needed to repack status bits upon updates.
228 <     * Updates tend not to contend with each other except during
229 <     * bursts while submitted tasks begin or end.  In some cases when
230 <     * they do contend, threads can instead do something else
231 <     * (usually, scan for tasks) until contention subsides.
232 <     *
233 <     * To enable packing, we restrict maximum parallelism to (1<<15)-1
234 <     * (which is far in excess of normal operating range) to allow
235 <     * ids, counts, and their negations (used for thresholding) to fit
236 <     * into 16bit fields.
237 <     *
238 <     * Recording Workers.  Workers are recorded in the "workers" array
239 <     * that is created upon pool construction and expanded if (rarely)
240 <     * necessary.  This is an array as opposed to some other data
241 <     * structure to support index-based random steals by workers.
242 <     * Updates to the array recording new workers and unrecording
243 <     * terminated ones are protected from each other by a seqLock
244 <     * (scanGuard) but the array is otherwise concurrently readable,
166 <     * and accessed directly by workers. To simplify index-based
221 >     * essentially atomic control state into two volatile variables
222 >     * that are by far most often read (not written) as status and
223 >     * consistency checks
224 >     *
225 >     * Field "ctl" contains 64 bits holding all the information needed
226 >     * to atomically decide to add, inactivate, enqueue (on an event
227 >     * queue), dequeue, and/or re-activate workers.  To enable this
228 >     * packing, we restrict maximum parallelism to (1<<15)-1 (which is
229 >     * far in excess of normal operating range) to allow ids, counts,
230 >     * and their negations (used for thresholding) to fit into 16bit
231 >     * fields.
232 >     *
233 >     * Field "runState" contains 32 bits needed to register and
234 >     * deregister WorkQueues, as well as to enable shutdown. It is
235 >     * only modified under a lock (normally briefly held, but
236 >     * occasionally protecting allocations and resizings) but even
237 >     * when locked remains available to check consistency.
238 >     *
239 >     * Recording WorkQueues.  WorkQueues are recorded in the
240 >     * "workQueues" array that is created upon pool construction and
241 >     * expanded if necessary.  Updates to the array while recording
242 >     * new workers and unrecording terminated ones are protected from
243 >     * each other by a lock but the array is otherwise concurrently
244 >     * readable, and accessed directly.  To simplify index-based
245       * operations, the array size is always a power of two, and all
246 <     * readers must tolerate null slots. To avoid flailing during
247 <     * start-up, the array is presized to hold twice #parallelism
248 <     * workers (which is unlikely to need further resizing during
249 <     * execution). But to avoid dealing with so many null slots,
250 <     * variable scanGuard includes a mask for the nearest power of two
251 <     * that contains all current workers.  All worker thread creation
252 <     * is on-demand, triggered by task submissions, replacement of
253 <     * terminated workers, and/or compensation for blocked
254 <     * workers. However, all other support code is set up to work with
255 <     * other policies.  To ensure that we do not hold on to worker
256 <     * references that would prevent GC, ALL accesses to workers are
257 <     * via indices into the workers array (which is one source of some
258 <     * of the messy code constructions here). In essence, the workers
259 <     * array serves as a weak reference mechanism. Thus for example
260 <     * the wait queue field of ctl stores worker indices, not worker
261 <     * references.  Access to the workers in associated methods (for
262 <     * example signalWork) must both index-check and null-check the
263 <     * IDs. All such accesses ignore bad IDs by returning out early
264 <     * from what they are doing, since this can only be associated
265 <     * with termination, in which case it is OK to give up.
266 <     *
267 <     * All uses of the workers array, as well as queue arrays, check
268 <     * that the array is non-null (even if previously non-null). This
269 <     * allows nulling during termination, which is currently not
270 <     * necessary, but remains an option for resource-revocation-based
271 <     * shutdown schemes.
246 >     * readers must tolerate null slots. Shared (submission) queues
247 >     * are at even indices, worker queues at odd indices. Grouping
248 >     * them together in this way simplifies and speeds up task
249 >     * scanning. To avoid flailing during start-up, the array is
250 >     * presized to hold twice #parallelism workers (which is unlikely
251 >     * to need further resizing during execution). But to avoid
252 >     * dealing with so many null slots, variable runState includes a
253 >     * mask for the nearest power of two that contains all current
254 >     * workers.  All worker thread creation is on-demand, triggered by
255 >     * task submissions, replacement of terminated workers, and/or
256 >     * compensation for blocked workers. However, all other support
257 >     * code is set up to work with other policies.  To ensure that we
258 >     * do not hold on to worker references that would prevent GC, ALL
259 >     * accesses to workQueues are via indices into the workQueues
260 >     * array (which is one source of some of the messy code
261 >     * constructions here). In essence, the workQueues array serves as
262 >     * a weak reference mechanism. Thus for example the wait queue
263 >     * field of ctl stores indices, not references.  Access to the
264 >     * workQueues in associated methods (for example signalWork) must
265 >     * both index-check and null-check the IDs. All such accesses
266 >     * ignore bad IDs by returning out early from what they are doing,
267 >     * since this can only be associated with termination, in which
268 >     * case it is OK to give up.
269 >     *
270 >     * All uses of the workQueues array check that it is non-null
271 >     * (even if previously non-null). This allows nulling during
272 >     * termination, which is currently not necessary, but remains an
273 >     * option for resource-revocation-based shutdown schemes. It also
274 >     * helps reduce JIT issuance of uncommon-trap code, which tends to
275 >     * unnecessarily complicate control flow in some methods.
276       *
277 <     * Wait Queuing. Unlike HPC work-stealing frameworks, we cannot
277 >     * Event Queuing. Unlike HPC work-stealing frameworks, we cannot
278       * let workers spin indefinitely scanning for tasks when none can
279       * be found immediately, and we cannot start/resume workers unless
280       * there appear to be tasks available.  On the other hand, we must
281       * quickly prod them into action when new tasks are submitted or
282 <     * generated.  We park/unpark workers after placing in an event
283 <     * wait queue when they cannot find work. This "queue" is actually
284 <     * a simple Treiber stack, headed by the "id" field of ctl, plus a
285 <     * 15bit counter value to both wake up waiters (by advancing their
286 <     * count) and avoid ABA effects. Successors are held in worker
287 <     * field "nextWait".  Queuing deals with several intrinsic races,
288 <     * mainly that a task-producing thread can miss seeing (and
282 >     * generated. In many usages, ramp-up time to activate workers is
283 >     * the main limiting factor in overall performance (this is
284 >     * compounded at program start-up by JIT compilation and
285 >     * allocation). So we try to streamline this as much as possible.
286 >     * We park/unpark workers after placing in an event wait queue
287 >     * when they cannot find work. This "queue" is actually a simple
288 >     * Treiber stack, headed by the "id" field of ctl, plus a 15bit
289 >     * counter value (that reflects the number of times a worker has
290 >     * been inactivated) to avoid ABA effects (we need only as many
291 >     * version numbers as worker threads). Successors are held in
292 >     * field WorkQueue.nextWait.  Queuing deals with several intrinsic
293 >     * races, mainly that a task-producing thread can miss seeing (and
294       * signalling) another thread that gave up looking for work but
295       * has not yet entered the wait queue. We solve this by requiring
296 <     * a full sweep of all workers both before (in scan()) and after
297 <     * (in tryAwaitWork()) a newly waiting worker is added to the wait
298 <     * queue. During a rescan, the worker might release some other
299 <     * queued worker rather than itself, which has the same net
300 <     * effect. Because enqueued workers may actually be rescanning
301 <     * rather than waiting, we set and clear the "parked" field of
302 <     * ForkJoinWorkerThread to reduce unnecessary calls to unpark.
303 <     * (Use of the parked field requires a secondary recheck to avoid
304 <     * missed signals.)
296 >     * a full sweep of all workers (via repeated calls to method
297 >     * scan()) both before and after a newly waiting worker is added
298 >     * to the wait queue. During a rescan, the worker might release
299 >     * some other queued worker rather than itself, which has the same
300 >     * net effect. Because enqueued workers may actually be rescanning
301 >     * rather than waiting, we set and clear the "parker" field of
302 >     * Workqueues to reduce unnecessary calls to unpark.  (This
303 >     * requires a secondary recheck to avoid missed signals.)  Note
304 >     * the unusual conventions about Thread.interrupts surrounding
305 >     * parking and other blocking: Because interrupts are used solely
306 >     * to alert threads to check termination, which is checked anyway
307 >     * upon blocking, we clear status (using Thread.interrupted)
308 >     * before any call to park, so that park does not immediately
309 >     * return due to status being set via some other unrelated call to
310 >     * interrupt in user code.
311       *
312       * Signalling.  We create or wake up workers only when there
313       * appears to be at least one task they might be able to find and
314       * execute.  When a submission is added or another worker adds a
315 <     * task to a queue that previously had two or fewer tasks, they
315 >     * task to a queue that previously had fewer than two tasks, they
316       * signal waiting workers (or trigger creation of new ones if
317       * fewer than the given parallelism level -- see signalWork).
318 <     * These primary signals are buttressed by signals during rescans
319 <     * as well as those performed when a worker steals a task and
320 <     * notices that there are more tasks too; together these cover the
321 <     * signals needed in cases when more than two tasks are pushed
229 <     * but untaken.
318 >     * These primary signals are buttressed by signals during rescans;
319 >     * together these cover the signals needed in cases when more
320 >     * tasks are pushed but untaken, and improve performance compared
321 >     * to having one thread wake up all workers.
322       *
323       * Trimming workers. To release resources after periods of lack of
324       * use, a worker starting to wait when the pool is quiescent will
# Line 234 | Line 326 | public class ForkJoinPool extends Abstra
326       * SHRINK_RATE nanosecs. This will slowly propagate, eventually
327       * terminating all workers after long periods of non-use.
328       *
329 <     * Submissions. External submissions are maintained in an
330 <     * array-based queue that is structured identically to
331 <     * ForkJoinWorkerThread queues except for the use of
332 <     * submissionLock in method addSubmission. Unlike the case for
333 <     * worker queues, multiple external threads can add new
334 <     * submissions, so adding requires a lock.
335 <     *
336 <     * Compensation. Beyond work-stealing support and lifecycle
337 <     * control, the main responsibility of this framework is to take
338 <     * actions when one worker is waiting to join a task stolen (or
339 <     * always held by) another.  Because we are multiplexing many
340 <     * tasks on to a pool of workers, we can't just let them block (as
341 <     * in Thread.join).  We also cannot just reassign the joiner's
342 <     * run-time stack with another and replace it later, which would
343 <     * be a form of "continuation", that even if possible is not
344 <     * necessarily a good idea since we sometimes need both an
345 <     * unblocked task and its continuation to progress. Instead we
346 <     * combine two tactics:
329 >     * Shutdown and Termination. A call to shutdownNow atomically sets
330 >     * a runState bit and then (non-atomically) sets each workers
331 >     * runState status, cancels all unprocessed tasks, and wakes up
332 >     * all waiting workers.  Detecting whether termination should
333 >     * commence after a non-abrupt shutdown() call requires more work
334 >     * and bookkeeping. We need consensus about quiescence (i.e., that
335 >     * there is no more work). The active count provides a primary
336 >     * indication but non-abrupt shutdown still requires a rechecking
337 >     * scan for any workers that are inactive but not queued.
338 >     *
339 >     * Joining Tasks.
340 >     * ==============
341 >     *
342 >     * Any of several actions may be taken when one worker is waiting
343 >     * to join a task stolen (or always held by) another.  Because we
344 >     * are multiplexing many tasks on to a pool of workers, we can't
345 >     * just let them block (as in Thread.join).  We also cannot just
346 >     * reassign the joiner's run-time stack with another and replace
347 >     * it later, which would be a form of "continuation", that even if
348 >     * possible is not necessarily a good idea since we sometimes need
349 >     * both an unblocked task and its continuation to
350 >     * progress. Instead we combine two tactics:
351       *
352       *   Helping: Arranging for the joiner to execute some task that it
353 <     *      would be running if the steal had not occurred.  Method
258 <     *      ForkJoinWorkerThread.joinTask tracks joining->stealing
259 <     *      links to try to find such a task.
353 >     *      would be running if the steal had not occurred.
354       *
355       *   Compensating: Unless there are already enough live threads,
356 <     *      method tryPreBlock() may create or re-activate a spare
357 <     *      thread to compensate for blocked joiners until they
358 <     *      unblock.
356 >     *      method tryCompensate() may create or re-activate a spare
357 >     *      thread to compensate for blocked joiners until they unblock.
358 >     *
359 >     * A third form (implemented in tryRemoveAndExec and
360 >     * tryPollForAndExec) amounts to helping a hypothetical
361 >     * compensator: If we can readily tell that a possible action of a
362 >     * compensator is to steal and execute the task being joined, the
363 >     * joining thread can do so directly, without the need for a
364 >     * compensation thread (although at the expense of larger run-time
365 >     * stacks, but the tradeoff is typically worthwhile).
366       *
367       * The ManagedBlocker extension API can't use helping so relies
368       * only on compensation in method awaitBlocker.
369       *
370 +     * The algorithm in tryHelpStealer entails a form of "linear"
371 +     * helping: Each worker records (in field currentSteal) the most
372 +     * recent task it stole from some other worker. Plus, it records
373 +     * (in field currentJoin) the task it is currently actively
374 +     * joining. Method tryHelpStealer uses these markers to try to
375 +     * find a worker to help (i.e., steal back a task from and execute
376 +     * it) that could hasten completion of the actively joined task.
377 +     * In essence, the joiner executes a task that would be on its own
378 +     * local deque had the to-be-joined task not been stolen. This may
379 +     * be seen as a conservative variant of the approach in Wagner &
380 +     * Calder "Leapfrogging: a portable technique for implementing
381 +     * efficient futures" SIGPLAN Notices, 1993
382 +     * (http://portal.acm.org/citation.cfm?id=155354). It differs in
383 +     * that: (1) We only maintain dependency links across workers upon
384 +     * steals, rather than use per-task bookkeeping.  This sometimes
385 +     * requires a linear scan of workers array to locate stealers, but
386 +     * often doesn't because stealers leave hints (that may become
387 +     * stale/wrong) of where to locate them.  A stealHint is only a
388 +     * hint because a worker might have had multiple steals and the
389 +     * hint records only one of them (usually the most current).
390 +     * Hinting isolates cost to when it is needed, rather than adding
391 +     * to per-task overhead.  (2) It is "shallow", ignoring nesting
392 +     * and potentially cyclic mutual steals.  (3) It is intentionally
393 +     * racy: field currentJoin is updated only while actively joining,
394 +     * which means that we miss links in the chain during long-lived
395 +     * tasks, GC stalls etc (which is OK since blocking in such cases
396 +     * is usually a good idea).  (4) We bound the number of attempts
397 +     * to find work (see MAX_HELP_DEPTH) and fall back to suspending
398 +     * the worker and if necessary replacing it with another.
399 +     *
400       * It is impossible to keep exactly the target parallelism number
401       * of threads running at any given time.  Determining the
402       * existence of conservatively safe helping targets, the
403       * availability of already-created spares, and the apparent need
404 <     * to create new spares are all racy and require heuristic
405 <     * guidance, so we rely on multiple retries of each.  Currently,
406 <     * in keeping with on-demand signalling policy, we compensate only
407 <     * if blocking would leave less than one active (non-waiting,
408 <     * non-blocked) worker. Additionally, to avoid some false alarms
409 <     * due to GC, lagging counters, system activity, etc, compensated
410 <     * blocking for joins is only attempted after rechecks stabilize
411 <     * (retries are interspersed with Thread.yield, for good
412 <     * citizenship).  The variable blockedCount, incremented before
282 <     * blocking and decremented after, is sometimes needed to
283 <     * distinguish cases of waiting for work vs blocking on joins or
284 <     * other managed sync. Both cases are equivalent for most pool
285 <     * control, so we can update non-atomically. (Additionally,
286 <     * contention on blockedCount alleviates some contention on ctl).
287 <     *
288 <     * Shutdown and Termination. A call to shutdownNow atomically sets
289 <     * the ctl stop bit and then (non-atomically) sets each workers
290 <     * "terminate" status, cancels all unprocessed tasks, and wakes up
291 <     * all waiting workers.  Detecting whether termination should
292 <     * commence after a non-abrupt shutdown() call requires more work
293 <     * and bookkeeping. We need consensus about quiescence (i.e., that
294 <     * there is no more work) which is reflected in active counts so
295 <     * long as there are no current blockers, as well as possible
296 <     * re-evaluations during independent changes in blocking or
297 <     * quiescing workers.
404 >     * to create new spares are all racy, so we rely on multiple
405 >     * retries of each.  Currently, in keeping with on-demand
406 >     * signalling policy, we compensate only if blocking would leave
407 >     * less than one active (non-waiting, non-blocked) worker.
408 >     * Additionally, to avoid some false alarms due to GC, lagging
409 >     * counters, system activity, etc, compensated blocking for joins
410 >     * is only attempted after rechecks stabilize in
411 >     * ForkJoinTask.awaitJoin. (Retries are interspersed with
412 >     * Thread.yield, for good citizenship.)
413       *
414       * Style notes: There is a lot of representation-level coupling
415       * among classes ForkJoinPool, ForkJoinWorkerThread, and
416 <     * ForkJoinTask.  Most fields of ForkJoinWorkerThread maintain
417 <     * data structures managed by ForkJoinPool, so are directly
418 <     * accessed.  Conversely we allow access to "workers" array by
419 <     * workers, and direct access to ForkJoinTask.status by both
420 <     * ForkJoinPool and ForkJoinWorkerThread.  There is little point
421 <     * trying to reduce this, since any associated future changes in
422 <     * representations will need to be accompanied by algorithmic
423 <     * changes anyway. All together, these low-level implementation
424 <     * choices produce as much as a factor of 4 performance
310 <     * improvement compared to naive implementations, and enable the
311 <     * processing of billions of tasks per second, at the expense of
312 <     * some ugliness.
416 >     * ForkJoinTask.  The fields of WorkQueue maintain data structures
417 >     * managed by ForkJoinPool, so are directly accessed.  There is
418 >     * little point trying to reduce this, since any associated future
419 >     * changes in representations will need to be accompanied by
420 >     * algorithmic changes anyway. All together, these low-level
421 >     * implementation choices produce as much as a factor of 4
422 >     * performance improvement compared to naive implementations, and
423 >     * enable the processing of billions of tasks per second, at the
424 >     * expense of some ugliness.
425       *
426       * Methods signalWork() and scan() are the main bottlenecks so are
427       * especially heavily micro-optimized/mangled.  There are lots of
# Line 326 | Line 438 | public class ForkJoinPool extends Abstra
438       * The order of declarations in this file is: (1) declarations of
439       * statics (2) fields (along with constants used when unpacking
440       * some of them), listed in an order that tends to reduce
441 <     * contention among them a bit under most JVMs.  (3) internal
442 <     * control methods (4) callbacks and other support for
443 <     * ForkJoinTask and ForkJoinWorkerThread classes, (5) exported
444 <     * methods (plus a few little helpers). (6) static block
445 <     * initializing all statics in a minimally dependent order.
441 >     * contention among them a bit under most JVMs; (3) nested
442 >     * classes; (4) internal control methods; (5) callbacks and other
443 >     * support for ForkJoinTask methods; (6) exported methods (plus a
444 >     * few little helpers); (7) static block initializing all statics
445 >     * in a minimally dependent order.
446       */
447  
448      /**
# Line 389 | Line 501 | public class ForkJoinPool extends Abstra
501      private static final AtomicInteger poolNumberGenerator;
502  
503      /**
504 <     * Generator for initial random seeds for worker victim
505 <     * selection. This is used only to create initial seeds. Random
506 <     * steals use a cheaper xorshift generator per steal attempt. We
395 <     * don't expect much contention on seedGenerator, so just use a
396 <     * plain Random.
397 <     */
398 <    static final Random workerSeedGenerator;
399 <
400 <    /**
401 <     * Array holding all worker threads in the pool.  Initialized upon
402 <     * construction. Array size must be a power of two.  Updates and
403 <     * replacements are protected by scanGuard, but the array is
404 <     * always kept in a consistent enough state to be randomly
405 <     * accessed without locking by workers performing work-stealing,
406 <     * as well as other traversal-based methods in this class, so long
407 <     * as reads memory-acquire by first reading ctl. All readers must
408 <     * tolerate that some array slots may be null.
409 <     */
410 <    ForkJoinWorkerThread[] workers;
411 <
412 <    /**
413 <     * Initial size for submission queue array. Must be a power of
414 <     * two.  In many applications, these always stay small so we use a
415 <     * small initial cap.
416 <     */
417 <    private static final int INITIAL_QUEUE_CAPACITY = 8;
418 <
419 <    /**
420 <     * Maximum size for submission queue array. Must be a power of two
421 <     * less than or equal to 1 << (31 - width of array entry) to
422 <     * ensure lack of index wraparound, but is capped at a lower
423 <     * value to help users trap runaway computations.
424 <     */
425 <    private static final int MAXIMUM_QUEUE_CAPACITY = 1 << 24; // 16M
426 <
427 <    /**
428 <     * Array serving as submission queue. Initialized upon construction.
429 <     */
430 <    private ForkJoinTask<?>[] submissionQueue;
431 <
432 <    /**
433 <     * Lock protecting submissions array for addSubmission
434 <     */
435 <    private final ReentrantLock submissionLock;
436 <
437 <    /**
438 <     * Condition for awaitTermination, using submissionLock for
439 <     * convenience.
440 <     */
441 <    private final Condition termination;
442 <
443 <    /**
444 <     * Creation factory for worker threads.
445 <     */
446 <    private final ForkJoinWorkerThreadFactory factory;
447 <
448 <    /**
449 <     * The uncaught exception handler used when any worker abruptly
450 <     * terminates.
451 <     */
452 <    final Thread.UncaughtExceptionHandler ueh;
453 <
454 <    /**
455 <     * Prefix for assigning names to worker threads
456 <     */
457 <    private final String workerNamePrefix;
458 <
459 <    /**
460 <     * Sum of per-thread steal counts, updated only when threads are
461 <     * idle or terminating.
462 <     */
463 <    private volatile long stealCount;
464 <
465 <    /**
466 <     * Main pool control -- a long packed with:
504 >     * Bits and masks for control variables
505 >     *
506 >     * Field ctl is a long packed with:
507       * AC: Number of active running workers minus target parallelism (16 bits)
508 <     * TC: Number of total workers minus target parallelism (16bits)
508 >     * TC: Number of total workers minus target parallelism (16 bits)
509       * ST: true if pool is terminating (1 bit)
510       * EC: the wait count of top waiting thread (15 bits)
511 <     * ID: ~poolIndex of top of Treiber stack of waiting threads (16 bits)
511 >     * ID: ~(poolIndex >>> 1) of top of Treiber stack of waiters (16 bits)
512       *
513       * When convenient, we can extract the upper 32 bits of counts and
514       * the lower 32 bits of queue state, u = (int)(ctl >>> 32) and e =
# Line 482 | Line 522 | public class ForkJoinPool extends Abstra
522       * negative, the pool is terminating.  To deal with these possibly
523       * negative fields, we use casts in and out of "short" and/or
524       * signed shifts to maintain signedness.
525 +     *
526 +     * When a thread is queued (inactivated), its eventCount field is
527 +     * negative, which is the only way to tell if a worker is
528 +     * prevented from executing tasks, even though it must continue to
529 +     * scan for them to avoid queuing races.
530 +     *
531 +     * Field runState is an int packed with:
532 +     * SHUTDOWN: true if shutdown is enabled (1 bit)
533 +     * SEQ:  a sequence number updated upon (de)registering workers (15 bits)
534 +     * MASK: mask (power of 2 - 1) covering all registered poolIndexes (16 bits)
535 +     *
536 +     * The combination of mask and sequence number enables simple
537 +     * consistency checks: Staleness of read-only operations on the
538 +     * workers and queues arrays can be checked by comparing runState
539 +     * before vs after the reads. The low 16 bits (i.e, anding with
540 +     * SMASK) hold (the smallest power of two covering all worker
541 +     * indices, minus one.  The mask for queues (vs workers) is twice
542 +     * this value plus 1.
543       */
486    volatile long ctl;
544  
545      // bit positions/shifts for fields
546      private static final int  AC_SHIFT   = 48;
# Line 515 | Line 572 | public class ForkJoinPool extends Abstra
572      private static final int  UTC_UNIT   = 1 << UTC_SHIFT;
573  
574      // masks and units for dealing with e = (int)ctl
575 <    private static final int  E_MASK     = 0x7fffffff; // no STOP_BIT
576 <    private static final int  EC_UNIT    = 1 << EC_SHIFT;
575 >    private static final int E_MASK      = 0x7fffffff; // no STOP_BIT
576 >    private static final int E_SEQ       = 1 << EC_SHIFT;
577  
578 <    /**
579 <     * The target parallelism level.
580 <     */
581 <    final int parallelism;
578 >    // runState bits
579 >    private static final int SHUTDOWN    = 1 << 31;
580 >    private static final int RS_SEQ      = 1 << 16;
581 >    private static final int RS_SEQ_MASK = 0x7fff0000;
582 >
583 >    // access mode for WorkQueue
584 >    static final int LIFO_QUEUE          =  0;
585 >    static final int FIFO_QUEUE          =  1;
586 >    static final int SHARED_QUEUE        = -1;
587  
588      /**
589 <     * Index (mod submission queue length) of next element to take
590 <     * from submission queue. Usage is identical to that for
591 <     * per-worker queues -- see ForkJoinWorkerThread internal
592 <     * documentation.
589 >     * The wakeup interval (in nanoseconds) for a worker waiting for a
590 >     * task when the pool is quiescent to instead try to shrink the
591 >     * number of workers.  The exact value does not matter too
592 >     * much. It must be short enough to release resources during
593 >     * sustained periods of idleness, but not so short that threads
594 >     * are continually re-created.
595       */
596 <    volatile int queueBase;
596 >    private static final long SHRINK_RATE =
597 >        4L * 1000L * 1000L * 1000L; // 4 seconds
598  
599      /**
600 <     * Index (mod submission queue length) of next element to add
601 <     * in submission queue. Usage is identical to that for
537 <     * per-worker queues -- see ForkJoinWorkerThread internal
538 <     * documentation.
600 >     * The timeout value for attempted shrinkage, includes
601 >     * some slop to cope with system timer imprecision.
602       */
603 <    int queueTop;
603 >    private static final long SHRINK_TIMEOUT = SHRINK_RATE - (SHRINK_RATE / 10);
604  
605      /**
606 <     * True when shutdown() has been called.
606 >     * The maximum stolen->joining link depth allowed in tryHelpStealer.
607 >     * Depths for legitimate chains are unbounded, but we use a fixed
608 >     * constant to avoid (otherwise unchecked) cycles and to bound
609 >     * staleness of traversal parameters at the expense of sometimes
610 >     * blocking when we could be helping.
611       */
612 <    volatile boolean shutdown;
612 >    private static final int MAX_HELP_DEPTH = 16;
613  
614 <    /**
615 <     * True if use local fifo, not default lifo, for local polling
616 <     * Read by, and replicated by ForkJoinWorkerThreads
614 >    /*
615 >     * Field layout order in this class tends to matter more than one
616 >     * would like. Runtime layout order is only loosely related to
617 >     * declaration order and may differ across JVMs, but the following
618 >     * empirically works OK on current JVMs.
619 >     */
620 >
621 >    volatile long ctl;                       // main pool control
622 >    final int parallelism;                   // parallelism level
623 >    final int localMode;                     // per-worker scheduling mode
624 >    int nextPoolIndex;                       // hint used in registerWorker
625 >    volatile int runState;                   // shutdown status, seq, and mask
626 >    WorkQueue[] workQueues;                  // main registry
627 >    final ReentrantLock lock;                // for registration
628 >    final Condition termination;             // for awaitTermination
629 >    final ForkJoinWorkerThreadFactory factory; // factory for new workers
630 >    final Thread.UncaughtExceptionHandler ueh; // per-worker UEH
631 >    final AtomicLong stealCount;             // collect counts when terminated
632 >    final AtomicInteger nextWorkerNumber;    // to create worker name string
633 >    final String workerNamePrefix;           // Prefix for assigning worker names
634 >
635 >    /**
636 >     * Queues supporting work-stealing as well as external task
637 >     * submission. See above for main rationale and algorithms.
638 >     * Implementation relies heavily on "Unsafe" intrinsics
639 >     * and selective use of "volatile":
640 >     *
641 >     * Field "base" is the index (mod array.length) of the least valid
642 >     * queue slot, which is always the next position to steal (poll)
643 >     * from if nonempty. Reads and writes require volatile orderings
644 >     * but not CAS, because updates are only performed after slot
645 >     * CASes.
646 >     *
647 >     * Field "top" is the index (mod array.length) of the next queue
648 >     * slot to push to or pop from. It is written only by owner thread
649 >     * for push, or under lock for trySharedPush, and accessed by
650 >     * other threads only after reading (volatile) base.  Both top and
651 >     * base are allowed to wrap around on overflow, but (top - base)
652 >     * (or more commonly -(base - top) to force volatile read of base
653 >     * before top) still estimates size.
654 >     *
655 >     * The array slots are read and written using the emulation of
656 >     * volatiles/atomics provided by Unsafe. Insertions must in
657 >     * general use putOrderedObject as a form of releasing store to
658 >     * ensure that all writes to the task object are ordered before
659 >     * its publication in the queue. (Although we can avoid one case
660 >     * of this when locked in trySharedPush.) All removals entail a
661 >     * CAS to null.  The array is always a power of two. To ensure
662 >     * safety of Unsafe array operations, all accesses perform
663 >     * explicit null checks and implicit bounds checks via
664 >     * power-of-two masking.
665 >     *
666 >     * In addition to basic queuing support, this class contains
667 >     * fields described elsewhere to control execution. It turns out
668 >     * to work better memory-layout-wise to include them in this
669 >     * class rather than a separate class.
670 >     *
671 >     * Performance on most platforms is very sensitive to placement of
672 >     * instances of both WorkQueues and their arrays -- we absolutely
673 >     * do not want multiple WorkQueue instances or multiple queue
674 >     * arrays sharing cache lines. (It would be best for queue objects
675 >     * and their arrays to share, but there is nothing available to
676 >     * help arrange that).  Unfortunately, because they are recorded
677 >     * in a common array, WorkQueue instances are often moved to be
678 >     * adjacent by garbage collectors. To reduce impact, we use field
679 >     * padding that works OK on common platforms; this effectively
680 >     * trades off slightly slower average field access for the sake of
681 >     * avoiding really bad worst-case access. (Until better JVM
682 >     * support is in place, this padding is dependent on transient
683 >     * properties of JVM field layout rules.)  We also take care in
684 >     * allocating and sizing and resizing the array. Non-shared queue
685 >     * arrays are initialized (via method growArray) by workers before
686 >     * use. Others are allocated on first use.
687       */
688 <    final boolean locallyFifo;
688 >    static final class WorkQueue {
689 >        /**
690 >         * Capacity of work-stealing queue array upon initialization.
691 >         * Must be a power of two; at least 4, but set larger to
692 >         * reduce cacheline sharing among queues.
693 >         */
694 >        static final int INITIAL_QUEUE_CAPACITY = 1 << 8;
695 >
696 >        /**
697 >         * Maximum size for queue arrays. Must be a power of two less
698 >         * than or equal to 1 << (31 - width of array entry) to ensure
699 >         * lack of wraparound of index calculations, but defined to a
700 >         * value a bit less than this to help users trap runaway
701 >         * programs before saturating systems.
702 >         */
703 >        static final int MAXIMUM_QUEUE_CAPACITY = 1 << 26; // 64M
704 >
705 >        volatile long totalSteals; // cumulative number of steals
706 >        int seed;                  // for random scanning; initialize nonzero
707 >        volatile int eventCount;   // encoded inactivation count; < 0 if inactive
708 >        int nextWait;              // encoded record of next event waiter
709 >        int rescans;               // remaining scans until block
710 >        int nsteals;               // top-level task executions since last idle
711 >        final int mode;            // lifo, fifo, or shared
712 >        int poolIndex;             // index of this queue in pool (or 0)
713 >        int stealHint;             // index of most recent known stealer
714 >        volatile int runState;     // 1: locked, -1: terminate; else 0
715 >        volatile int base;         // index of next slot for poll
716 >        int top;                   // index of next slot for push
717 >        ForkJoinTask<?>[] array;   // the elements (initially unallocated)
718 >        final ForkJoinWorkerThread owner; // owning thread or null if shared
719 >        volatile Thread parker;    // == owner during call to park; else null
720 >        ForkJoinTask<?> currentJoin;  // task being joined in awaitJoin
721 >        ForkJoinTask<?> currentSteal; // current non-local task being executed
722 >        // Heuristic padding to ameliorate unfortunate memory placements
723 >        Object p00, p01, p02, p03, p04, p05, p06, p07, p08, p09, p0a;
724 >
725 >        WorkQueue(ForkJoinWorkerThread owner, int mode) {
726 >            this.owner = owner;
727 >            this.mode = mode;
728 >            // Place indices in the center of array (that is not yet allocated)
729 >            base = top = INITIAL_QUEUE_CAPACITY >>> 1;
730 >        }
731 >
732 >        /**
733 >         * Returns number of tasks in the queue
734 >         */
735 >        final int queueSize() {
736 >            int n = base - top; // non-owner callers must read base first
737 >            return (n >= 0) ? 0 : -n;
738 >        }
739 >
740 >        /**
741 >         * Pushes a task. Call only by owner in unshared queues.
742 >         *
743 >         * @param task the task. Caller must ensure non-null.
744 >         * @param p, if non-null, pool to signal if necessary
745 >         * @throw RejectedExecutionException if array cannot
746 >         * be resized
747 >         */
748 >        final void push(ForkJoinTask<?> task, ForkJoinPool p) {
749 >            ForkJoinTask<?>[] a;
750 >            int s = top, m, n;
751 >            if ((a = array) != null) {    // ignore if queue removed
752 >                U.putOrderedObject
753 >                    (a, (((m = a.length - 1) & s) << ASHIFT) + ABASE, task);
754 >                if ((n = (top = s + 1) - base) <= 2) {
755 >                    if (p != null)
756 >                        p.signalWork();
757 >                }
758 >                else if (n >= m)
759 >                    growArray(true);
760 >            }
761 >        }
762 >
763 >        /**
764 >         * Pushes a task if lock is free and array is either big
765 >         * enough or can be resized to be big enough.
766 >         *
767 >         * @param task the task. Caller must ensure non-null.
768 >         * @return true if submitted
769 >         */
770 >        final boolean trySharedPush(ForkJoinTask<?> task) {
771 >            boolean submitted = false;
772 >            if (runState == 0 && U.compareAndSwapInt(this, RUNSTATE, 0, 1)) {
773 >                ForkJoinTask<?>[] a = array;
774 >                int s = top, n = s - base;
775 >                try {
776 >                    if ((a != null && n < a.length - 1) ||
777 >                        (a = growArray(false)) != null) { // must presize
778 >                        int j = (((a.length - 1) & s) << ASHIFT) + ABASE;
779 >                        U.putObject(a, (long)j, task);    // don't need "ordered"
780 >                        top = s + 1;
781 >                        submitted = true;
782 >                    }
783 >                } finally {
784 >                    runState = 0;                         // unlock
785 >                }
786 >            }
787 >            return submitted;
788 >        }
789 >
790 >        /**
791 >         * Takes next task, if one exists, in FIFO order.
792 >         */
793 >        final ForkJoinTask<?> poll() {
794 >            ForkJoinTask<?>[] a; int b, i;
795 >            while ((b = base) - top < 0 && (a = array) != null &&
796 >                   (i = (a.length - 1) & b) >= 0) {
797 >                int j = (i << ASHIFT) + ABASE;
798 >                ForkJoinTask<?> t = (ForkJoinTask<?>)U.getObjectVolatile(a, j);
799 >                if (t != null && base == b &&
800 >                    U.compareAndSwapObject(a, j, t, null)) {
801 >                    base = b + 1;
802 >                    return t;
803 >                }
804 >            }
805 >            return null;
806 >        }
807 >
808 >        /**
809 >         * Takes next task, if one exists, in LIFO order.
810 >         * Call only by owner in unshared queues.
811 >         */
812 >        final ForkJoinTask<?> pop() {
813 >            ForkJoinTask<?> t; int m;
814 >            ForkJoinTask<?>[] a = array;
815 >            if (a != null && (m = a.length - 1) >= 0) {
816 >                for (int s; (s = top - 1) - base >= 0;) {
817 >                    int j = ((m & s) << ASHIFT) + ABASE;
818 >                    if ((t = (ForkJoinTask<?>)U.getObjectVolatile(a, j)) == null)
819 >                        break;
820 >                    if (U.compareAndSwapObject(a, j, t, null)) {
821 >                        top = s;
822 >                        return t;
823 >                    }
824 >                }
825 >            }
826 >            return null;
827 >        }
828 >
829 >        /**
830 >         * Takes next task, if one exists, in order specified by mode.
831 >         */
832 >        final ForkJoinTask<?> nextLocalTask() {
833 >            return mode == 0 ? pop() : poll();
834 >        }
835 >
836 >        /**
837 >         * Returns next task, if one exists, in order specified by mode.
838 >         */
839 >        final ForkJoinTask<?> peek() {
840 >            ForkJoinTask<?>[] a = array; int m;
841 >            if (a == null || (m = a.length - 1) < 0)
842 >                return null;
843 >            int i = mode == 0 ? top - 1 : base;
844 >            int j = ((i & m) << ASHIFT) + ABASE;
845 >            return (ForkJoinTask<?>)U.getObjectVolatile(a, j);
846 >        }
847 >
848 >        /**
849 >         * Returns task at index b if b is current base of queue.
850 >         */
851 >        final ForkJoinTask<?> pollAt(int b) {
852 >            ForkJoinTask<?>[] a; int i;
853 >            ForkJoinTask<?> task = null;
854 >            if ((a = array) != null && (i = ((a.length - 1) & b)) >= 0) {
855 >                int j = (i << ASHIFT) + ABASE;
856 >                ForkJoinTask<?> t = (ForkJoinTask<?>)U.getObjectVolatile(a, j);
857 >                if (t != null && base == b &&
858 >                    U.compareAndSwapObject(a, j, t, null)) {
859 >                    base = b + 1;
860 >                    task = t;
861 >                }
862 >            }
863 >            return task;
864 >        }
865 >
866 >        /**
867 >         * Pops the given task only if it is at the current top.
868 >         */
869 >        final boolean tryUnpush(ForkJoinTask<?> t) {
870 >            ForkJoinTask<?>[] a; int s;
871 >            if ((a = array) != null && (s = top) != base &&
872 >                U.compareAndSwapObject
873 >                (a, (((a.length - 1) & --s) << ASHIFT) + ABASE, t, null)) {
874 >                top = s;
875 >                return true;
876 >            }
877 >            return false;
878 >        }
879 >
880 >        /**
881 >         * Polls the given task only if it is at the current base.
882 >         */
883 >        final boolean pollFor(ForkJoinTask<?> task) {
884 >            ForkJoinTask<?>[] a; int b, i;
885 >            if ((b = base) - top < 0 && (a = array) != null &&
886 >                (i = (a.length - 1) & b) >= 0) {
887 >                int j = (i << ASHIFT) + ABASE;
888 >                if (U.getObjectVolatile(a, j) == task && base == b &&
889 >                    U.compareAndSwapObject(a, j, task, null)) {
890 >                    base = b + 1;
891 >                    return true;
892 >                }
893 >            }
894 >            return false;
895 >        }
896 >
897 >        /**
898 >         * If present, removes from queue and executes the given task, or
899 >         * any other cancelled task. Returns (true) immediately on any CAS
900 >         * or consistency check failure so caller can retry.
901 >         *
902 >         * @return false if no progress can be made
903 >         */
904 >        final boolean tryRemoveAndExec(ForkJoinTask<?> task) {
905 >            boolean removed = false, empty = true, progress = true;
906 >            ForkJoinTask<?>[] a; int m, s, b, n;
907 >            if ((a = array) != null && (m = a.length - 1) >= 0 &&
908 >                (n = (s = top) - (b = base)) > 0) {
909 >                for (ForkJoinTask<?> t;;) {           // traverse from s to b
910 >                    int j = ((--s & m) << ASHIFT) + ABASE;
911 >                    t = (ForkJoinTask<?>)U.getObjectVolatile(a, j);
912 >                    if (t == null)                    // inconsistent length
913 >                        break;
914 >                    else if (t == task) {
915 >                        if (s + 1 == top) {           // pop
916 >                            if (!U.compareAndSwapObject(a, j, task, null))
917 >                                break;
918 >                            top = s;
919 >                            removed = true;
920 >                        }
921 >                        else if (base == b)           // replace with proxy
922 >                            removed = U.compareAndSwapObject(a, j, task,
923 >                                                             new EmptyTask());
924 >                        break;
925 >                    }
926 >                    else if (t.status >= 0)
927 >                        empty = false;
928 >                    else if (s + 1 == top) {          // pop and throw away
929 >                        if (U.compareAndSwapObject(a, j, t, null))
930 >                            top = s;
931 >                        break;
932 >                    }
933 >                    if (--n == 0) {
934 >                        if (!empty && base == b)
935 >                            progress = false;
936 >                        break;
937 >                    }
938 >                }
939 >            }
940 >            if (removed)
941 >                task.doExec();
942 >            return progress;
943 >        }
944 >
945 >        /**
946 >         * Initializes or doubles the capacity of array. Call either
947 >         * by owner or with lock held -- it is OK for base, but not
948 >         * top, to move while resizings are in progress.
949 >         *
950 >         * @param rejectOnFailure if true, throw exception if capacity
951 >         * exceeded (relayed ultimately to user); else return null.
952 >         */
953 >        final ForkJoinTask<?>[] growArray(boolean rejectOnFailure) {
954 >            ForkJoinTask<?>[] oldA = array;
955 >            int size = oldA != null ? oldA.length << 1 : INITIAL_QUEUE_CAPACITY;
956 >            if (size <= MAXIMUM_QUEUE_CAPACITY) {
957 >                int oldMask, t, b;
958 >                ForkJoinTask<?>[] a = array = new ForkJoinTask<?>[size];
959 >                if (oldA != null && (oldMask = oldA.length - 1) >= 0 &&
960 >                    (t = top) - (b = base) > 0) {
961 >                    int mask = size - 1;
962 >                    do {
963 >                        ForkJoinTask<?> x;
964 >                        int oldj = ((b & oldMask) << ASHIFT) + ABASE;
965 >                        int j    = ((b &    mask) << ASHIFT) + ABASE;
966 >                        x = (ForkJoinTask<?>)U.getObjectVolatile(oldA, oldj);
967 >                        if (x != null &&
968 >                            U.compareAndSwapObject(oldA, oldj, x, null))
969 >                            U.putObjectVolatile(a, j, x);
970 >                    } while (++b != t);
971 >                }
972 >                return a;
973 >            }
974 >            else if (!rejectOnFailure)
975 >                return null;
976 >            else
977 >                throw new RejectedExecutionException("Queue capacity exceeded");
978 >        }
979 >
980 >        /**
981 >         * Removes and cancels all known tasks, ignoring any exceptions
982 >         */
983 >        final void cancelAll() {
984 >            ForkJoinTask.cancelIgnoringExceptions(currentJoin);
985 >            ForkJoinTask.cancelIgnoringExceptions(currentSteal);
986 >            for (ForkJoinTask<?> t; (t = poll()) != null; )
987 >                ForkJoinTask.cancelIgnoringExceptions(t);
988 >        }
989 >
990 >        // Execution methods
991 >
992 >        /**
993 >         * Removes and runs tasks until empty, using local mode
994 >         * ordering.
995 >         */
996 >        final void runLocalTasks() {
997 >            if (base - top < 0) {
998 >                for (ForkJoinTask<?> t; (t = nextLocalTask()) != null; )
999 >                    t.doExec();
1000 >            }
1001 >        }
1002 >
1003 >        /**
1004 >         * Executes a top-level task and any local tasks remaining
1005 >         * after execution.
1006 >         *
1007 >         * @return true unless terminating
1008 >         */
1009 >        final boolean runTask(ForkJoinTask<?> t) {
1010 >            boolean alive = true;
1011 >            if (t != null) {
1012 >                currentSteal = t;
1013 >                t.doExec();
1014 >                runLocalTasks();
1015 >                ++nsteals;
1016 >                currentSteal = null;
1017 >            }
1018 >            else if (runState < 0)            // terminating
1019 >                alive = false;
1020 >            return alive;
1021 >        }
1022 >
1023 >        /**
1024 >         * Executes a non-top-level (stolen) task
1025 >         */
1026 >        final void runSubtask(ForkJoinTask<?> t) {
1027 >            if (t != null) {
1028 >                ForkJoinTask<?> ps = currentSteal;
1029 >                currentSteal = t;
1030 >                t.doExec();
1031 >                currentSteal = ps;
1032 >            }
1033 >        }
1034 >
1035 >        /**
1036 >         * Computes next value for random probes.  Scans don't require
1037 >         * a very high quality generator, but also not a crummy one.
1038 >         * Marsaglia xor-shift is cheap and works well enough.  Note:
1039 >         * This is manually inlined in several usages in ForkJoinPool
1040 >         * to avoid writes inside busy scan loops.
1041 >         */
1042 >        final int nextSeed() {
1043 >            int r = seed;
1044 >            r ^= r << 13;
1045 >            r ^= r >>> 17;
1046 >            r ^= r << 5;
1047 >            return seed = r;
1048 >        }
1049 >
1050 >        // Unsafe mechanics
1051 >        private static final sun.misc.Unsafe U;
1052 >        private static final long RUNSTATE;
1053 >        private static final int ABASE;
1054 >        private static final int ASHIFT;
1055 >        static {
1056 >            int s;
1057 >            try {
1058 >                U = getUnsafe();
1059 >                Class<?> k = WorkQueue.class;
1060 >                Class<?> ak = ForkJoinTask[].class;
1061 >                RUNSTATE = U.objectFieldOffset
1062 >                    (k.getDeclaredField("runState"));
1063 >                ABASE = U.arrayBaseOffset(ak);
1064 >                s = U.arrayIndexScale(ak);
1065 >            } catch (Exception e) {
1066 >                throw new Error(e);
1067 >            }
1068 >            if ((s & (s-1)) != 0)
1069 >                throw new Error("data type scale not a power of two");
1070 >            ASHIFT = 31 - Integer.numberOfLeadingZeros(s);
1071 >        }
1072 >    }
1073  
1074      /**
1075 <     * The number of threads in ForkJoinWorkerThreads.helpQuiescePool.
1076 <     * When non-zero, suppresses automatic shutdown when active
1077 <     * counts become zero.
1075 >     * Class for artificial tasks that are used to replace the target
1076 >     * of local joins if they are removed from an interior queue slot
1077 >     * in WorkQueue.tryRemoveAndExec. We don't need the proxy to
1078 >     * actually do anything beyond having a unique identity.
1079       */
1080 <    volatile int quiescerCount;
1080 >    static final class EmptyTask extends ForkJoinTask<Void> {
1081 >        EmptyTask() { status = ForkJoinTask.NORMAL; } // force done
1082 >        public Void getRawResult() { return null; }
1083 >        public void setRawResult(Void x) {}
1084 >        public boolean exec() { return true; }
1085 >    }
1086  
1087      /**
1088 <     * The number of threads blocked in join.
1088 >     * Computes a hash code for the given thread. This method is
1089 >     * expected to provide higher-quality hash codes than those using
1090 >     * method hashCode().
1091       */
1092 <    volatile int blockedCount;
1092 >    static final int hashThread(Thread t) {
1093 >        long id = (t == null) ? 0L : t.getId(); // Use MurmurHash of thread id
1094 >        int h = (int)id ^ (int)(id >>> 32);
1095 >        h ^= h >>> 16;
1096 >        h *= 0x85ebca6b;
1097 >        h ^= h >>> 13;
1098 >        h *= 0xc2b2ae35;
1099 >        return h ^ (h >>> 16);
1100 >    }
1101  
1102      /**
1103 <     * Counter for worker Thread names (unrelated to their poolIndex)
1103 >     * Top-level runloop for workers
1104       */
1105 <    private volatile int nextWorkerNumber;
1105 >    final void runWorker(ForkJoinWorkerThread wt) {
1106 >        WorkQueue w = wt.workQueue;
1107 >        w.growArray(false);     // Initialize queue array and seed in this thread
1108 >        w.seed = hashThread(Thread.currentThread()) | (1 << 31); // force < 0
1109 >
1110 >        do {} while (w.runTask(scan(w)));
1111 >    }
1112 >
1113 >    // Creating, registering and deregistering workers
1114  
1115      /**
1116 <     * The index for the next created worker. Accessed under scanGuard.
1116 >     * Tries to create and start a worker
1117       */
1118 <    private int nextWorkerIndex;
1118 >    private void addWorker() {
1119 >        Throwable ex = null;
1120 >        ForkJoinWorkerThread w = null;
1121 >        try {
1122 >            if ((w = factory.newThread(this)) != null) {
1123 >                w.start();
1124 >                return;
1125 >            }
1126 >        } catch (Throwable e) {
1127 >            ex = e;
1128 >        }
1129 >        deregisterWorker(w, ex);
1130 >    }
1131  
1132      /**
1133 <     * SeqLock and index masking for updates to workers array.  Locked
1134 <     * when SG_UNIT is set. Unlocking clears bit by adding
1135 <     * SG_UNIT. Staleness of read-only operations can be checked by
1136 <     * comparing scanGuard to value before the reads. The low 16 bits
580 <     * (i.e, anding with SMASK) hold (the smallest power of two
581 <     * covering all worker indices, minus one, and is used to avoid
582 <     * dealing with large numbers of null slots when the workers array
583 <     * is overallocated.
1133 >     * Callback from ForkJoinWorkerThread constructor to assign a
1134 >     * public name. This must be separate from registerWorker because
1135 >     * it is called during the "super" constructor call in
1136 >     * ForkJoinWorkerThread.
1137       */
1138 <    volatile int scanGuard;
1139 <
1140 <    private static final int SG_UNIT = 1 << 16;
1138 >    final String nextWorkerName() {
1139 >        return workerNamePrefix.concat
1140 >            (Integer.toString(nextWorkerNumber.addAndGet(1)));
1141 >    }
1142  
1143      /**
1144 <     * The wakeup interval (in nanoseconds) for a worker waiting for a
1145 <     * task when the pool is quiescent to instead try to shrink the
1146 <     * number of workers.  The exact value does not matter too
1147 <     * much. It must be short enough to release resources during
594 <     * sustained periods of idleness, but not so short that threads
595 <     * are continually re-created.
1144 >     * Callback from ForkJoinWorkerThread constructor to establish and
1145 >     * record its WorkQueue
1146 >     *
1147 >     * @param wt the worker thread
1148       */
1149 <    private static final long SHRINK_RATE =
1150 <        4L * 1000L * 1000L * 1000L; // 4 seconds
1149 >    final void registerWorker(ForkJoinWorkerThread wt) {
1150 >        WorkQueue w = wt.workQueue;
1151 >        ReentrantLock lock = this.lock;
1152 >        lock.lock();
1153 >        try {
1154 >            int k = nextPoolIndex;
1155 >            WorkQueue[] ws = workQueues;
1156 >            if (ws != null) {                       // ignore on shutdown
1157 >                int n = ws.length;
1158 >                if (k < 0 || (k & 1) == 0 || k >= n || ws[k] != null) {
1159 >                    for (k = 1; k < n && ws[k] != null; k += 2)
1160 >                        ;                           // workers are at odd indices
1161 >                    if (k >= n)                     // resize
1162 >                        workQueues = ws = Arrays.copyOf(ws, n << 1);
1163 >                }
1164 >                w.poolIndex = k;
1165 >                w.eventCount = ~(k >>> 1) & SMASK;  // Set up wait count
1166 >                ws[k] = w;                          // record worker
1167 >                nextPoolIndex = k + 2;
1168 >                int rs = runState;
1169 >                int m = rs & SMASK;                 // recalculate runState mask
1170 >                if (k > m)
1171 >                    m = (m << 1) + 1;
1172 >                runState = (rs & SHUTDOWN) | ((rs + RS_SEQ) & RS_SEQ_MASK) | m;
1173 >            }
1174 >        } finally {
1175 >            lock.unlock();
1176 >        }
1177 >    }
1178  
1179      /**
1180 <     * Top-level loop for worker threads: On each step: if the
1181 <     * previous step swept through all queues and found no tasks, or
1182 <     * there are excess threads, then possibly blocks. Otherwise,
1183 <     * scans for and, if found, executes a task. Returns when pool
605 <     * and/or worker terminate.
1180 >     * Final callback from terminating worker, as well as failure to
1181 >     * construct or start a worker in addWorker.  Removes record of
1182 >     * worker from array, and adjusts counts. If pool is shutting
1183 >     * down, tries to complete termination.
1184       *
1185 <     * @param w the worker
1185 >     * @param wt the worker thread or null if addWorker failed
1186 >     * @param ex the exception causing failure, or null if none
1187       */
1188 <    final void work(ForkJoinWorkerThread w) {
1189 <        boolean swept = false;                // true on empty scans
1190 <        long c;
1191 <        while (!w.terminate && (int)(c = ctl) >= 0) {
1192 <            int a;                            // active count
1193 <            if (!swept && (a = (int)(c >> AC_SHIFT)) <= 0)
1194 <                swept = scan(w, a);
1195 <            else if (tryAwaitWork(w, c))
1196 <                swept = false;
1188 >    final void deregisterWorker(ForkJoinWorkerThread wt, Throwable ex) {
1189 >        WorkQueue w = null;
1190 >        if (wt != null && (w = wt.workQueue) != null) {
1191 >            w.runState = -1;                // ensure runState is set
1192 >            stealCount.getAndAdd(w.totalSteals + w.nsteals);
1193 >            int idx = w.poolIndex;
1194 >            ReentrantLock lock = this.lock;
1195 >            lock.lock();
1196 >            try {                           // remove record from array
1197 >                WorkQueue[] ws = workQueues;
1198 >                if (ws != null && idx >= 0 && idx < ws.length && ws[idx] == w)
1199 >                    ws[nextPoolIndex = idx] = null;
1200 >            } finally {
1201 >                lock.unlock();
1202 >            }
1203 >        }
1204 >
1205 >        long c;                             // adjust ctl counts
1206 >        do {} while (!U.compareAndSwapLong
1207 >                     (this, CTL, c = ctl, (((c - AC_UNIT) & AC_MASK) |
1208 >                                           ((c - TC_UNIT) & TC_MASK) |
1209 >                                           (c & ~(AC_MASK|TC_MASK)))));
1210 >
1211 >        if (!tryTerminate(false) && w != null) {
1212 >            w.cancelAll();                  // cancel remaining tasks
1213 >            if (w.array != null)            // suppress signal if never ran
1214 >                signalWork();               // wake up or create replacement
1215          }
1216 +
1217 +        if (ex != null)                     // rethrow
1218 +            U.throwException(ex);
1219      }
1220  
1221 <    // Signalling
1221 >
1222 >    // Maintaining ctl counts
1223  
1224      /**
1225 <     * Wakes up or creates a worker.
1225 >     * Increments active count; mainly called upon return from blocking
1226 >     */
1227 >    final void incrementActiveCount() {
1228 >        long c;
1229 >        do {} while (!U.compareAndSwapLong(this, CTL, c = ctl, c + AC_UNIT));
1230 >    }
1231 >
1232 >    /**
1233 >     * Activates or creates a worker
1234       */
1235      final void signalWork() {
1236          /*
# Line 637 | Line 1246 | public class ForkJoinPool extends Abstra
1246           */
1247          long c; int e, u;
1248          while ((((e = (int)(c = ctl)) | (u = (int)(c >>> 32))) &
1249 <                (INT_SIGN|SHORT_SIGN)) == (INT_SIGN|SHORT_SIGN) && e >= 0) {
1250 <            if (e > 0) {                         // release a waiting worker
1251 <                int i; ForkJoinWorkerThread w; ForkJoinWorkerThread[] ws;
1252 <                if ((ws = workers) == null ||
1253 <                    (i = ~e & SMASK) >= ws.length ||
1254 <                    (w = ws[i]) == null)
1249 >                (INT_SIGN|SHORT_SIGN)) == (INT_SIGN|SHORT_SIGN)) {
1250 >            WorkQueue[] ws = workQueues; int i; WorkQueue w; Thread p;
1251 >            if (e == 0) {                    // add a new worker
1252 >                if (U.compareAndSwapLong
1253 >                    (this, CTL, c, (long)(((u + UTC_UNIT) & UTC_MASK) |
1254 >                                          ((u + UAC_UNIT) & UAC_MASK)) << 32)) {
1255 >                    addWorker();
1256                      break;
1257 <                long nc = (((long)(w.nextWait & E_MASK)) |
1258 <                           ((long)(u + UAC_UNIT) << 32));
1259 <                if (w.eventCount == e &&
1260 <                    UNSAFE.compareAndSwapLong(this, ctlOffset, c, nc)) {
1261 <                    w.eventCount = (e + EC_UNIT) & E_MASK;
1262 <                    if (w.parked)
1263 <                        UNSAFE.unpark(w);
1257 >                }
1258 >            }
1259 >            else if (e > 0 && ws != null &&
1260 >                     (i = ((~e << 1) | 1) & SMASK) < ws.length &&
1261 >                     (w = ws[i]) != null &&
1262 >                     w.eventCount == (e | INT_SIGN)) {
1263 >                if (U.compareAndSwapLong
1264 >                    (this, CTL, c, (((long)(w.nextWait & E_MASK)) |
1265 >                                    ((long)(u + UAC_UNIT) << 32)))) {
1266 >                    w.eventCount = (e + E_SEQ) & E_MASK;
1267 >                    if ((p = w.parker) != null)
1268 >                        U.unpark(p);         // release a waiting worker
1269                      break;
1270                  }
1271              }
1272 <            else if (UNSAFE.compareAndSwapLong
658 <                     (this, ctlOffset, c,
659 <                      (long)(((u + UTC_UNIT) & UTC_MASK) |
660 <                             ((u + UAC_UNIT) & UAC_MASK)) << 32)) {
661 <                addWorker();
1272 >            else
1273                  break;
663            }
1274          }
1275      }
1276  
1277      /**
1278 <     * Variant of signalWork to help release waiters on rescans.
1279 <     * Tries once to release a waiter if active count < 0.
1278 >     * Tries to decrement active count (sometimes implicitly) and
1279 >     * possibly release or create a compensating worker in preparation
1280 >     * for blocking. Fails on contention or termination.
1281       *
1282 <     * @return false if failed due to contention, else true
1282 >     * @return true if the caller can block, else should recheck and retry
1283       */
1284 <    private boolean tryReleaseWaiter() {
1285 <        long c; int e, i; ForkJoinWorkerThread w; ForkJoinWorkerThread[] ws;
1286 <        if ((e = (int)(c = ctl)) > 0 &&
1287 <            (int)(c >> AC_SHIFT) < 0 &&
677 <            (ws = workers) != null &&
678 <            (i = ~e & SMASK) < ws.length &&
679 <            (w = ws[i]) != null) {
680 <            long nc = ((long)(w.nextWait & E_MASK) |
681 <                       ((c + AC_UNIT) & (AC_MASK|TC_MASK)));
682 <            if (w.eventCount != e ||
683 <                !UNSAFE.compareAndSwapLong(this, ctlOffset, c, nc))
684 <                return false;
685 <            w.eventCount = (e + EC_UNIT) & E_MASK;
686 <            if (w.parked)
687 <                UNSAFE.unpark(w);
688 <        }
689 <        return true;
690 <    }
691 <
692 <    // Scanning for tasks
1284 >    final boolean tryCompensate() {
1285 >        WorkQueue[] ws; WorkQueue w; Thread p;
1286 >        int pc = parallelism, e, u, ac, tc, i;
1287 >        long c = ctl;
1288  
1289 <    /**
1290 <     * Scans for and, if found, executes one task. Scans start at a
1291 <     * random index of workers array, and randomly select the first
1292 <     * (2*#workers)-1 probes, and then, if all empty, resort to 2
1293 <     * circular sweeps, which is necessary to check quiescence. and
1294 <     * taking a submission only if no stealable tasks were found.  The
1295 <     * steal code inside the loop is a specialized form of
1296 <     * ForkJoinWorkerThread.deqTask, followed bookkeeping to support
1297 <     * helpJoinTask and signal propagation. The code for submission
1298 <     * queues is almost identical. On each steal, the worker completes
1299 <     * not only the task, but also all local tasks that this task may
1300 <     * have generated. On detecting staleness or contention when
1301 <     * trying to take a task, this method returns without finishing
707 <     * sweep, which allows global state rechecks before retry.
708 <     *
709 <     * @param w the worker
710 <     * @param a the number of active workers
711 <     * @return true if swept all queues without finding a task
712 <     */
713 <    private boolean scan(ForkJoinWorkerThread w, int a) {
714 <        int g = scanGuard; // mask 0 avoids useless scans if only one active
715 <        int m = (parallelism == 1 - a && blockedCount == 0) ? 0 : g & SMASK;
716 <        ForkJoinWorkerThread[] ws = workers;
717 <        if (ws == null || ws.length <= m)         // staleness check
718 <            return false;
719 <        for (int r = w.seed, k = r, j = -(m + m); j <= m + m; ++j) {
720 <            ForkJoinTask<?> t; ForkJoinTask<?>[] q; int b, i;
721 <            ForkJoinWorkerThread v = ws[k & m];
722 <            if (v != null && (b = v.queueBase) != v.queueTop &&
723 <                (q = v.queue) != null && (i = (q.length - 1) & b) >= 0) {
724 <                long u = (i << ASHIFT) + ABASE;
725 <                if ((t = q[i]) != null && v.queueBase == b &&
726 <                    UNSAFE.compareAndSwapObject(q, u, t, null)) {
727 <                    int d = (v.queueBase = b + 1) - v.queueTop;
728 <                    v.stealHint = w.poolIndex;
729 <                    if (d != 0)
730 <                        signalWork();             // propagate if nonempty
731 <                    w.execTask(t);
1289 >        if ((e = (int)c) >= 0) {
1290 >            if ((ac = ((u = (int)(c >>> 32)) >> UAC_SHIFT)) <= 0 &&
1291 >                e != 0 && (ws = workQueues) != null &&
1292 >                (i = ((~e << 1) | 1) & SMASK) < ws.length &&
1293 >                (w = ws[i]) != null) {
1294 >                if (w.eventCount == (e | INT_SIGN) &&
1295 >                    U.compareAndSwapLong
1296 >                    (this, CTL, c, ((long)(w.nextWait & E_MASK) |
1297 >                                    (c & (AC_MASK|TC_MASK))))) {
1298 >                    w.eventCount = (e + E_SEQ) & E_MASK;
1299 >                    if ((p = w.parker) != null)
1300 >                        U.unpark(p);
1301 >                    return true;             // release an idle worker
1302                  }
733                r ^= r << 13; r ^= r >>> 17; w.seed = r ^ (r << 5);
734                return false;                     // store next seed
1303              }
1304 <            else if (j < 0) {                     // xorshift
1305 <                r ^= r << 13; r ^= r >>> 17; k = r ^= r << 5;
1304 >            else if ((tc = (short)(u >>> UTC_SHIFT)) >= 0 && ac + pc > 1) {
1305 >                long nc = ((c - AC_UNIT) & AC_MASK) | (c & ~AC_MASK);
1306 >                if (U.compareAndSwapLong(this, CTL, c, nc))
1307 >                    return true;             // no compensation needed
1308 >            }
1309 >            else if (tc + pc < MAX_ID) {
1310 >                long nc = ((c + TC_UNIT) & TC_MASK) | (c & ~TC_MASK);
1311 >                if (U.compareAndSwapLong(this, CTL, c, nc)) {
1312 >                    addWorker();
1313 >                    return true;             // create replacement
1314 >                }
1315              }
739            else
740                ++k;
741        }
742        if (scanGuard != g)                       // staleness check
743            return false;
744        else {                                    // try to take submission
745            ForkJoinTask<?> t; ForkJoinTask<?>[] q; int b, i;
746            if ((b = queueBase) != queueTop &&
747                (q = submissionQueue) != null &&
748                (i = (q.length - 1) & b) >= 0) {
749                long u = (i << ASHIFT) + ABASE;
750                if ((t = q[i]) != null && queueBase == b &&
751                    UNSAFE.compareAndSwapObject(q, u, t, null)) {
752                    queueBase = b + 1;
753                    w.execTask(t);
754                }
755                return false;
756            }
757            return true;                         // all queues empty
1316          }
1317 +        return false;
1318      }
1319  
1320 +    // Submissions
1321 +
1322      /**
1323 <     * Tries to enqueue worker w in wait queue and await change in
1324 <     * worker's eventCount.  If the pool is quiescent and there is
1325 <     * more than one worker, possibly terminates worker upon exit.
1326 <     * Otherwise, before blocking, rescans queues to avoid missed
1327 <     * signals.  Upon finding work, releases at least one worker
1328 <     * (which may be the current worker). Rescans restart upon
768 <     * detected staleness or failure to release due to
769 <     * contention. Note the unusual conventions about Thread.interrupt
770 <     * here and elsewhere: Because interrupts are used solely to alert
771 <     * threads to check termination, which is checked here anyway, we
772 <     * clear status (using Thread.interrupted) before any call to
773 <     * park, so that park does not immediately return due to status
774 <     * being set via some other unrelated call to interrupt in user
775 <     * code.
776 <     *
777 <     * @param w the calling worker
778 <     * @param c the ctl value on entry
779 <     * @return true if waited or another thread was released upon enq
1323 >     * Unless shutting down, adds the given task to some submission
1324 >     * queue; using a randomly chosen queue index if the caller is a
1325 >     * ForkJoinWorkerThread, else one based on caller thread's hash
1326 >     * code. If no queue exists at the index, one is created.  If the
1327 >     * queue is busy, another is chosen by sweeping through the queues
1328 >     * array.
1329       */
1330 <    private boolean tryAwaitWork(ForkJoinWorkerThread w, long c) {
1331 <        int v = w.eventCount;
1332 <        w.nextWait = (int)c;                      // w's successor record
1333 <        long nc = (long)(v & E_MASK) | ((c - AC_UNIT) & (AC_MASK|TC_MASK));
1334 <        if (ctl != c || !UNSAFE.compareAndSwapLong(this, ctlOffset, c, nc)) {
1335 <            long d = ctl; // return true if lost to a deq, to force scan
1336 <            return (int)d != (int)c && ((d - c) & AC_MASK) >= 0L;
1337 <        }
1338 <        for (int sc = w.stealCount; sc != 0;) {   // accumulate stealCount
1339 <            long s = stealCount;
1340 <            if (UNSAFE.compareAndSwapLong(this, stealCountOffset, s, s + sc))
1341 <                sc = w.stealCount = 0;
1342 <            else if (w.eventCount != v)
1343 <                return true;                      // update next time
1344 <        }
1345 <        if ((!shutdown || !tryTerminate(false)) &&
1346 <            (int)c != 0 && parallelism + (int)(nc >> AC_SHIFT) == 0 &&
1347 <            blockedCount == 0 && quiescerCount == 0)
1348 <            idleAwaitWork(w, nc, c, v);           // quiescent
1349 <        for (boolean rescanned = false;;) {
1350 <            if (w.eventCount != v)
1351 <                return true;
1352 <            if (!rescanned) {
804 <                int g = scanGuard, m = g & SMASK;
805 <                ForkJoinWorkerThread[] ws = workers;
806 <                if (ws != null && m < ws.length) {
807 <                    rescanned = true;
808 <                    for (int i = 0; i <= m; ++i) {
809 <                        ForkJoinWorkerThread u = ws[i];
810 <                        if (u != null) {
811 <                            if (u.queueBase != u.queueTop &&
812 <                                !tryReleaseWaiter())
813 <                                rescanned = false; // contended
814 <                            if (w.eventCount != v)
815 <                                return true;
816 <                        }
1330 >    private void doSubmit(ForkJoinTask<?> task) {
1331 >        if (task == null)
1332 >            throw new NullPointerException();
1333 >        Thread t = Thread.currentThread();
1334 >        int r = ((t instanceof ForkJoinWorkerThread) ?
1335 >                 ((ForkJoinWorkerThread)t).workQueue.nextSeed() : hashThread(t));
1336 >        for (;;) {
1337 >            int rs = runState, m = rs & SMASK;
1338 >            int j = r &= (m & ~1);                      // even numbered queues
1339 >            WorkQueue[] ws = workQueues;
1340 >            if (rs < 0 || ws == null)
1341 >                throw new RejectedExecutionException(); // shutting down
1342 >            if (ws.length > m) {                        // consistency check
1343 >                for (WorkQueue q;;) {                   // circular sweep
1344 >                    if (((q = ws[j]) != null ||
1345 >                         (q = tryAddSharedQueue(j)) != null) &&
1346 >                        q.trySharedPush(task)) {
1347 >                        signalWork();
1348 >                        return;
1349 >                    }
1350 >                    if ((j = (j + 2) & m) == r) {
1351 >                        Thread.yield();                 // all queues busy
1352 >                        break;
1353                      }
1354                  }
819                if (scanGuard != g ||              // stale
820                    (queueBase != queueTop && !tryReleaseWaiter()))
821                    rescanned = false;
822                if (!rescanned)
823                    Thread.yield();                // reduce contention
824                else
825                    Thread.interrupted();          // clear before park
826            }
827            else {
828                w.parked = true;                   // must recheck
829                if (w.eventCount != v) {
830                    w.parked = false;
831                    return true;
832                }
833                LockSupport.park(this);
834                rescanned = w.parked = false;
1355              }
1356          }
1357      }
1358  
1359      /**
1360 <     * If inactivating worker w has caused pool to become
841 <     * quiescent, check for pool termination, and wait for event
842 <     * for up to SHRINK_RATE nanosecs (rescans are unnecessary in
843 <     * this case because quiescence reflects consensus about lack
844 <     * of work). On timeout, if ctl has not changed, terminate the
845 <     * worker. Upon its termination (see deregisterWorker), it may
846 <     * wake up another worker to possibly repeat this process.
1360 >     * Tries to add and register a new queue at the given index.
1361       *
1362 <     * @param w the calling worker
1363 <     * @param currentCtl the ctl value after enqueuing w
1364 <     * @param prevCtl the ctl value if w terminated
1365 <     * @param v the eventCount w awaits change
1366 <     */
1367 <    private void idleAwaitWork(ForkJoinWorkerThread w, long currentCtl,
1368 <                               long prevCtl, int v) {
1369 <        if (w.eventCount == v) {
1370 <            if (shutdown)
1371 <                tryTerminate(false);
1372 <            ForkJoinTask.helpExpungeStaleExceptions(); // help clean weak refs
1373 <            while (ctl == currentCtl) {
1374 <                long startTime = System.nanoTime();
1375 <                w.parked = true;
1376 <                if (w.eventCount == v)             // must recheck
1377 <                    LockSupport.parkNanos(this, SHRINK_RATE);
1378 <                w.parked = false;
1379 <                if (w.eventCount != v)
1380 <                    break;
1381 <                else if (System.nanoTime() - startTime <
1382 <                         SHRINK_RATE - (SHRINK_RATE / 10)) // timing slop
1383 <                    Thread.interrupted();          // spurious wakeup
1384 <                else if (UNSAFE.compareAndSwapLong(this, ctlOffset,
871 <                                                   currentCtl, prevCtl)) {
872 <                    w.terminate = true;            // restore previous
873 <                    w.eventCount = ((int)currentCtl + EC_UNIT) & E_MASK;
874 <                    break;
1362 >     * @param idx the workQueues array index to register the queue
1363 >     * @return the queue, or null if could not add because could
1364 >     * not acquire lock or idx is unusable
1365 >     */
1366 >    private WorkQueue tryAddSharedQueue(int idx) {
1367 >        WorkQueue q = null;
1368 >        ReentrantLock lock = this.lock;
1369 >        if (idx >= 0 && (idx & 1) == 0 && !lock.isLocked()) {
1370 >            // create queue outside of lock but only if apparently free
1371 >            WorkQueue nq = new WorkQueue(null, SHARED_QUEUE);
1372 >            if (lock.tryLock()) {
1373 >                try {
1374 >                    WorkQueue[] ws = workQueues;
1375 >                    if (ws != null && idx < ws.length) {
1376 >                        if ((q = ws[idx]) == null) {
1377 >                            int rs;         // update runState seq
1378 >                            ws[idx] = q = nq;
1379 >                            runState = (((rs = runState) & SHUTDOWN) |
1380 >                                        ((rs + RS_SEQ) & ~SHUTDOWN));
1381 >                        }
1382 >                    }
1383 >                } finally {
1384 >                    lock.unlock();
1385                  }
1386              }
1387          }
1388 +        return q;
1389      }
1390  
1391 <    // Submissions
1391 >    // Scanning for tasks
1392  
1393      /**
1394 <     * Enqueues the given task in the submissionQueue.  Same idea as
1395 <     * ForkJoinWorkerThread.pushTask except for use of submissionLock.
1396 <     *
1397 <     * @param t the task
1398 <     */
1399 <    private void addSubmission(ForkJoinTask<?> t) {
1400 <        final ReentrantLock lock = this.submissionLock;
1401 <        lock.lock();
1402 <        try {
1403 <            ForkJoinTask<?>[] q; int s, m;
1404 <            if ((q = submissionQueue) != null) {    // ignore if queue removed
1405 <                long u = (((s = queueTop) & (m = q.length-1)) << ASHIFT)+ABASE;
1406 <                UNSAFE.putOrderedObject(q, u, t);
1407 <                queueTop = s + 1;
1408 <                if (s - queueBase == m)
1409 <                    growSubmissionQueue();
1394 >     * Scans for and, if found, returns one task, else possibly
1395 >     * inactivates the worker. This method operates on single reads of
1396 >     * volatile state and is designed to be re-invoked continuously in
1397 >     * part because it returns upon detecting inconsistencies,
1398 >     * contention, or state changes that indicate possible success on
1399 >     * re-invocation.
1400 >     *
1401 >     * The scan searches for tasks across queues, randomly selecting
1402 >     * the first #queues probes, favoring steals 2:1 over submissions
1403 >     * (by exploiting even/odd indexing), and then performing a
1404 >     * circular sweep of all queues.  The scan terminates upon either
1405 >     * finding a non-empty queue, or completing a full sweep. If the
1406 >     * worker is not inactivated, it takes and returns a task from
1407 >     * this queue.  On failure to find a task, we take one of the
1408 >     * following actions, after which the caller will retry calling
1409 >     * this method unless terminated.
1410 >     *
1411 >     * * If not a complete sweep, try to release a waiting worker.  If
1412 >     * the scan terminated because the worker is inactivated, then the
1413 >     * released worker will often be the calling worker, and it can
1414 >     * succeed obtaining a task on the next call. Or maybe it is
1415 >     * another worker, but with same net effect. Releasing in other
1416 >     * cases as well ensures that we have enough workers running.
1417 >     *
1418 >     * * If the caller has run a task since the the last empty scan,
1419 >     * return (to allow rescan) if other workers are not also yet
1420 >     * enqueued.  Field WorkQueue.rescans counts down on each scan to
1421 >     * ensure eventual inactivation, and occasional calls to
1422 >     * Thread.yield to help avoid interference with more useful
1423 >     * activities on the system.
1424 >     *
1425 >     * * If pool is terminating, terminate the worker
1426 >     *
1427 >     * * If not already enqueued, try to inactivate and enqueue the
1428 >     * worker on wait queue.
1429 >     *
1430 >     * * If already enqueued and none of the above apply, either park
1431 >     * awaiting signal, or if this is the most recent waiter and pool
1432 >     * is quiescent, relay to idleAwaitWork to check for termination
1433 >     * and possibly shrink pool.
1434 >     *
1435 >     * @param w the worker (via its WorkQueue)
1436 >     * @return a task or null of none found
1437 >     */
1438 >    private final ForkJoinTask<?> scan(WorkQueue w) {
1439 >        boolean swept = false;                 // true after full empty scan
1440 >        WorkQueue[] ws;                        // volatile read order matters
1441 >        int r = w.seed, ec = w.eventCount;     // ec is negative if inactive
1442 >        int rs = runState, m = rs & SMASK;
1443 >        if ((ws = workQueues) != null && ws.length > m) {
1444 >            ForkJoinTask<?> task = null;
1445 >            for (int k = 0, j = -2 - m; ; ++j) {
1446 >                WorkQueue q; int b;
1447 >                if (j < 0) {                    // random probes while j negative
1448 >                    r ^= r << 13; r ^= r >>> 17; k = (r ^= r << 5) | (j & 1);
1449 >                }                               // worker (not submit) for odd j
1450 >                else                            // cyclic scan when j >= 0
1451 >                    k += (m >>> 1) | 1;         // step by half to reduce bias
1452 >
1453 >                if ((q = ws[k & m]) != null && (b = q.base) - q.top < 0) {
1454 >                    if (ec >= 0)
1455 >                        task = q.pollAt(b);     // steal
1456 >                    break;
1457 >                }
1458 >                else if (j > m) {
1459 >                    if (rs == runState)        // staleness check
1460 >                        swept = true;
1461 >                    break;
1462 >                }
1463 >            }
1464 >            w.seed = r;                        // save seed for next scan
1465 >            if (task != null)
1466 >                return task;
1467 >        }
1468 >
1469 >        // Decode ctl on empty scan
1470 >        long c = ctl; int e = (int)c, a = (int)(c >> AC_SHIFT), nr, ns;
1471 >        if (!swept) {                          // try to release a waiter
1472 >            WorkQueue v; Thread p;
1473 >            if (e > 0 && a < 0 && ws != null &&
1474 >                (v = ws[((~e << 1) | 1) & m]) != null &&
1475 >                v.eventCount == (e | INT_SIGN) && U.compareAndSwapLong
1476 >                (this, CTL, c, ((long)(v.nextWait & E_MASK) |
1477 >                                ((c + AC_UNIT) & (AC_MASK|TC_MASK))))) {
1478 >                v.eventCount = (e + E_SEQ) & E_MASK;
1479 >                if ((p = v.parker) != null)
1480 >                    U.unpark(p);
1481 >            }
1482 >        }
1483 >        else if ((nr = w.rescans) > 0) {       // continue rescanning
1484 >            int ac = a + parallelism;
1485 >            if ((w.rescans = (ac < nr) ? ac : nr - 1) > 0 && w.seed < 0 &&
1486 >                w.eventCount == ec)
1487 >                Thread.yield();                // 1 bit randomness for yield call
1488 >        }
1489 >        else if (e < 0)                        // pool is terminating
1490 >            w.runState = -1;
1491 >        else if (ec >= 0) {                    // try to enqueue
1492 >            long nc = (long)ec | ((c - AC_UNIT) & (AC_MASK|TC_MASK));
1493 >            w.nextWait = e;
1494 >            w.eventCount = ec | INT_SIGN;      // mark as inactive
1495 >            if (!U.compareAndSwapLong(this, CTL, c, nc))
1496 >                w.eventCount = ec;             // back out on CAS failure
1497 >            else if ((ns = w.nsteals) != 0) {  // set rescans if ran task
1498 >                if (a <= 0)                    // ... unless too many active
1499 >                    w.rescans = a + parallelism;
1500 >                w.nsteals = 0;
1501 >                w.totalSteals += ns;
1502 >            }
1503 >        }
1504 >        else{                                  // already queued
1505 >            if (parallelism == -a)
1506 >                idleAwaitWork(w);              // quiescent
1507 >            if (w.eventCount == ec) {
1508 >                Thread.interrupted();          // clear status
1509 >                ForkJoinWorkerThread wt = w.owner;
1510 >                U.putObject(wt, PARKBLOCKER, this);
1511 >                w.parker = wt;                 // emulate LockSupport.park
1512 >                if (w.eventCount == ec)        // recheck
1513 >                    U.park(false, 0L);         // block
1514 >                w.parker = null;
1515 >                U.putObject(wt, PARKBLOCKER, null);
1516              }
900        } finally {
901            lock.unlock();
1517          }
1518 <        signalWork();
1518 >        return null;
1519      }
1520  
906    //  (pollSubmission is defined below with exported methods)
907
1521      /**
1522 <     * Creates or doubles submissionQueue array.
1523 <     * Basically identical to ForkJoinWorkerThread version.
1522 >     * If inactivating worker w has caused pool to become quiescent,
1523 >     * check for pool termination, and, so long as this is not the
1524 >     * only worker, wait for event for up to SHRINK_RATE nanosecs On
1525 >     * timeout, if ctl has not changed, terminate the worker, which
1526 >     * will in turn wake up another worker to possibly repeat this
1527 >     * process.
1528 >     *
1529 >     * @param w the calling worker
1530       */
1531 <    private void growSubmissionQueue() {
1532 <        ForkJoinTask<?>[] oldQ = submissionQueue;
1533 <        int size = oldQ != null ? oldQ.length << 1 : INITIAL_QUEUE_CAPACITY;
1534 <        if (size > MAXIMUM_QUEUE_CAPACITY)
1535 <            throw new RejectedExecutionException("Queue capacity exceeded");
1536 <        if (size < INITIAL_QUEUE_CAPACITY)
1537 <            size = INITIAL_QUEUE_CAPACITY;
1538 <        ForkJoinTask<?>[] q = submissionQueue = new ForkJoinTask<?>[size];
1539 <        int mask = size - 1;
1540 <        int top = queueTop;
1541 <        int oldMask;
1542 <        if (oldQ != null && (oldMask = oldQ.length - 1) >= 0) {
1543 <            for (int b = queueBase; b != top; ++b) {
1544 <                long u = ((b & oldMask) << ASHIFT) + ABASE;
1545 <                Object x = UNSAFE.getObjectVolatile(oldQ, u);
1546 <                if (x != null && UNSAFE.compareAndSwapObject(oldQ, u, x, null))
1547 <                    UNSAFE.putObjectVolatile
1548 <                        (q, ((b & mask) << ASHIFT) + ABASE, x);
1531 >    private void idleAwaitWork(WorkQueue w) {
1532 >        long c; int nw, ec;
1533 >        if (!tryTerminate(false) &&
1534 >            (int)((c = ctl) >> AC_SHIFT) + parallelism == 0 &&
1535 >            (ec = w.eventCount) == ((int)c | INT_SIGN) &&
1536 >            (nw = w.nextWait) != 0) {
1537 >            long nc = ((long)(nw & E_MASK) | // ctl to restore on timeout
1538 >                       ((c + AC_UNIT) & AC_MASK) | (c & TC_MASK));
1539 >            ForkJoinTask.helpExpungeStaleExceptions(); // help clean
1540 >            ForkJoinWorkerThread wt = w.owner;
1541 >            while (ctl == c) {
1542 >                long startTime = System.nanoTime();
1543 >                Thread.interrupted();  // timed variant of version in scan()
1544 >                U.putObject(wt, PARKBLOCKER, this);
1545 >                w.parker = wt;
1546 >                if (ctl == c)
1547 >                    U.park(false, SHRINK_RATE);
1548 >                w.parker = null;
1549 >                U.putObject(wt, PARKBLOCKER, null);
1550 >                if (ctl != c)
1551 >                    break;
1552 >                if (System.nanoTime() - startTime >= SHRINK_TIMEOUT &&
1553 >                    U.compareAndSwapLong(this, CTL, c, nc)) {
1554 >                    w.runState = -1;          // shrink
1555 >                    w.eventCount = (ec + E_SEQ) | E_MASK;
1556 >                    break;
1557 >                }
1558              }
1559          }
1560      }
1561  
934    // Blocking support
935
1562      /**
1563 <     * Tries to increment blockedCount, decrement active count
1564 <     * (sometimes implicitly) and possibly release or create a
1565 <     * compensating worker in preparation for blocking. Fails
1566 <     * on contention or termination.
1567 <     *
1568 <     * @return true if the caller can block, else should recheck and retry
1569 <     */
1570 <    private boolean tryPreBlock() {
1571 <        int b = blockedCount;
1572 <        if (UNSAFE.compareAndSwapInt(this, blockedCountOffset, b, b + 1)) {
1573 <            int pc = parallelism;
1574 <            do {
1575 <                ForkJoinWorkerThread[] ws; ForkJoinWorkerThread w;
1576 <                int e, ac, tc, i;
1577 <                long c = ctl;
1578 <                int u = (int)(c >>> 32);
1579 <                if ((e = (int)c) < 0) {
1580 <                                                 // skip -- terminating
1581 <                }
1582 <                else if ((ac = (u >> UAC_SHIFT)) <= 0 && e != 0 &&
1583 <                         (ws = workers) != null &&
1584 <                         (i = ~e & SMASK) < ws.length &&
1585 <                         (w = ws[i]) != null) {
1586 <                    long nc = ((long)(w.nextWait & E_MASK) |
1587 <                               (c & (AC_MASK|TC_MASK)));
1588 <                    if (w.eventCount == e &&
1589 <                        UNSAFE.compareAndSwapLong(this, ctlOffset, c, nc)) {
1590 <                        w.eventCount = (e + EC_UNIT) & E_MASK;
1591 <                        if (w.parked)
1592 <                            UNSAFE.unpark(w);
1593 <                        return true;             // release an idle worker
1563 >     * Tries to locate and execute tasks for a stealer of the given
1564 >     * task, or in turn one of its stealers, Traces currentSteal ->
1565 >     * currentJoin links looking for a thread working on a descendant
1566 >     * of the given task and with a non-empty queue to steal back and
1567 >     * execute tasks from. The first call to this method upon a
1568 >     * waiting join will often entail scanning/search, (which is OK
1569 >     * because the joiner has nothing better to do), but this method
1570 >     * leaves hints in workers to speed up subsequent calls. The
1571 >     * implementation is very branchy to cope with potential
1572 >     * inconsistencies or loops encountering chains that are stale,
1573 >     * unknown, or of length greater than MAX_HELP_DEPTH links.  All
1574 >     * of these cases are dealt with by just retrying by caller.
1575 >     *
1576 >     * @param joiner the joining worker
1577 >     * @param task the task to join
1578 >     * @return true if found or ran a task (and so is immediately retryable)
1579 >     */
1580 >    final boolean tryHelpStealer(WorkQueue joiner, ForkJoinTask<?> task) {
1581 >        ForkJoinTask<?> subtask;    // current target
1582 >        boolean progress = false;
1583 >        int depth = 0;              // current chain depth
1584 >        int m = runState & SMASK;
1585 >        WorkQueue[] ws = workQueues;
1586 >
1587 >        if (ws != null && ws.length > m && (subtask = task).status >= 0) {
1588 >            outer:for (WorkQueue j = joiner;;) {
1589 >                // Try to find the stealer of subtask, by first using hint
1590 >                WorkQueue stealer = null;
1591 >                WorkQueue v = ws[j.stealHint & m];
1592 >                if (v != null && v.currentSteal == subtask)
1593 >                    stealer = v;
1594 >                else {
1595 >                    for (int i = 1; i <= m; i += 2) {
1596 >                        if ((v = ws[i]) != null && v.currentSteal == subtask) {
1597 >                            stealer = v;
1598 >                            j.stealHint = i; // save hint
1599 >                            break;
1600 >                        }
1601                      }
1602 +                    if (stealer == null)
1603 +                        break;
1604                  }
1605 <                else if ((tc = (short)(u >>> UTC_SHIFT)) >= 0 && ac + pc > 1) {
1606 <                    long nc = ((c - AC_UNIT) & AC_MASK) | (c & ~AC_MASK);
1607 <                    if (UNSAFE.compareAndSwapLong(this, ctlOffset, c, nc))
1608 <                        return true;             // no compensation needed
1609 <                }
1610 <                else if (tc + pc < MAX_ID) {
1611 <                    long nc = ((c + TC_UNIT) & TC_MASK) | (c & ~TC_MASK);
1612 <                    if (UNSAFE.compareAndSwapLong(this, ctlOffset, c, nc)) {
1613 <                        addWorker();
1614 <                        return true;            // create a replacement
1605 >
1606 >                for (WorkQueue q = stealer;;) { // Try to help stealer
1607 >                    ForkJoinTask<?> t; int b;
1608 >                    if (task.status < 0)
1609 >                        break outer;
1610 >                    if ((b = q.base) - q.top < 0) {
1611 >                        progress = true;
1612 >                        if (subtask.status < 0)
1613 >                            break outer;               // stale
1614 >                        if ((t = q.pollAt(b)) != null) {
1615 >                            stealer.stealHint = joiner.poolIndex;
1616 >                            joiner.runSubtask(t);
1617 >                        }
1618 >                    }
1619 >                    else { // empty - try to descend to find stealer's stealer
1620 >                        ForkJoinTask<?> next = stealer.currentJoin;
1621 >                        if (++depth == MAX_HELP_DEPTH || subtask.status < 0 ||
1622 >                            next == null || next == subtask)
1623 >                            break outer;  // max depth, stale, dead-end, cyclic
1624 >                        subtask = next;
1625 >                        j = stealer;
1626 >                        break;
1627                      }
1628                  }
1629 <                // try to back out on any failure and let caller retry
983 <            } while (!UNSAFE.compareAndSwapInt(this, blockedCountOffset,
984 <                                               b = blockedCount, b - 1));
1629 >            }
1630          }
1631 <        return false;
1631 >        return progress;
1632      }
1633  
1634      /**
1635 <     * Decrements blockedCount and increments active count.
991 <     */
992 <    private void postBlock() {
993 <        long c;
994 <        do {} while (!UNSAFE.compareAndSwapLong(this, ctlOffset,  // no mask
995 <                                                c = ctl, c + AC_UNIT));
996 <        int b;
997 <        do {} while (!UNSAFE.compareAndSwapInt(this, blockedCountOffset,
998 <                                               b = blockedCount, b - 1));
999 <    }
1000 <
1001 <    /**
1002 <     * Possibly blocks waiting for the given task to complete, or
1003 <     * cancels the task if terminating.  Fails to wait if contended.
1635 >     * If task is at base of some steal queue, steals and executes it.
1636       *
1637 <     * @param joinMe the task
1637 >     * @param joiner the joining worker
1638 >     * @param task the task
1639       */
1640 <    final void tryAwaitJoin(ForkJoinTask<?> joinMe) {
1641 <        Thread.interrupted(); // clear interrupts before checking termination
1642 <        if (joinMe.status >= 0) {
1643 <            if (tryPreBlock()) {
1644 <                joinMe.tryAwaitDone(0L);
1645 <                postBlock();
1640 >    final void tryPollForAndExec(WorkQueue joiner, ForkJoinTask<?> task) {
1641 >        WorkQueue[] ws;
1642 >        int m = runState & SMASK;
1643 >        if ((ws = workQueues) != null && ws.length > m) {
1644 >            for (int j = 1; j <= m && task.status >= 0; j += 2) {
1645 >                WorkQueue q = ws[j];
1646 >                if (q != null && q.pollFor(task)) {
1647 >                    joiner.runSubtask(task);
1648 >                    break;
1649 >                }
1650              }
1014            else if ((ctl & STOP_BIT) != 0L)
1015                joinMe.cancelIgnoringExceptions();
1651          }
1652      }
1653  
1654      /**
1655 <     * Possibly blocks the given worker waiting for joinMe to
1656 <     * complete or timeout.
1657 <     *
1658 <     * @param joinMe the task
1659 <     * @param millis the wait time for underlying Object.wait
1660 <     */
1661 <    final void timedAwaitJoin(ForkJoinTask<?> joinMe, long nanos) {
1662 <        while (joinMe.status >= 0) {
1663 <            Thread.interrupted();
1664 <            if ((ctl & STOP_BIT) != 0L) {
1665 <                joinMe.cancelIgnoringExceptions();
1666 <                break;
1667 <            }
1668 <            if (tryPreBlock()) {
1669 <                long last = System.nanoTime();
1670 <                while (joinMe.status >= 0) {
1671 <                    long millis = TimeUnit.NANOSECONDS.toMillis(nanos);
1037 <                    if (millis <= 0)
1038 <                        break;
1039 <                    joinMe.tryAwaitDone(millis);
1040 <                    if (joinMe.status < 0)
1041 <                        break;
1042 <                    if ((ctl & STOP_BIT) != 0L) {
1043 <                        joinMe.cancelIgnoringExceptions();
1044 <                        break;
1655 >     * Returns a non-empty steal queue, if one is found during a random,
1656 >     * then cyclic scan, else null.  This method must be retried by
1657 >     * caller if, by the time it tries to use the queue, it is empty.
1658 >     */
1659 >    private WorkQueue findNonEmptyStealQueue(WorkQueue w) {
1660 >        int r = w.seed;    // Same idea as scan(), but ignoring submissions
1661 >        for (WorkQueue[] ws;;) {
1662 >            int m = runState & SMASK;
1663 >            if ((ws = workQueues) == null)
1664 >                return null;
1665 >            if (ws.length > m) {
1666 >                WorkQueue q;
1667 >                for (int n = m << 2, k = r, j = -n;;) {
1668 >                    r ^= r << 13; r ^= r >>> 17; r ^= r << 5;
1669 >                    if ((q = ws[(k | 1) & m]) != null && q.base - q.top < 0) {
1670 >                        w.seed = r;
1671 >                        return q;
1672                      }
1673 <                    long now = System.nanoTime();
1674 <                    nanos -= now - last;
1675 <                    last = now;
1673 >                    else if (j > n)
1674 >                        return null;
1675 >                    else
1676 >                        k = (j++ < 0) ? r : k + ((m >>> 1) | 1);
1677 >
1678                  }
1050                postBlock();
1051                break;
1679              }
1680          }
1681      }
1682  
1683      /**
1684 <     * If necessary, compensates for blocker, and blocks.
1685 <     */
1686 <    private void awaitBlocker(ManagedBlocker blocker)
1687 <        throws InterruptedException {
1688 <        while (!blocker.isReleasable()) {
1689 <            if (tryPreBlock()) {
1690 <                try {
1691 <                    do {} while (!blocker.isReleasable() && !blocker.block());
1692 <                } finally {
1693 <                    postBlock();
1684 >     * Runs tasks until {@code isQuiescent()}. We piggyback on
1685 >     * active count ctl maintenance, but rather than blocking
1686 >     * when tasks cannot be found, we rescan until all others cannot
1687 >     * find tasks either.
1688 >     */
1689 >    final void helpQuiescePool(WorkQueue w) {
1690 >        for (boolean active = true;;) {
1691 >            w.runLocalTasks();      // exhaust local queue
1692 >            WorkQueue q = findNonEmptyStealQueue(w);
1693 >            if (q != null) {
1694 >                ForkJoinTask<?> t;
1695 >                if (!active) {      // re-establish active count
1696 >                    long c;
1697 >                    active = true;
1698 >                    do {} while (!U.compareAndSwapLong
1699 >                                 (this, CTL, c = ctl, c + AC_UNIT));
1700 >                }
1701 >                if ((t = q.poll()) != null)
1702 >                    w.runSubtask(t);
1703 >            }
1704 >            else {
1705 >                long c;
1706 >                if (active) {       // decrement active count without queuing
1707 >                    active = false;
1708 >                    do {} while (!U.compareAndSwapLong
1709 >                                 (this, CTL, c = ctl, c -= AC_UNIT));
1710 >                }
1711 >                else
1712 >                    c = ctl;        // re-increment on exit
1713 >                if ((int)(c >> AC_SHIFT) + parallelism == 0) {
1714 >                    do {} while (!U.compareAndSwapLong
1715 >                                 (this, CTL, c = ctl, c + AC_UNIT));
1716 >                    break;
1717                  }
1068                break;
1718              }
1719          }
1720      }
1721  
1073    // Creating, registering and deregistring workers
1074
1722      /**
1723 <     * Tries to create and start a worker; minimally rolls back counts
1724 <     * on failure.
1723 >     * Gets and removes a local or stolen task for the given worker
1724 >     *
1725 >     * @return a task, if available
1726       */
1727 <    private void addWorker() {
1728 <        Throwable ex = null;
1729 <        ForkJoinWorkerThread t = null;
1730 <        try {
1731 <            t = factory.newThread(this);
1732 <        } catch (Throwable e) {
1733 <            ex = e;
1734 <        }
1735 <        if (t == null) {  // null or exceptional factory return
1088 <            long c;       // adjust counts
1089 <            do {} while (!UNSAFE.compareAndSwapLong
1090 <                         (this, ctlOffset, c = ctl,
1091 <                          (((c - AC_UNIT) & AC_MASK) |
1092 <                           ((c - TC_UNIT) & TC_MASK) |
1093 <                           (c & ~(AC_MASK|TC_MASK)))));
1094 <            // Propagate exception if originating from an external caller
1095 <            if (!tryTerminate(false) && ex != null &&
1096 <                !(Thread.currentThread() instanceof ForkJoinWorkerThread))
1097 <                UNSAFE.throwException(ex);
1727 >    final ForkJoinTask<?> nextTaskFor(WorkQueue w) {
1728 >        for (ForkJoinTask<?> t;;) {
1729 >            WorkQueue q;
1730 >            if ((t = w.nextLocalTask()) != null)
1731 >                return t;
1732 >            if ((q = findNonEmptyStealQueue(w)) == null)
1733 >                return null;
1734 >            if ((t = q.poll()) != null)
1735 >                return t;
1736          }
1099        else
1100            t.start();
1737      }
1738  
1739      /**
1740 <     * Callback from ForkJoinWorkerThread constructor to assign a
1741 <     * public name
1740 >     * Returns the approximate (non-atomic) number of idle threads per
1741 >     * active thread to offset steal queue size for method
1742 >     * ForkJoinTask.getSurplusQueuedTaskCount().
1743       */
1744 <    final String nextWorkerName() {
1745 <        for (int n;;) {
1746 <            if (UNSAFE.compareAndSwapInt(this, nextWorkerNumberOffset,
1747 <                                         n = nextWorkerNumber, ++n))
1748 <                return workerNamePrefix + n;
1749 <        }
1744 >    final int idlePerActive() {
1745 >        // Approximate at powers of two for small values, saturate past 4
1746 >        int p = parallelism;
1747 >        int a = p + (int)(ctl >> AC_SHIFT);
1748 >        return (a > (p >>>= 1) ? 0 :
1749 >                a > (p >>>= 1) ? 1 :
1750 >                a > (p >>>= 1) ? 2 :
1751 >                a > (p >>>= 1) ? 4 :
1752 >                8);
1753      }
1754  
1755 <    /**
1116 <     * Callback from ForkJoinWorkerThread constructor to
1117 <     * determine its poolIndex and record in workers array.
1118 <     *
1119 <     * @param w the worker
1120 <     * @return the worker's pool index
1121 <     */
1122 <    final int registerWorker(ForkJoinWorkerThread w) {
1123 <        /*
1124 <         * In the typical case, a new worker acquires the lock, uses
1125 <         * next available index and returns quickly.  Since we should
1126 <         * not block callers (ultimately from signalWork or
1127 <         * tryPreBlock) waiting for the lock needed to do this, we
1128 <         * instead help release other workers while waiting for the
1129 <         * lock.
1130 <         */
1131 <        for (int g;;) {
1132 <            ForkJoinWorkerThread[] ws;
1133 <            if (((g = scanGuard) & SG_UNIT) == 0 &&
1134 <                UNSAFE.compareAndSwapInt(this, scanGuardOffset,
1135 <                                         g, g | SG_UNIT)) {
1136 <                int k = nextWorkerIndex;
1137 <                try {
1138 <                    if ((ws = workers) != null) { // ignore on shutdown
1139 <                        int n = ws.length;
1140 <                        if (k < 0 || k >= n || ws[k] != null) {
1141 <                            for (k = 0; k < n && ws[k] != null; ++k)
1142 <                                ;
1143 <                            if (k == n)
1144 <                                ws = workers = Arrays.copyOf(ws, n << 1);
1145 <                        }
1146 <                        ws[k] = w;
1147 <                        nextWorkerIndex = k + 1;
1148 <                        int m = g & SMASK;
1149 <                        g = (k > m) ? ((m << 1) + 1) & SMASK : g + (SG_UNIT<<1);
1150 <                    }
1151 <                } finally {
1152 <                    scanGuard = g;
1153 <                }
1154 <                return k;
1155 <            }
1156 <            else if ((ws = workers) != null) { // help release others
1157 <                for (ForkJoinWorkerThread u : ws) {
1158 <                    if (u != null && u.queueBase != u.queueTop) {
1159 <                        if (tryReleaseWaiter())
1160 <                            break;
1161 <                    }
1162 <                }
1163 <            }
1164 <        }
1165 <    }
1755 >    // Termination
1756  
1757      /**
1758 <     * Final callback from terminating worker.  Removes record of
1169 <     * worker from array, and adjusts counts. If pool is shutting
1170 <     * down, tries to complete termination.
1171 <     *
1172 <     * @param w the worker
1758 >     * Sets SHUTDOWN bit of runState under lock
1759       */
1760 <    final void deregisterWorker(ForkJoinWorkerThread w, Throwable ex) {
1761 <        int idx = w.poolIndex;
1762 <        int sc = w.stealCount;
1763 <        int steps = 0;
1764 <        // Remove from array, adjust worker counts and collect steal count.
1765 <        // We can intermix failed removes or adjusts with steal updates
1180 <        do {
1181 <            long s, c;
1182 <            int g;
1183 <            if (steps == 0 && ((g = scanGuard) & SG_UNIT) == 0 &&
1184 <                UNSAFE.compareAndSwapInt(this, scanGuardOffset,
1185 <                                         g, g |= SG_UNIT)) {
1186 <                ForkJoinWorkerThread[] ws = workers;
1187 <                if (ws != null && idx >= 0 &&
1188 <                    idx < ws.length && ws[idx] == w)
1189 <                    ws[idx] = null;    // verify
1190 <                nextWorkerIndex = idx;
1191 <                scanGuard = g + SG_UNIT;
1192 <                steps = 1;
1193 <            }
1194 <            if (steps == 1 &&
1195 <                UNSAFE.compareAndSwapLong(this, ctlOffset, c = ctl,
1196 <                                          (((c - AC_UNIT) & AC_MASK) |
1197 <                                           ((c - TC_UNIT) & TC_MASK) |
1198 <                                           (c & ~(AC_MASK|TC_MASK)))))
1199 <                steps = 2;
1200 <            if (sc != 0 &&
1201 <                UNSAFE.compareAndSwapLong(this, stealCountOffset,
1202 <                                          s = stealCount, s + sc))
1203 <                sc = 0;
1204 <        } while (steps != 2 || sc != 0);
1205 <        if (!tryTerminate(false)) {
1206 <            if (ex != null)   // possibly replace if died abnormally
1207 <                signalWork();
1208 <            else
1209 <                tryReleaseWaiter();
1760 >    private void enableShutdown() {
1761 >        ReentrantLock lock = this.lock;
1762 >        if (runState >= 0) {
1763 >            lock.lock();                       // don't need try/finally
1764 >            runState |= SHUTDOWN;
1765 >            lock.unlock();
1766          }
1767      }
1768  
1213    // Shutdown and termination
1214
1769      /**
1770 <     * Possibly initiates and/or completes termination.
1770 >     * Possibly initiates and/or completes termination.  Upon
1771 >     * termination, cancels all queued tasks and then
1772       *
1773       * @param now if true, unconditionally terminate, else only
1774 <     * if shutdown and empty queue and no active workers
1774 >     * if no work and no active workers
1775       * @return true if now terminating or terminated
1776       */
1777      private boolean tryTerminate(boolean now) {
1778 <        long c;
1779 <        while (((c = ctl) & STOP_BIT) == 0) {
1778 >        for (long c;;) {
1779 >            if (((c = ctl) & STOP_BIT) != 0) {      // already terminating
1780 >                if ((short)(c >>> TC_SHIFT) == -parallelism) {
1781 >                    ReentrantLock lock = this.lock; // signal when no workers
1782 >                    lock.lock();                    // don't need try/finally
1783 >                    termination.signalAll();        // signal when 0 workers
1784 >                    lock.unlock();
1785 >                }
1786 >                return true;
1787 >            }
1788              if (!now) {
1789 <                if ((int)(c >> AC_SHIFT) != -parallelism)
1789 >                if ((int)(c >> AC_SHIFT) != -parallelism || runState >= 0 ||
1790 >                    hasQueuedSubmissions())
1791                      return false;
1792 <                if (!shutdown || blockedCount != 0 || quiescerCount != 0 ||
1793 <                    queueBase != queueTop) {
1794 <                    if (ctl == c) // staleness check
1795 <                        return false;
1796 <                    continue;
1792 >                // Check for unqueued inactive workers. One pass suffices.
1793 >                WorkQueue[] ws = workQueues; WorkQueue w;
1794 >                if (ws != null) {
1795 >                    int n = ws.length;
1796 >                    for (int i = 1; i < n; i += 2) {
1797 >                        if ((w = ws[i]) != null && w.eventCount >= 0)
1798 >                            return false;
1799 >                    }
1800                  }
1801              }
1802 <            if (UNSAFE.compareAndSwapLong(this, ctlOffset, c, c | STOP_BIT))
1802 >            if (U.compareAndSwapLong(this, CTL, c, c | STOP_BIT))
1803                  startTerminating();
1804          }
1238        if ((short)(c >>> TC_SHIFT) == -parallelism) { // signal when 0 workers
1239            final ReentrantLock lock = this.submissionLock;
1240            lock.lock();
1241            try {
1242                termination.signalAll();
1243            } finally {
1244                lock.unlock();
1245            }
1246        }
1247        return true;
1805      }
1806  
1807      /**
1808 <     * Runs up to three passes through workers: (0) Setting
1809 <     * termination status for each worker, followed by wakeups up to
1810 <     * queued workers; (1) helping cancel tasks; (2) interrupting
1811 <     * lagging threads (likely in external tasks, but possibly also
1812 <     * blocked in joins).  Each pass repeats previous steps because of
1813 <     * potential lagging thread creation.
1808 >     * Initiates termination: Runs three passes through workQueues:
1809 >     * (0) Setting termination status, followed by wakeups of queued
1810 >     * workers; (1) cancelling all tasks; (2) interrupting lagging
1811 >     * threads (likely in external tasks, but possibly also blocked in
1812 >     * joins).  Each pass repeats previous steps because of potential
1813 >     * lagging thread creation.
1814       */
1815      private void startTerminating() {
1259        cancelSubmissions();
1816          for (int pass = 0; pass < 3; ++pass) {
1817 <            ForkJoinWorkerThread[] ws = workers;
1817 >            WorkQueue[] ws = workQueues;
1818              if (ws != null) {
1819 <                for (ForkJoinWorkerThread w : ws) {
1820 <                    if (w != null) {
1821 <                        w.terminate = true;
1819 >                WorkQueue w; Thread wt;
1820 >                int n = ws.length;
1821 >                for (int j = 0; j < n; ++j) {
1822 >                    if ((w = ws[j]) != null) {
1823 >                        w.runState = -1;
1824                          if (pass > 0) {
1825 <                            w.cancelTasks();
1826 <                            if (pass > 1 && !w.isInterrupted()) {
1825 >                            w.cancelAll();
1826 >                            if (pass > 1 && (wt = w.owner) != null &&
1827 >                                !wt.isInterrupted()) {
1828                                  try {
1829 <                                    w.interrupt();
1829 >                                    wt.interrupt();
1830                                  } catch (SecurityException ignore) {
1831                                  }
1832                              }
1833                          }
1834                      }
1835                  }
1836 <                terminateWaiters();
1837 <            }
1838 <        }
1839 <    }
1840 <
1841 <    /**
1842 <     * Polls and cancels all submissions. Called only during termination.
1843 <     */
1844 <    private void cancelSubmissions() {
1845 <        while (queueBase != queueTop) {
1846 <            ForkJoinTask<?> task = pollSubmission();
1847 <            if (task != null) {
1848 <                try {
1290 <                    task.cancel(false);
1291 <                } catch (Throwable ignore) {
1292 <                }
1293 <            }
1294 <        }
1295 <    }
1296 <
1297 <    /**
1298 <     * Tries to set the termination status of waiting workers, and
1299 <     * then wakes them up (after which they will terminate).
1300 <     */
1301 <    private void terminateWaiters() {
1302 <        ForkJoinWorkerThread[] ws = workers;
1303 <        if (ws != null) {
1304 <            ForkJoinWorkerThread w; long c; int i, e;
1305 <            int n = ws.length;
1306 <            while ((i = ~(e = (int)(c = ctl)) & SMASK) < n &&
1307 <                   (w = ws[i]) != null && w.eventCount == (e & E_MASK)) {
1308 <                if (UNSAFE.compareAndSwapLong(this, ctlOffset, c,
1309 <                                              (long)(w.nextWait & E_MASK) |
1310 <                                              ((c + AC_UNIT) & AC_MASK) |
1311 <                                              (c & (TC_MASK|STOP_BIT)))) {
1312 <                    w.terminate = true;
1313 <                    w.eventCount = e + EC_UNIT;
1314 <                    if (w.parked)
1315 <                        UNSAFE.unpark(w);
1836 >                // Wake up workers parked on event queue
1837 >                int i, e; long c; Thread p;
1838 >                while ((i = ((~(e = (int)(c = ctl)) << 1) | 1) & SMASK) < n &&
1839 >                       (w = ws[i]) != null &&
1840 >                       w.eventCount == (e | INT_SIGN)) {
1841 >                    long nc = ((long)(w.nextWait & E_MASK) |
1842 >                               ((c + AC_UNIT) & AC_MASK) |
1843 >                               (c & (TC_MASK|STOP_BIT)));
1844 >                    if (U.compareAndSwapLong(this, CTL, c, nc)) {
1845 >                        w.eventCount = (e + E_SEQ) & E_MASK;
1846 >                        if ((p = w.parker) != null)
1847 >                            U.unpark(p);
1848 >                    }
1849                  }
1850              }
1851          }
1852      }
1853  
1321    // misc ForkJoinWorkerThread support
1322
1323    /**
1324     * Increment or decrement quiescerCount. Needed only to prevent
1325     * triggering shutdown if a worker is transiently inactive while
1326     * checking quiescence.
1327     *
1328     * @param delta 1 for increment, -1 for decrement
1329     */
1330    final void addQuiescerCount(int delta) {
1331        int c;
1332        do {} while (!UNSAFE.compareAndSwapInt(this, quiescerCountOffset,
1333                                               c = quiescerCount, c + delta));
1334    }
1335
1336    /**
1337     * Directly increment or decrement active count without
1338     * queuing. This method is used to transiently assert inactivation
1339     * while checking quiescence.
1340     *
1341     * @param delta 1 for increment, -1 for decrement
1342     */
1343    final void addActiveCount(int delta) {
1344        long d = delta < 0 ? -AC_UNIT : AC_UNIT;
1345        long c;
1346        do {} while (!UNSAFE.compareAndSwapLong(this, ctlOffset, c = ctl,
1347                                                ((c + d) & AC_MASK) |
1348                                                (c & ~AC_MASK)));
1349    }
1350
1351    /**
1352     * Returns the approximate (non-atomic) number of idle threads per
1353     * active thread.
1354     */
1355    final int idlePerActive() {
1356        // Approximate at powers of two for small values, saturate past 4
1357        int p = parallelism;
1358        int a = p + (int)(ctl >> AC_SHIFT);
1359        return (a > (p >>>= 1) ? 0 :
1360                a > (p >>>= 1) ? 1 :
1361                a > (p >>>= 1) ? 2 :
1362                a > (p >>>= 1) ? 4 :
1363                8);
1364    }
1365
1854      // Exported methods
1855  
1856      // Constructors
# Line 1437 | Line 1925 | public class ForkJoinPool extends Abstra
1925          this.parallelism = parallelism;
1926          this.factory = factory;
1927          this.ueh = handler;
1928 <        this.locallyFifo = asyncMode;
1928 >        this.localMode = asyncMode ? FIFO_QUEUE : LIFO_QUEUE;
1929 >        this.nextPoolIndex = 1;
1930          long np = (long)(-parallelism); // offset ctl counts
1931          this.ctl = ((np << AC_SHIFT) & AC_MASK) | ((np << TC_SHIFT) & TC_MASK);
1932 <        this.submissionQueue = new ForkJoinTask<?>[INITIAL_QUEUE_CAPACITY];
1444 <        // initialize workers array with room for 2*parallelism if possible
1932 >        // initialize workQueues array with room for 2*parallelism if possible
1933          int n = parallelism << 1;
1934          if (n >= MAX_ID)
1935              n = MAX_ID;
1936          else { // See Hackers Delight, sec 3.2, where n < (1 << 16)
1937              n |= n >>> 1; n |= n >>> 2; n |= n >>> 4; n |= n >>> 8;
1938          }
1939 <        workers = new ForkJoinWorkerThread[n + 1];
1940 <        this.submissionLock = new ReentrantLock();
1941 <        this.termination = submissionLock.newCondition();
1939 >        this.workQueues = new WorkQueue[(n + 1) << 1];
1940 >        ReentrantLock lck = this.lock = new ReentrantLock();
1941 >        this.termination = lck.newCondition();
1942 >        this.stealCount = new AtomicLong();
1943 >        this.nextWorkerNumber = new AtomicInteger();
1944          StringBuilder sb = new StringBuilder("ForkJoinPool-");
1945          sb.append(poolNumberGenerator.incrementAndGet());
1946          sb.append("-worker-");
1947          this.workerNamePrefix = sb.toString();
1948 +        // Create initial submission queue
1949 +        WorkQueue sq = tryAddSharedQueue(0);
1950 +        if (sq != null)
1951 +            sq.growArray(false);
1952      }
1953  
1954      // Execution methods
# Line 1476 | Line 1970 | public class ForkJoinPool extends Abstra
1970       *         scheduled for execution
1971       */
1972      public <T> T invoke(ForkJoinTask<T> task) {
1973 <        Thread t = Thread.currentThread();
1974 <        if (task == null)
1481 <            throw new NullPointerException();
1482 <        if (shutdown)
1483 <            throw new RejectedExecutionException();
1484 <        if ((t instanceof ForkJoinWorkerThread) &&
1485 <            ((ForkJoinWorkerThread)t).pool == this)
1486 <            return task.invoke();  // bypass submit if in same pool
1487 <        else {
1488 <            addSubmission(task);
1489 <            return task.join();
1490 <        }
1491 <    }
1492 <
1493 <    /**
1494 <     * Unless terminating, forks task if within an ongoing FJ
1495 <     * computation in the current pool, else submits as external task.
1496 <     */
1497 <    private <T> void forkOrSubmit(ForkJoinTask<T> task) {
1498 <        ForkJoinWorkerThread w;
1499 <        Thread t = Thread.currentThread();
1500 <        if (shutdown)
1501 <            throw new RejectedExecutionException();
1502 <        if ((t instanceof ForkJoinWorkerThread) &&
1503 <            (w = (ForkJoinWorkerThread)t).pool == this)
1504 <            w.pushTask(task);
1505 <        else
1506 <            addSubmission(task);
1973 >        doSubmit(task);
1974 >        return task.join();
1975      }
1976  
1977      /**
# Line 1515 | Line 1983 | public class ForkJoinPool extends Abstra
1983       *         scheduled for execution
1984       */
1985      public void execute(ForkJoinTask<?> task) {
1986 <        if (task == null)
1519 <            throw new NullPointerException();
1520 <        forkOrSubmit(task);
1986 >        doSubmit(task);
1987      }
1988  
1989      // AbstractExecutorService methods
# Line 1535 | Line 2001 | public class ForkJoinPool extends Abstra
2001              job = (ForkJoinTask<?>) task;
2002          else
2003              job = ForkJoinTask.adapt(task, null);
2004 <        forkOrSubmit(job);
2004 >        doSubmit(job);
2005      }
2006  
2007      /**
# Line 1548 | Line 2014 | public class ForkJoinPool extends Abstra
2014       *         scheduled for execution
2015       */
2016      public <T> ForkJoinTask<T> submit(ForkJoinTask<T> task) {
2017 <        if (task == null)
1552 <            throw new NullPointerException();
1553 <        forkOrSubmit(task);
2017 >        doSubmit(task);
2018          return task;
2019      }
2020  
# Line 1563 | Line 2027 | public class ForkJoinPool extends Abstra
2027          if (task == null)
2028              throw new NullPointerException();
2029          ForkJoinTask<T> job = ForkJoinTask.adapt(task);
2030 <        forkOrSubmit(job);
2030 >        doSubmit(job);
2031          return job;
2032      }
2033  
# Line 1576 | Line 2040 | public class ForkJoinPool extends Abstra
2040          if (task == null)
2041              throw new NullPointerException();
2042          ForkJoinTask<T> job = ForkJoinTask.adapt(task, result);
2043 <        forkOrSubmit(job);
2043 >        doSubmit(job);
2044          return job;
2045      }
2046  
# Line 1593 | Line 2057 | public class ForkJoinPool extends Abstra
2057              job = (ForkJoinTask<?>) task;
2058          else
2059              job = ForkJoinTask.adapt(task, null);
2060 <        forkOrSubmit(job);
2060 >        doSubmit(job);
2061          return job;
2062      }
2063  
# Line 1670 | Line 2134 | public class ForkJoinPool extends Abstra
2134       * @return {@code true} if this pool uses async mode
2135       */
2136      public boolean getAsyncMode() {
2137 <        return locallyFifo;
2137 >        return localMode != 0;
2138      }
2139  
2140      /**
# Line 1682 | Line 2146 | public class ForkJoinPool extends Abstra
2146       * @return the number of worker threads
2147       */
2148      public int getRunningThreadCount() {
2149 <        int r = parallelism + (int)(ctl >> AC_SHIFT);
2150 <        return (r <= 0) ? 0 : r; // suppress momentarily negative values
2149 >        int rc = 0;
2150 >        WorkQueue[] ws; WorkQueue w;
2151 >        if ((ws = workQueues) != null) {
2152 >            int n = ws.length;
2153 >            for (int i = 1; i < n; i += 2) {
2154 >                Thread.State s; ForkJoinWorkerThread wt;
2155 >                if ((w = ws[i]) != null && (wt = w.owner) != null &&
2156 >                    w.eventCount >= 0 &&
2157 >                    (s = wt.getState()) != Thread.State.BLOCKED &&
2158 >                    s != Thread.State.WAITING &&
2159 >                    s != Thread.State.TIMED_WAITING)
2160 >                    ++rc;
2161 >            }
2162 >        }
2163 >        return rc;
2164      }
2165  
2166      /**
# Line 1694 | Line 2171 | public class ForkJoinPool extends Abstra
2171       * @return the number of active threads
2172       */
2173      public int getActiveThreadCount() {
2174 <        int r = parallelism + (int)(ctl >> AC_SHIFT) + blockedCount;
2174 >        int r = parallelism + (int)(ctl >> AC_SHIFT);
2175          return (r <= 0) ? 0 : r; // suppress momentarily negative values
2176      }
2177  
# Line 1710 | Line 2187 | public class ForkJoinPool extends Abstra
2187       * @return {@code true} if all threads are currently idle
2188       */
2189      public boolean isQuiescent() {
2190 <        return parallelism + (int)(ctl >> AC_SHIFT) + blockedCount == 0;
2190 >        return (int)(ctl >> AC_SHIFT) + parallelism == 0;
2191      }
2192  
2193      /**
# Line 1725 | Line 2202 | public class ForkJoinPool extends Abstra
2202       * @return the number of steals
2203       */
2204      public long getStealCount() {
2205 <        return stealCount;
2205 >        long count = stealCount.get();
2206 >        WorkQueue[] ws; WorkQueue w;
2207 >        if ((ws = workQueues) != null) {
2208 >            int n = ws.length;
2209 >            for (int i = 1; i < n; i += 2) {
2210 >                if ((w = ws[i]) != null)
2211 >                    count += w.totalSteals;
2212 >            }
2213 >        }
2214 >        return count;
2215      }
2216  
2217      /**
# Line 1740 | Line 2226 | public class ForkJoinPool extends Abstra
2226       */
2227      public long getQueuedTaskCount() {
2228          long count = 0;
2229 <        ForkJoinWorkerThread[] ws;
2230 <        if ((short)(ctl >>> TC_SHIFT) > -parallelism &&
2231 <            (ws = workers) != null) {
2232 <            for (ForkJoinWorkerThread w : ws)
2233 <                if (w != null)
2234 <                    count -= w.queueBase - w.queueTop; // must read base first
2229 >        WorkQueue[] ws; WorkQueue w;
2230 >        if ((ws = workQueues) != null) {
2231 >            int n = ws.length;
2232 >            for (int i = 1; i < n; i += 2) {
2233 >                if ((w = ws[i]) != null)
2234 >                    count += w.queueSize();
2235 >            }
2236          }
2237          return count;
2238      }
# Line 1758 | Line 2245 | public class ForkJoinPool extends Abstra
2245       * @return the number of queued submissions
2246       */
2247      public int getQueuedSubmissionCount() {
2248 <        return -queueBase + queueTop;
2248 >        int count = 0;
2249 >        WorkQueue[] ws; WorkQueue w;
2250 >        if ((ws = workQueues) != null) {
2251 >            int n = ws.length;
2252 >            for (int i = 0; i < n; i += 2) {
2253 >                if ((w = ws[i]) != null)
2254 >                    count += w.queueSize();
2255 >            }
2256 >        }
2257 >        return count;
2258      }
2259  
2260      /**
# Line 1768 | Line 2264 | public class ForkJoinPool extends Abstra
2264       * @return {@code true} if there are any queued submissions
2265       */
2266      public boolean hasQueuedSubmissions() {
2267 <        return queueBase != queueTop;
2267 >        WorkQueue[] ws; WorkQueue w;
2268 >        if ((ws = workQueues) != null) {
2269 >            int n = ws.length;
2270 >            for (int i = 0; i < n; i += 2) {
2271 >                if ((w = ws[i]) != null && w.queueSize() != 0)
2272 >                    return true;
2273 >            }
2274 >        }
2275 >        return false;
2276      }
2277  
2278      /**
# Line 1779 | Line 2283 | public class ForkJoinPool extends Abstra
2283       * @return the next submission, or {@code null} if none
2284       */
2285      protected ForkJoinTask<?> pollSubmission() {
2286 <        ForkJoinTask<?> t; ForkJoinTask<?>[] q; int b, i;
2287 <        while ((b = queueBase) != queueTop &&
2288 <               (q = submissionQueue) != null &&
2289 <               (i = (q.length - 1) & b) >= 0) {
2290 <            long u = (i << ASHIFT) + ABASE;
2291 <            if ((t = q[i]) != null &&
1788 <                queueBase == b &&
1789 <                UNSAFE.compareAndSwapObject(q, u, t, null)) {
1790 <                queueBase = b + 1;
1791 <                return t;
2286 >        WorkQueue[] ws; WorkQueue w; ForkJoinTask<?> t;
2287 >        if ((ws = workQueues) != null) {
2288 >            int n = ws.length;
2289 >            for (int i = 0; i < n; i += 2) {
2290 >                if ((w = ws[i]) != null && (t = w.poll()) != null)
2291 >                    return t;
2292              }
2293          }
2294          return null;
# Line 1813 | Line 2313 | public class ForkJoinPool extends Abstra
2313       */
2314      protected int drainTasksTo(Collection<? super ForkJoinTask<?>> c) {
2315          int count = 0;
2316 <        while (queueBase != queueTop) {
2317 <            ForkJoinTask<?> t = pollSubmission();
2318 <            if (t != null) {
2319 <                c.add(t);
2320 <                ++count;
2316 >        WorkQueue[] ws; WorkQueue w; ForkJoinTask<?> t;
2317 >        if ((ws = workQueues) != null) {
2318 >            int n = ws.length;
2319 >            for (int i = 0; i < n; ++i) {
2320 >                if ((w = ws[i]) != null) {
2321 >                    while ((t = w.poll()) != null) {
2322 >                        c.add(t);
2323 >                        ++count;
2324 >                    }
2325 >                }
2326              }
2327          }
1823        ForkJoinWorkerThread[] ws;
1824        if ((short)(ctl >>> TC_SHIFT) > -parallelism &&
1825            (ws = workers) != null) {
1826            for (ForkJoinWorkerThread w : ws)
1827                if (w != null)
1828                    count += w.drainTasksTo(c);
1829        }
2328          return count;
2329      }
2330  
# Line 1841 | Line 2339 | public class ForkJoinPool extends Abstra
2339          long st = getStealCount();
2340          long qt = getQueuedTaskCount();
2341          long qs = getQueuedSubmissionCount();
2342 +        int rc = getRunningThreadCount();
2343          int pc = parallelism;
2344          long c = ctl;
2345          int tc = pc + (short)(c >>> TC_SHIFT);
2346 <        int rc = pc + (int)(c >> AC_SHIFT);
2347 <        if (rc < 0) // ignore transient negative
2348 <            rc = 0;
1850 <        int ac = rc + blockedCount;
2346 >        int ac = pc + (int)(c >> AC_SHIFT);
2347 >        if (ac < 0) // ignore transient negative
2348 >            ac = 0;
2349          String level;
2350          if ((c & STOP_BIT) != 0)
2351              level = (tc == 0) ? "Terminated" : "Terminating";
2352          else
2353 <            level = shutdown ? "Shutting down" : "Running";
2353 >            level = runState < 0 ? "Shutting down" : "Running";
2354          return super.toString() +
2355              "[" + level +
2356              ", parallelism = " + pc +
# Line 1879 | Line 2377 | public class ForkJoinPool extends Abstra
2377       */
2378      public void shutdown() {
2379          checkPermission();
2380 <        shutdown = true;
2380 >        enableShutdown();
2381          tryTerminate(false);
2382      }
2383  
# Line 1901 | Line 2399 | public class ForkJoinPool extends Abstra
2399       */
2400      public List<Runnable> shutdownNow() {
2401          checkPermission();
2402 <        shutdown = true;
2402 >        enableShutdown();
2403          tryTerminate(true);
2404          return Collections.emptyList();
2405      }
# Line 1937 | Line 2435 | public class ForkJoinPool extends Abstra
2435      }
2436  
2437      /**
1940     * Returns true if terminating or terminated. Used by ForkJoinWorkerThread.
1941     */
1942    final boolean isAtLeastTerminating() {
1943        return (ctl & STOP_BIT) != 0L;
1944    }
1945
1946    /**
2438       * Returns {@code true} if this pool has been shut down.
2439       *
2440       * @return {@code true} if this pool has been shut down
2441       */
2442      public boolean isShutdown() {
2443 <        return shutdown;
2443 >        return runState < 0;
2444      }
2445  
2446      /**
# Line 1966 | Line 2457 | public class ForkJoinPool extends Abstra
2457      public boolean awaitTermination(long timeout, TimeUnit unit)
2458          throws InterruptedException {
2459          long nanos = unit.toNanos(timeout);
2460 <        final ReentrantLock lock = this.submissionLock;
2460 >        final ReentrantLock lock = this.lock;
2461          lock.lock();
2462          try {
2463              for (;;) {
# Line 2077 | Line 2568 | public class ForkJoinPool extends Abstra
2568      public static void managedBlock(ManagedBlocker blocker)
2569          throws InterruptedException {
2570          Thread t = Thread.currentThread();
2571 <        if (t instanceof ForkJoinWorkerThread) {
2572 <            ForkJoinWorkerThread w = (ForkJoinWorkerThread) t;
2573 <            w.pool.awaitBlocker(blocker);
2574 <        }
2575 <        else {
2576 <            do {} while (!blocker.isReleasable() && !blocker.block());
2571 >        ForkJoinPool p = ((t instanceof ForkJoinWorkerThread) ?
2572 >                          ((ForkJoinWorkerThread)t).pool : null);
2573 >        while (!blocker.isReleasable()) {
2574 >            if (p == null || p.tryCompensate()) {
2575 >                try {
2576 >                    do {} while (!blocker.isReleasable() && !blocker.block());
2577 >                } finally {
2578 >                    if (p != null)
2579 >                        p.incrementActiveCount();
2580 >                }
2581 >                break;
2582 >            }
2583          }
2584      }
2585  
# Line 2099 | Line 2596 | public class ForkJoinPool extends Abstra
2596      }
2597  
2598      // Unsafe mechanics
2599 <    private static final sun.misc.Unsafe UNSAFE;
2600 <    private static final long ctlOffset;
2601 <    private static final long stealCountOffset;
2602 <    private static final long blockedCountOffset;
2106 <    private static final long quiescerCountOffset;
2107 <    private static final long scanGuardOffset;
2108 <    private static final long nextWorkerNumberOffset;
2109 <    private static final long ABASE;
2110 <    private static final int ASHIFT;
2599 >    private static final sun.misc.Unsafe U;
2600 >    private static final long CTL;
2601 >    private static final long RUNSTATE;
2602 >    private static final long PARKBLOCKER;
2603  
2604      static {
2605          poolNumberGenerator = new AtomicInteger();
2114        workerSeedGenerator = new Random();
2606          modifyThreadPermission = new RuntimePermission("modifyThread");
2607          defaultForkJoinWorkerThreadFactory =
2608              new DefaultForkJoinWorkerThreadFactory();
2609 +        int s;
2610          try {
2611 <            UNSAFE = getUnsafe();
2611 >            U = getUnsafe();
2612              Class<?> k = ForkJoinPool.class;
2613 <            ctlOffset = UNSAFE.objectFieldOffset
2613 >            Class<?> tk = Thread.class;
2614 >            CTL = U.objectFieldOffset
2615                  (k.getDeclaredField("ctl"));
2616 <            stealCountOffset = UNSAFE.objectFieldOffset
2617 <                (k.getDeclaredField("stealCount"));
2618 <            blockedCountOffset = UNSAFE.objectFieldOffset
2619 <                (k.getDeclaredField("blockedCount"));
2127 <            quiescerCountOffset = UNSAFE.objectFieldOffset
2128 <                (k.getDeclaredField("quiescerCount"));
2129 <            scanGuardOffset = UNSAFE.objectFieldOffset
2130 <                (k.getDeclaredField("scanGuard"));
2131 <            nextWorkerNumberOffset = UNSAFE.objectFieldOffset
2132 <                (k.getDeclaredField("nextWorkerNumber"));
2616 >            RUNSTATE = U.objectFieldOffset
2617 >                (k.getDeclaredField("runState"));
2618 >            PARKBLOCKER = U.objectFieldOffset
2619 >                (tk.getDeclaredField("parkBlocker"));
2620          } catch (Exception e) {
2621              throw new Error(e);
2622          }
2136        Class<?> a = ForkJoinTask[].class;
2137        ABASE = UNSAFE.arrayBaseOffset(a);
2138        int s = UNSAFE.arrayIndexScale(a);
2139        if ((s & (s-1)) != 0)
2140            throw new Error("data type scale not a power of two");
2141        ASHIFT = 31 - Integer.numberOfLeadingZeros(s);
2623      }
2624  
2625      /**
# Line 2168 | Line 2649 | public class ForkJoinPool extends Abstra
2649              }
2650          }
2651      }
2652 +
2653   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines