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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines