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.90 by jsr166, Mon Nov 29 20:58:06 2010 UTC vs.
Revision 1.111 by dl, Thu Jan 26 00:08:13 2012 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines