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.68 by jsr166, Wed Sep 1 06:40:12 2010 UTC vs.
Revision 1.139 by dl, Wed Oct 31 12:49:24 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.*;
10
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.AbstractQueuedSynchronizer;
25 > import java.util.concurrent.locks.Condition;
26  
27   /**
28   * An {@link ExecutorService} for running {@link ForkJoinTask}s.
# Line 27 | 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 static {@link #commonPool} is available and appropriate for
46 > * most applications. The common pool is used by any ForkJoinTask that
47 > * is not explicitly submitted to a specified pool. Using the common
48 > * pool normally reduces resource usage (its threads are slowly
49 > * reclaimed during periods of non-use, and reinstated upon subsequent
50 > * use).  The common pool is by default constructed with default
51 > * parameters, but these may be controlled by setting any or all of
52 > * the three properties {@code
53 > * java.util.concurrent.ForkJoinPool.common.{parallelism,
54 > * threadFactory, exceptionHandler}}.
55   *
56 < * <p>A {@code ForkJoinPool} is constructed with a given target
57 < * parallelism level; by default, equal to the number of available
58 < * processors. The pool attempts to maintain enough active (or
59 < * available) threads by dynamically adding, suspending, or resuming
60 < * internal worker threads, even if some tasks are stalled waiting to
61 < * join others. However, no such adjustments are guaranteed in the
62 < * face of blocked IO or other unmanaged synchronization. The nested
63 < * {@link ManagedBlocker} interface enables extension of the kinds of
56 > * <p>For applications that require separate or custom pools, a {@code
57 > * ForkJoinPool} may be constructed with a given target parallelism
58 > * level; by default, equal to the number of available processors. The
59 > * pool attempts to maintain enough active (or available) threads by
60 > * dynamically adding, suspending, or resuming internal worker
61 > * threads, even if some tasks are stalled waiting to join
62 > * others. However, no such adjustments are guaranteed in the face of
63 > * blocked IO or other unmanaged synchronization. The nested {@link
64 > * ManagedBlocker} interface enables extension of the kinds of
65   * synchronization accommodated.
66   *
67   * <p>In addition to execution and lifecycle control methods, this
# Line 52 | Line 72 | import java.util.concurrent.CountDownLat
72   * convenient form for informal monitoring.
73   *
74   * <p> As is the case with other ExecutorServices, there are three
75 < * main task execution methods summarized in the following
76 < * table. These are designed to be used by clients not already engaged
77 < * in fork/join computations in the current pool.  The main forms of
78 < * these methods accept instances of {@code ForkJoinTask}, but
79 < * overloaded forms also allow mixed execution of plain {@code
75 > * main task execution methods summarized in the following table.
76 > * These are designed to be used primarily by clients not already
77 > * engaged in fork/join computations in the current pool.  The main
78 > * forms of these methods accept instances of {@code ForkJoinTask},
79 > * but overloaded forms also allow mixed execution of plain {@code
80   * Runnable}- or {@code Callable}- based activities as well.  However,
81 < * tasks that are already executing in a pool should normally
82 < * <em>NOT</em> use these pool execution methods, but instead use the
83 < * within-computation forms listed in the table.
81 > * tasks that are already executing in a pool should normally instead
82 > * use the within-computation forms listed in the table unless using
83 > * async event-style tasks that are not usually joined, in which case
84 > * there is little difference among choice of methods.
85   *
86   * <table BORDER CELLPADDING=3 CELLSPACING=1>
87   *  <tr>
# Line 85 | Line 106 | import java.util.concurrent.CountDownLat
106   *  </tr>
107   * </table>
108   *
88 * <p><b>Sample Usage.</b> Normally a single {@code ForkJoinPool} is
89 * used for all parallel task execution in a program or subsystem.
90 * Otherwise, use would not usually outweigh the construction and
91 * bookkeeping overhead of creating a large set of threads. For
92 * example, a common pool could be used for the {@code SortTasks}
93 * illustrated in {@link RecursiveAction}. Because {@code
94 * ForkJoinPool} uses threads in {@linkplain java.lang.Thread#isDaemon
95 * daemon} mode, there is typically no need to explicitly {@link
96 * #shutdown} such a pool upon program exit.
97 *
98 * <pre>
99 * static final ForkJoinPool mainPool = new ForkJoinPool();
100 * ...
101 * public void sort(long[] array) {
102 *   mainPool.invoke(new SortTask(array, 0, array.length));
103 * }
104 * </pre>
105 *
109   * <p><b>Implementation notes</b>: This implementation restricts the
110   * maximum number of running threads to 32767. Attempts to create
111   * pools with greater than the maximum number result in
# Line 120 | Line 123 | public class ForkJoinPool extends Abstra
123      /*
124       * Implementation Overview
125       *
126 <     * This class provides the central bookkeeping and control for a
127 <     * set of worker threads: Submissions from non-FJ threads enter
128 <     * into a submission queue. Workers take these tasks and typically
129 <     * split them into subtasks that may be stolen by other workers.
130 <     * The main work-stealing mechanics implemented in class
131 <     * ForkJoinWorkerThread give first priority to processing tasks
132 <     * from their own queues (LIFO or FIFO, depending on mode), then
133 <     * to randomized FIFO steals of tasks in other worker queues, and
134 <     * lastly to new submissions. These mechanics do not consider
135 <     * affinities, loads, cache localities, etc, so rarely provide the
136 <     * best possible performance on a given machine, but portably
137 <     * provide good throughput by averaging over these factors.
138 <     * (Further, even if we did try to use such information, we do not
139 <     * usually have a basis for exploiting it. For example, some sets
140 <     * of tasks profit from cache affinities, but others are harmed by
141 <     * cache pollution effects.)
142 <     *
143 <     * Beyond work-stealing support and essential bookkeeping, the
144 <     * main responsibility of this framework is to take actions when
145 <     * one worker is waiting to join a task stolen (or always held by)
146 <     * another.  Because we are multiplexing many tasks on to a pool
147 <     * of workers, we can't just let them block (as in Thread.join).
148 <     * We also cannot just reassign the joiner's run-time stack with
149 <     * another and replace it later, which would be a form of
150 <     * "continuation", that even if possible is not necessarily a good
151 <     * idea. Given that the creation costs of most threads on most
152 <     * systems mainly surrounds setting up runtime stacks, thread
153 <     * creation and switching is usually not much more expensive than
154 <     * stack creation and switching, and is more flexible). Instead we
155 <     * combine two tactics:
126 >     * This class and its nested classes provide the main
127 >     * functionality and control for a set of worker threads:
128 >     * Submissions from non-FJ threads enter into submission queues.
129 >     * Workers take these tasks and typically split them into subtasks
130 >     * that may be stolen by other workers.  Preference rules give
131 >     * first priority to processing tasks from their own queues (LIFO
132 >     * or FIFO, depending on mode), then to randomized FIFO steals of
133 >     * tasks in other queues.
134 >     *
135 >     * WorkQueues
136 >     * ==========
137 >     *
138 >     * Most operations occur within work-stealing queues (in nested
139 >     * class WorkQueue).  These are special forms of Deques that
140 >     * support only three of the four possible end-operations -- push,
141 >     * pop, and poll (aka steal), under the further constraints that
142 >     * push and pop are called only from the owning thread (or, as
143 >     * extended here, under a lock), while poll may be called from
144 >     * other threads.  (If you are unfamiliar with them, you probably
145 >     * want to read Herlihy and Shavit's book "The Art of
146 >     * Multiprocessor programming", chapter 16 describing these in
147 >     * more detail before proceeding.)  The main work-stealing queue
148 >     * design is roughly similar to those in the papers "Dynamic
149 >     * Circular Work-Stealing Deque" by Chase and Lev, SPAA 2005
150 >     * (http://research.sun.com/scalable/pubs/index.html) and
151 >     * "Idempotent work stealing" by Michael, Saraswat, and Vechev,
152 >     * PPoPP 2009 (http://portal.acm.org/citation.cfm?id=1504186).
153 >     * The main differences ultimately stem from GC requirements that
154 >     * we null out taken slots as soon as we can, to maintain as small
155 >     * a footprint as possible even in programs generating huge
156 >     * numbers of tasks. To accomplish this, we shift the CAS
157 >     * arbitrating pop vs poll (steal) from being on the indices
158 >     * ("base" and "top") to the slots themselves.  So, both a
159 >     * successful pop and poll mainly entail a CAS of a slot from
160 >     * non-null to null.  Because we rely on CASes of references, we
161 >     * do not need tag bits on base or top.  They are simple ints as
162 >     * used in any circular array-based queue (see for example
163 >     * ArrayDeque).  Updates to the indices must still be ordered in a
164 >     * way that guarantees that top == base means the queue is empty,
165 >     * but otherwise may err on the side of possibly making the queue
166 >     * appear nonempty when a push, pop, or poll have not fully
167 >     * committed. Note that this means that the poll operation,
168 >     * considered individually, is not wait-free. One thief cannot
169 >     * successfully continue until another in-progress one (or, if
170 >     * previously empty, a push) completes.  However, in the
171 >     * aggregate, we ensure at least probabilistic non-blockingness.
172 >     * If an attempted steal fails, a thief always chooses a different
173 >     * random victim target to try next. So, in order for one thief to
174 >     * progress, it suffices for any in-progress poll or new push on
175 >     * any empty queue to complete. (This is why we normally use
176 >     * method pollAt and its variants that try once at the apparent
177 >     * base index, else consider alternative actions, rather than
178 >     * method poll.)
179 >     *
180 >     * This approach also enables support of a user mode in which local
181 >     * task processing is in FIFO, not LIFO order, simply by using
182 >     * poll rather than pop.  This can be useful in message-passing
183 >     * frameworks in which tasks are never joined.  However neither
184 >     * mode considers affinities, loads, cache localities, etc, so
185 >     * rarely provide the best possible performance on a given
186 >     * machine, but portably provide good throughput by averaging over
187 >     * these factors.  (Further, even if we did try to use such
188 >     * information, we do not usually have a basis for exploiting it.
189 >     * For example, some sets of tasks profit from cache affinities,
190 >     * but others are harmed by cache pollution effects.)
191 >     *
192 >     * WorkQueues are also used in a similar way for tasks submitted
193 >     * to the pool. We cannot mix these tasks in the same queues used
194 >     * for work-stealing (this would contaminate lifo/fifo
195 >     * processing). Instead, we loosely associate submission queues
196 >     * with submitting threads, using a form of hashing.  The
197 >     * ThreadLocal Submitter class contains a value initially used as
198 >     * a hash code for choosing existing queues, but may be randomly
199 >     * repositioned upon contention with other submitters.  In
200 >     * essence, submitters act like workers except that they never
201 >     * take tasks, and they are multiplexed on to a finite number of
202 >     * shared work queues. However, classes are set up so that future
203 >     * extensions could allow submitters to optionally help perform
204 >     * tasks as well. Insertion of tasks in shared mode requires a
205 >     * lock (mainly to protect in the case of resizing) but we use
206 >     * only a simple spinlock (using bits in field runState), because
207 >     * submitters encountering a busy queue move on to try or create
208 >     * other queues -- they block only when creating and registering
209 >     * new queues.
210 >     *
211 >     * Management
212 >     * ==========
213 >     *
214 >     * The main throughput advantages of work-stealing stem from
215 >     * decentralized control -- workers mostly take tasks from
216 >     * themselves or each other. We cannot negate this in the
217 >     * implementation of other management responsibilities. The main
218 >     * tactic for avoiding bottlenecks is packing nearly all
219 >     * essentially atomic control state into two volatile variables
220 >     * that are by far most often read (not written) as status and
221 >     * consistency checks.
222 >     *
223 >     * Field "ctl" contains 64 bits holding all the information needed
224 >     * to atomically decide to add, inactivate, enqueue (on an event
225 >     * queue), dequeue, and/or re-activate workers.  To enable this
226 >     * packing, we restrict maximum parallelism to (1<<15)-1 (which is
227 >     * far in excess of normal operating range) to allow ids, counts,
228 >     * and their negations (used for thresholding) to fit into 16bit
229 >     * fields.
230 >     *
231 >     * Field "runState" contains 32 bits needed to register and
232 >     * deregister WorkQueues, as well as to enable shutdown. It is
233 >     * only modified under a lock (normally briefly held, but
234 >     * occasionally protecting allocations and resizings) but even
235 >     * when locked remains available to check consistency.
236 >     *
237 >     * Recording WorkQueues.  WorkQueues are recorded in the
238 >     * "workQueues" array that is created upon first use and expanded
239 >     * if necessary.  Updates to the array while recording new workers
240 >     * and unrecording terminated ones are protected from each other
241 >     * by a lock but the array is otherwise concurrently readable, and
242 >     * accessed directly.  To simplify index-based operations, the
243 >     * array size is always a power of two, and all readers must
244 >     * tolerate null slots. Shared (submission) queues are at even
245 >     * indices, worker queues at odd indices. Grouping them together
246 >     * in this way simplifies and speeds up task scanning.
247 >     *
248 >     * All worker thread creation is on-demand, triggered by task
249 >     * submissions, replacement of terminated workers, and/or
250 >     * compensation for blocked workers. However, all other support
251 >     * code is set up to work with other policies.  To ensure that we
252 >     * do not hold on to worker references that would prevent GC, ALL
253 >     * accesses to workQueues are via indices into the workQueues
254 >     * array (which is one source of some of the messy code
255 >     * constructions here). In essence, the workQueues array serves as
256 >     * a weak reference mechanism. Thus for example the wait queue
257 >     * field of ctl stores indices, not references.  Access to the
258 >     * workQueues in associated methods (for example signalWork) must
259 >     * both index-check and null-check the IDs. All such accesses
260 >     * ignore bad IDs by returning out early from what they are doing,
261 >     * since this can only be associated with termination, in which
262 >     * case it is OK to give up.  All uses of the workQueues array
263 >     * also check that it is non-null (even if previously
264 >     * non-null). This allows nulling during termination, which is
265 >     * currently not necessary, but remains an option for
266 >     * resource-revocation-based shutdown schemes. It also helps
267 >     * reduce JIT issuance of uncommon-trap code, which tends to
268 >     * unnecessarily complicate control flow in some methods.
269 >     *
270 >     * Event Queuing. Unlike HPC work-stealing frameworks, we cannot
271 >     * let workers spin indefinitely scanning for tasks when none can
272 >     * be found immediately, and we cannot start/resume workers unless
273 >     * there appear to be tasks available.  On the other hand, we must
274 >     * quickly prod them into action when new tasks are submitted or
275 >     * generated. In many usages, ramp-up time to activate workers is
276 >     * the main limiting factor in overall performance (this is
277 >     * compounded at program start-up by JIT compilation and
278 >     * allocation). So we try to streamline this as much as possible.
279 >     * We park/unpark workers after placing in an event wait queue
280 >     * when they cannot find work. This "queue" is actually a simple
281 >     * Treiber stack, headed by the "id" field of ctl, plus a 15bit
282 >     * counter value (that reflects the number of times a worker has
283 >     * been inactivated) to avoid ABA effects (we need only as many
284 >     * version numbers as worker threads). Successors are held in
285 >     * field WorkQueue.nextWait.  Queuing deals with several intrinsic
286 >     * races, mainly that a task-producing thread can miss seeing (and
287 >     * signalling) another thread that gave up looking for work but
288 >     * has not yet entered the wait queue. We solve this by requiring
289 >     * a full sweep of all workers (via repeated calls to method
290 >     * scan()) both before and after a newly waiting worker is added
291 >     * to the wait queue. During a rescan, the worker might release
292 >     * some other queued worker rather than itself, which has the same
293 >     * net effect. Because enqueued workers may actually be rescanning
294 >     * rather than waiting, we set and clear the "parker" field of
295 >     * WorkQueues to reduce unnecessary calls to unpark.  (This
296 >     * requires a secondary recheck to avoid missed signals.)  Note
297 >     * the unusual conventions about Thread.interrupts surrounding
298 >     * parking and other blocking: Because interrupts are used solely
299 >     * to alert threads to check termination, which is checked anyway
300 >     * upon blocking, we clear status (using Thread.interrupted)
301 >     * before any call to park, so that park does not immediately
302 >     * return due to status being set via some other unrelated call to
303 >     * interrupt in user code.
304 >     *
305 >     * Signalling.  We create or wake up workers only when there
306 >     * appears to be at least one task they might be able to find and
307 >     * execute.  When a submission is added or another worker adds a
308 >     * task to a queue that previously had fewer than two tasks, they
309 >     * signal waiting workers (or trigger creation of new ones if
310 >     * fewer than the given parallelism level -- see signalWork).
311 >     * These primary signals are buttressed by signals during rescans;
312 >     * together these cover the signals needed in cases when more
313 >     * tasks are pushed but untaken, and improve performance compared
314 >     * to having one thread wake up all workers.
315 >     *
316 >     * Trimming workers. To release resources after periods of lack of
317 >     * use, a worker starting to wait when the pool is quiescent will
318 >     * time out and terminate if the pool has remained quiescent for a
319 >     * given period -- a short period if there are more threads than
320 >     * parallelism, longer as the number of threads decreases. This
321 >     * will slowly propagate, eventually terminating all workers after
322 >     * periods of non-use.
323 >     *
324 >     * Shutdown and Termination. A call to shutdownNow atomically sets
325 >     * a runState bit and then (non-atomically) sets each worker's
326 >     * runState status, cancels all unprocessed tasks, and wakes up
327 >     * all waiting workers.  Detecting whether termination should
328 >     * commence after a non-abrupt shutdown() call requires more work
329 >     * and bookkeeping. We need consensus about quiescence (i.e., that
330 >     * there is no more work). The active count provides a primary
331 >     * indication but non-abrupt shutdown still requires a rechecking
332 >     * scan for any workers that are inactive but not queued.
333 >     *
334 >     * Joining Tasks
335 >     * =============
336 >     *
337 >     * Any of several actions may be taken when one worker is waiting
338 >     * to join a task stolen (or always held) by another.  Because we
339 >     * are multiplexing many tasks on to a pool of workers, we can't
340 >     * just let them block (as in Thread.join).  We also cannot just
341 >     * reassign the joiner's run-time stack with another and replace
342 >     * it later, which would be a form of "continuation", that even if
343 >     * possible is not necessarily a good idea since we sometimes need
344 >     * both an unblocked task and its continuation to progress.
345 >     * Instead we combine two tactics:
346       *
347       *   Helping: Arranging for the joiner to execute some task that it
348 <     *      would be running if the steal had not occurred.  Method
156 <     *      ForkJoinWorkerThread.helpJoinTask tracks joining->stealing
157 <     *      links to try to find such a task.
348 >     *      would be running if the steal had not occurred.
349       *
350       *   Compensating: Unless there are already enough live threads,
351 <     *      method helpMaintainParallelism() may create or
352 <     *      re-activate a spare thread to compensate for blocked
162 <     *      joiners until they unblock.
351 >     *      method tryCompensate() may create or re-activate a spare
352 >     *      thread to compensate for blocked joiners until they unblock.
353       *
354 <     * It is impossible to keep exactly the target (parallelism)
355 <     * number of threads running at any given time.  Determining
356 <     * existence of conservatively safe helping targets, the
357 <     * availability of already-created spares, and the apparent need
358 <     * to create new spares are all racy and require heuristic
359 <     * guidance, so we rely on multiple retries of each.  Compensation
360 <     * occurs in slow-motion. It is triggered only upon timeouts of
171 <     * Object.wait used for joins. This reduces poor decisions that
172 <     * would otherwise be made when threads are waiting for others
173 <     * that are stalled because of unrelated activities such as
174 <     * garbage collection.
354 >     * A third form (implemented in tryRemoveAndExec and
355 >     * tryPollForAndExec) amounts to helping a hypothetical
356 >     * compensator: If we can readily tell that a possible action of a
357 >     * compensator is to steal and execute the task being joined, the
358 >     * joining thread can do so directly, without the need for a
359 >     * compensation thread (although at the expense of larger run-time
360 >     * stacks, but the tradeoff is typically worthwhile).
361       *
362       * The ManagedBlocker extension API can't use helping so relies
363       * only on compensation in method awaitBlocker.
364       *
365 <     * The main throughput advantages of work-stealing stem from
366 <     * decentralized control -- workers mostly steal tasks from each
367 <     * other. We do not want to negate this by creating bottlenecks
368 <     * implementing other management responsibilities. So we use a
369 <     * collection of techniques that avoid, reduce, or cope well with
370 <     * contention. These entail several instances of bit-packing into
371 <     * CASable fields to maintain only the minimally required
372 <     * atomicity. To enable such packing, we restrict maximum
373 <     * parallelism to (1<<15)-1 (enabling twice this (to accommodate
374 <     * unbalanced increments and decrements) to fit into a 16 bit
375 <     * field, which is far in excess of normal operating range.  Even
376 <     * though updates to some of these bookkeeping fields do sometimes
377 <     * contend with each other, they don't normally cache-contend with
378 <     * updates to others enough to warrant memory padding or
379 <     * isolation. So they are all held as fields of ForkJoinPool
380 <     * objects.  The main capabilities are as follows:
381 <     *
382 <     * 1. Creating and removing workers. Workers are recorded in the
383 <     * "workers" array. This is an array as opposed to some other data
384 <     * structure to support index-based random steals by workers.
385 <     * Updates to the array recording new workers and unrecording
386 <     * terminated ones are protected from each other by a lock
387 <     * (workerLock) but the array is otherwise concurrently readable,
388 <     * and accessed directly by workers. To simplify index-based
389 <     * operations, the array size is always a power of two, and all
390 <     * readers must tolerate null slots. Currently, all worker thread
391 <     * creation is on-demand, triggered by task submissions,
392 <     * replacement of terminated workers, and/or compensation for
393 <     * blocked workers. However, all other support code is set up to
394 <     * work with other policies.
395 <     *
396 <     * To ensure that we do not hold on to worker references that
397 <     * would prevent GC, ALL accesses to workers are via indices into
398 <     * the workers array (which is one source of some of the unusual
399 <     * code constructions here). In essence, the workers array serves
400 <     * as a WeakReference mechanism. Thus for example the event queue
401 <     * stores worker indices, not worker references. Access to the
402 <     * workers in associated methods (for example releaseEventWaiters)
403 <     * must both index-check and null-check the IDs. All such accesses
404 <     * ignore bad IDs by returning out early from what they are doing,
405 <     * since this can only be associated with shutdown, in which case
406 <     * it is OK to give up. On termination, we just clobber these
407 <     * data structures without trying to use them.
408 <     *
409 <     * 2. Bookkeeping for dynamically adding and removing workers. We
410 <     * aim to approximately maintain the given level of parallelism.
411 <     * When some workers are known to be blocked (on joins or via
412 <     * ManagedBlocker), we may create or resume others to take their
413 <     * place until they unblock (see below). Implementing this
414 <     * requires counts of the number of "running" threads (i.e., those
415 <     * that are neither blocked nor artificially suspended) as well as
416 <     * the total number.  These two values are packed into one field,
417 <     * "workerCounts" because we need accurate snapshots when deciding
418 <     * to create, resume or suspend.  Note however that the
419 <     * correspondence of these counts to reality is not guaranteed. In
420 <     * particular updates for unblocked threads may lag until they
421 <     * actually wake up.
422 <     *
423 <     * 3. Maintaining global run state. The run state of the pool
424 <     * consists of a runLevel (SHUTDOWN, TERMINATING, etc) similar to
425 <     * those in other Executor implementations, as well as a count of
426 <     * "active" workers -- those that are, or soon will be, or
427 <     * recently were executing tasks. The runLevel and active count
428 <     * are packed together in order to correctly trigger shutdown and
243 <     * termination. Without care, active counts can be subject to very
244 <     * high contention.  We substantially reduce this contention by
245 <     * relaxing update rules.  A worker must claim active status
246 <     * prospectively, by activating if it sees that a submitted or
247 <     * stealable task exists (it may find after activating that the
248 <     * task no longer exists). It stays active while processing this
249 <     * task (if it exists) and any other local subtasks it produces,
250 <     * until it cannot find any other tasks. It then tries
251 <     * inactivating (see method preStep), but upon update contention
252 <     * instead scans for more tasks, later retrying inactivation if it
253 <     * doesn't find any.
254 <     *
255 <     * 4. Managing idle workers waiting for tasks. We cannot let
256 <     * workers spin indefinitely scanning for tasks when none are
257 <     * available. On the other hand, we must quickly prod them into
258 <     * action when new tasks are submitted or generated.  We
259 <     * park/unpark these idle workers using an event-count scheme.
260 <     * Field eventCount is incremented upon events that may enable
261 <     * workers that previously could not find a task to now find one:
262 <     * Submission of a new task to the pool, or another worker pushing
263 <     * a task onto a previously empty queue.  (We also use this
264 <     * mechanism for configuration and termination actions that
265 <     * require wakeups of idle workers).  Each worker maintains its
266 <     * last known event count, and blocks when a scan for work did not
267 <     * find a task AND its lastEventCount matches the current
268 <     * eventCount. Waiting idle workers are recorded in a variant of
269 <     * Treiber stack headed by field eventWaiters which, when nonzero,
270 <     * encodes the thread index and count awaited for by the worker
271 <     * thread most recently calling eventSync. This thread in turn has
272 <     * a record (field nextEventWaiter) for the next waiting worker.
273 <     * In addition to allowing simpler decisions about need for
274 <     * wakeup, the event count bits in eventWaiters serve the role of
275 <     * tags to avoid ABA errors in Treiber stacks. Upon any wakeup,
276 <     * released threads also try to release at most two others.  The
277 <     * net effect is a tree-like diffusion of signals, where released
278 <     * threads (and possibly others) help with unparks.  To further
279 <     * reduce contention effects a bit, failed CASes to increment
280 <     * field eventCount are tolerated without retries in signalWork.
281 <     * Conceptually they are merged into the same event, which is OK
282 <     * when their only purpose is to enable workers to scan for work.
283 <     *
284 <     * 5. Managing suspension of extra workers. When a worker notices
285 <     * (usually upon timeout of a wait()) that there are too few
286 <     * running threads, we may create a new thread to maintain
287 <     * parallelism level, or at least avoid starvation. Usually, extra
288 <     * threads are needed for only very short periods, yet join
289 <     * dependencies are such that we sometimes need them in
290 <     * bursts. Rather than create new threads each time this happens,
291 <     * we suspend no-longer-needed extra ones as "spares". For most
292 <     * purposes, we don't distinguish "extra" spare threads from
293 <     * normal "core" threads: On each call to preStep (the only point
294 <     * at which we can do this) a worker checks to see if there are
295 <     * now too many running workers, and if so, suspends itself.
296 <     * Method helpMaintainParallelism looks for suspended threads to
297 <     * resume before considering creating a new replacement. The
298 <     * spares themselves are encoded on another variant of a Treiber
299 <     * Stack, headed at field "spareWaiters".  Note that the use of
300 <     * spares is intrinsically racy.  One thread may become a spare at
301 <     * about the same time as another is needlessly being created. We
302 <     * counteract this and related slop in part by requiring resumed
303 <     * spares to immediately recheck (in preStep) to see whether they
304 <     * they should re-suspend.
305 <     *
306 <     * 6. Killing off unneeded workers. A timeout mechanism is used to
307 <     * shed unused workers: The oldest (first) event queue waiter uses
308 <     * a timed rather than hard wait. When this wait times out without
309 <     * a normal wakeup, it tries to shutdown any one (for convenience
310 <     * the newest) other spare or event waiter via
311 <     * tryShutdownUnusedWorker. This eventually reduces the number of
312 <     * worker threads to a minimum of one after a long enough period
313 <     * without use.
314 <     *
315 <     * 7. Deciding when to create new workers. The main dynamic
316 <     * control in this class is deciding when to create extra threads
317 <     * in method helpMaintainParallelism. We would like to keep
318 <     * exactly #parallelism threads running, which is an impossible
319 <     * task. We always need to create one when the number of running
320 <     * threads would become zero and all workers are busy. Beyond
321 <     * this, we must rely on heuristics that work well in the
322 <     * presence of transient phenomena such as GC stalls, dynamic
323 <     * compilation, and wake-up lags. These transients are extremely
324 <     * common -- we are normally trying to fully saturate the CPUs on
325 <     * a machine, so almost any activity other than running tasks
326 <     * impedes accuracy. Our main defense is to allow parallelism to
327 <     * lapse for a while during joins, and use a timeout to see if,
328 <     * after the resulting settling, there is still a need for
329 <     * additional workers.  This also better copes with the fact that
330 <     * some of the methods in this class tend to never become compiled
331 <     * (but are interpreted), so some components of the entire set of
332 <     * controls might execute 100 times faster than others. And
333 <     * similarly for cases where the apparent lack of work is just due
334 <     * to GC stalls and other transient system activity.
365 >     * The algorithm in tryHelpStealer entails a form of "linear"
366 >     * helping: Each worker records (in field currentSteal) the most
367 >     * recent task it stole from some other worker. Plus, it records
368 >     * (in field currentJoin) the task it is currently actively
369 >     * joining. Method tryHelpStealer uses these markers to try to
370 >     * find a worker to help (i.e., steal back a task from and execute
371 >     * it) that could hasten completion of the actively joined task.
372 >     * In essence, the joiner executes a task that would be on its own
373 >     * local deque had the to-be-joined task not been stolen. This may
374 >     * be seen as a conservative variant of the approach in Wagner &
375 >     * Calder "Leapfrogging: a portable technique for implementing
376 >     * efficient futures" SIGPLAN Notices, 1993
377 >     * (http://portal.acm.org/citation.cfm?id=155354). It differs in
378 >     * that: (1) We only maintain dependency links across workers upon
379 >     * steals, rather than use per-task bookkeeping.  This sometimes
380 >     * requires a linear scan of workQueues array to locate stealers,
381 >     * but often doesn't because stealers leave hints (that may become
382 >     * stale/wrong) of where to locate them.  A stealHint is only a
383 >     * hint because a worker might have had multiple steals and the
384 >     * hint records only one of them (usually the most current).
385 >     * Hinting isolates cost to when it is needed, rather than adding
386 >     * to per-task overhead.  (2) It is "shallow", ignoring nesting
387 >     * and potentially cyclic mutual steals.  (3) It is intentionally
388 >     * racy: field currentJoin is updated only while actively joining,
389 >     * which means that we miss links in the chain during long-lived
390 >     * tasks, GC stalls etc (which is OK since blocking in such cases
391 >     * is usually a good idea).  (4) We bound the number of attempts
392 >     * to find work (see MAX_HELP) and fall back to suspending the
393 >     * worker and if necessary replacing it with another.
394 >     *
395 >     * It is impossible to keep exactly the target parallelism number
396 >     * of threads running at any given time.  Determining the
397 >     * existence of conservatively safe helping targets, the
398 >     * availability of already-created spares, and the apparent need
399 >     * to create new spares are all racy, so we rely on multiple
400 >     * retries of each.  Compensation in the apparent absence of
401 >     * helping opportunities is challenging to control on JVMs, where
402 >     * GC and other activities can stall progress of tasks that in
403 >     * turn stall out many other dependent tasks, without us being
404 >     * able to determine whether they will ever require compensation.
405 >     * Even though work-stealing otherwise encounters little
406 >     * degradation in the presence of more threads than cores,
407 >     * aggressively adding new threads in such cases entails risk of
408 >     * unwanted positive feedback control loops in which more threads
409 >     * cause more dependent stalls (as well as delayed progress of
410 >     * unblocked threads to the point that we know they are available)
411 >     * leading to more situations requiring more threads, and so
412 >     * on. This aspect of control can be seen as an (analytically
413 >     * intractable) game with an opponent that may choose the worst
414 >     * (for us) active thread to stall at any time.  We take several
415 >     * precautions to bound losses (and thus bound gains), mainly in
416 >     * methods tryCompensate and awaitJoin: (1) We only try
417 >     * compensation after attempting enough helping steps (measured
418 >     * via counting and timing) that we have already consumed the
419 >     * estimated cost of creating and activating a new thread.  (2) We
420 >     * allow up to 50% of threads to be blocked before initially
421 >     * adding any others, and unless completely saturated, check that
422 >     * some work is available for a new worker before adding. Also, we
423 >     * create up to only 50% more threads until entering a mode that
424 >     * only adds a thread if all others are possibly blocked.  All
425 >     * together, this means that we might be half as fast to react,
426 >     * and create half as many threads as possible in the ideal case,
427 >     * but present vastly fewer anomalies in all other cases compared
428 >     * to both more aggressive and more conservative alternatives.
429       *
430 <     * Beware that there is a lot of representation-level coupling
430 >     * Style notes: There is a lot of representation-level coupling
431       * among classes ForkJoinPool, ForkJoinWorkerThread, and
432 <     * ForkJoinTask.  For example, direct access to "workers" array by
433 <     * workers, and direct access to ForkJoinTask.status by both
434 <     * ForkJoinPool and ForkJoinWorkerThread.  There is little point
435 <     * trying to reduce this, since any associated future changes in
436 <     * representations will need to be accompanied by algorithmic
437 <     * changes anyway.
438 <     *
439 <     * Style notes: There are lots of inline assignments (of form
440 <     * "while ((local = field) != 0)") which are usually the simplest
441 <     * way to ensure the required read orderings (which are sometimes
442 <     * critical). Also several occurrences of the unusual "do {}
443 <     * while(!cas...)" which is the simplest way to force an update of
444 <     * a CAS'ed variable. There are also other coding oddities that
445 <     * help some methods perform reasonably even when interpreted (not
446 <     * compiled), at the expense of some messy constructions that
447 <     * reduce byte code counts.
448 <     *
449 <     * The order of declarations in this file is: (1) statics (2)
450 <     * fields (along with constants used when unpacking some of them)
451 <     * (3) internal control methods (4) callbacks and other support
452 <     * for ForkJoinTask and ForkJoinWorkerThread classes, (5) exported
453 <     * methods (plus a few little helpers).
432 >     * ForkJoinTask.  The fields of WorkQueue maintain data structures
433 >     * managed by ForkJoinPool, so are directly accessed.  There is
434 >     * little point trying to reduce this, since any associated future
435 >     * changes in representations will need to be accompanied by
436 >     * algorithmic changes anyway. Several methods intrinsically
437 >     * sprawl because they must accumulate sets of consistent reads of
438 >     * volatiles held in local variables.  Methods signalWork() and
439 >     * scan() are the main bottlenecks, so are especially heavily
440 >     * micro-optimized/mangled.  There are lots of inline assignments
441 >     * (of form "while ((local = field) != 0)") which are usually the
442 >     * simplest way to ensure the required read orderings (which are
443 >     * sometimes critical). This leads to a "C"-like style of listing
444 >     * declarations of these locals at the heads of methods or blocks.
445 >     * There are several occurrences of the unusual "do {} while
446 >     * (!cas...)"  which is the simplest way to force an update of a
447 >     * CAS'ed variable. There are also other coding oddities that help
448 >     * some methods perform reasonably even when interpreted (not
449 >     * compiled).
450 >     *
451 >     * The order of declarations in this file is:
452 >     * (1) Static utility functions
453 >     * (2) Nested (static) classes
454 >     * (3) Static fields
455 >     * (4) Fields, along with constants used when unpacking some of them
456 >     * (5) Internal control methods
457 >     * (6) Callbacks and other support for ForkJoinTask methods
458 >     * (7) Exported methods
459 >     * (8) Static block initializing statics in minimally dependent order
460       */
461  
462 +    // Static utilities
463 +
464 +    /**
465 +     * If there is a security manager, makes sure caller has
466 +     * permission to modify threads.
467 +     */
468 +    private static void checkPermission() {
469 +        SecurityManager security = System.getSecurityManager();
470 +        if (security != null)
471 +            security.checkPermission(modifyThreadPermission);
472 +    }
473 +
474 +    // Nested classes
475 +
476      /**
477       * Factory for creating new {@link ForkJoinWorkerThread}s.
478       * A {@code ForkJoinWorkerThreadFactory} must be defined and used
# Line 387 | Line 501 | public class ForkJoinPool extends Abstra
501      }
502  
503      /**
504 <     * Creates a new ForkJoinWorkerThread. This factory is used unless
505 <     * overridden in ForkJoinPool constructors.
504 >     * Class for artificial tasks that are used to replace the target
505 >     * of local joins if they are removed from an interior queue slot
506 >     * in WorkQueue.tryRemoveAndExec. We don't need the proxy to
507 >     * actually do anything beyond having a unique identity.
508 >     */
509 >    static final class EmptyTask extends ForkJoinTask<Void> {
510 >        EmptyTask() { status = ForkJoinTask.NORMAL; } // force done
511 >        public final Void getRawResult() { return null; }
512 >        public final void setRawResult(Void x) {}
513 >        public final boolean exec() { return true; }
514 >    }
515 >
516 >    /**
517 >     * Queues supporting work-stealing as well as external task
518 >     * submission. See above for main rationale and algorithms.
519 >     * Implementation relies heavily on "Unsafe" intrinsics
520 >     * and selective use of "volatile":
521 >     *
522 >     * Field "base" is the index (mod array.length) of the least valid
523 >     * queue slot, which is always the next position to steal (poll)
524 >     * from if nonempty. Reads and writes require volatile orderings
525 >     * but not CAS, because updates are only performed after slot
526 >     * CASes.
527 >     *
528 >     * Field "top" is the index (mod array.length) of the next queue
529 >     * slot to push to or pop from. It is written only by owner thread
530 >     * for push, or under lock for trySharedPush, and accessed by
531 >     * other threads only after reading (volatile) base.  Both top and
532 >     * base are allowed to wrap around on overflow, but (top - base)
533 >     * (or more commonly -(base - top) to force volatile read of base
534 >     * before top) still estimates size.
535 >     *
536 >     * The array slots are read and written using the emulation of
537 >     * volatiles/atomics provided by Unsafe. Insertions must in
538 >     * general use putOrderedObject as a form of releasing store to
539 >     * ensure that all writes to the task object are ordered before
540 >     * its publication in the queue. (Although we can avoid one case
541 >     * of this when locked in trySharedPush.) All removals entail a
542 >     * CAS to null.  The array is always a power of two. To ensure
543 >     * safety of Unsafe array operations, all accesses perform
544 >     * explicit null checks and implicit bounds checks via
545 >     * power-of-two masking.
546 >     *
547 >     * In addition to basic queuing support, this class contains
548 >     * fields described elsewhere to control execution. It turns out
549 >     * to work better memory-layout-wise to include them in this
550 >     * class rather than a separate class.
551 >     *
552 >     * Performance on most platforms is very sensitive to placement of
553 >     * instances of both WorkQueues and their arrays -- we absolutely
554 >     * do not want multiple WorkQueue instances or multiple queue
555 >     * arrays sharing cache lines. (It would be best for queue objects
556 >     * and their arrays to share, but there is nothing available to
557 >     * help arrange that).  Unfortunately, because they are recorded
558 >     * in a common array, WorkQueue instances are often moved to be
559 >     * adjacent by garbage collectors. To reduce impact, we use field
560 >     * padding that works OK on common platforms; this effectively
561 >     * trades off slightly slower average field access for the sake of
562 >     * avoiding really bad worst-case access. (Until better JVM
563 >     * support is in place, this padding is dependent on transient
564 >     * properties of JVM field layout rules.)  We also take care in
565 >     * allocating, sizing and resizing the array. Non-shared queue
566 >     * arrays are initialized (via method growArray) by workers before
567 >     * use. Others are allocated on first use.
568       */
569 <    public static final ForkJoinWorkerThreadFactory
570 <        defaultForkJoinWorkerThreadFactory =
571 <        new DefaultForkJoinWorkerThreadFactory();
569 >    static final class WorkQueue {
570 >        /**
571 >         * Capacity of work-stealing queue array upon initialization.
572 >         * Must be a power of two; at least 4, but should be larger to
573 >         * reduce or eliminate cacheline sharing among queues.
574 >         * Currently, it is much larger, as a partial workaround for
575 >         * the fact that JVMs often place arrays in locations that
576 >         * share GC bookkeeping (especially cardmarks) such that
577 >         * per-write accesses encounter serious memory contention.
578 >         */
579 >        static final int INITIAL_QUEUE_CAPACITY = 1 << 13;
580  
581 <    /**
582 <     * Permission required for callers of methods that may start or
583 <     * kill threads.
584 <     */
585 <    private static final RuntimePermission modifyThreadPermission =
586 <        new RuntimePermission("modifyThread");
581 >        /**
582 >         * Maximum size for queue arrays. Must be a power of two less
583 >         * than or equal to 1 << (31 - width of array entry) to ensure
584 >         * lack of wraparound of index calculations, but defined to a
585 >         * value a bit less than this to help users trap runaway
586 >         * programs before saturating systems.
587 >         */
588 >        static final int MAXIMUM_QUEUE_CAPACITY = 1 << 26; // 64M
589  
590 <    /**
591 <     * If there is a security manager, makes sure caller has
592 <     * permission to modify threads.
593 <     */
594 <    private static void checkPermission() {
595 <        SecurityManager security = System.getSecurityManager();
596 <        if (security != null)
597 <            security.checkPermission(modifyThreadPermission);
590 >        volatile long totalSteals; // cumulative number of steals
591 >        int seed;                  // for random scanning; initialize nonzero
592 >        volatile int eventCount;   // encoded inactivation count; < 0 if inactive
593 >        int nextWait;              // encoded record of next event waiter
594 >        int rescans;               // remaining scans until block
595 >        int nsteals;               // top-level task executions since last idle
596 >        final int mode;            // lifo, fifo, or shared
597 >        int poolIndex;             // index of this queue in pool (or 0)
598 >        int stealHint;             // index of most recent known stealer
599 >        volatile int runState;     // 1: locked, -1: terminate; else 0
600 >        volatile int base;         // index of next slot for poll
601 >        int top;                   // index of next slot for push
602 >        ForkJoinTask<?>[] array;   // the elements (initially unallocated)
603 >        final ForkJoinPool pool;   // the containing pool (may be null)
604 >        final ForkJoinWorkerThread owner; // owning thread or null if shared
605 >        volatile Thread parker;    // == owner during call to park; else null
606 >        volatile ForkJoinTask<?> currentJoin;  // task being joined in awaitJoin
607 >        ForkJoinTask<?> currentSteal; // current non-local task being executed
608 >        // Heuristic padding to ameliorate unfortunate memory placements
609 >        Object p00, p01, p02, p03, p04, p05, p06, p07;
610 >        Object p08, p09, p0a, p0b, p0c, p0d, p0e;
611 >
612 >        WorkQueue(ForkJoinPool pool, ForkJoinWorkerThread owner, int mode) {
613 >            this.mode = mode;
614 >            this.pool = pool;
615 >            this.owner = owner;
616 >            // Place indices in the center of array (that is not yet allocated)
617 >            base = top = INITIAL_QUEUE_CAPACITY >>> 1;
618 >        }
619 >
620 >        /**
621 >         * Returns the approximate number of tasks in the queue.
622 >         */
623 >        final int queueSize() {
624 >            int n = base - top;       // non-owner callers must read base first
625 >            return (n >= 0) ? 0 : -n; // ignore transient negative
626 >        }
627 >
628 >        /**
629 >         * Provides a more accurate estimate of whether this queue has
630 >         * any tasks than does queueSize, by checking whether a
631 >         * near-empty queue has at least one unclaimed task.
632 >         */
633 >        final boolean isEmpty() {
634 >            ForkJoinTask<?>[] a; int m, s;
635 >            int n = base - (s = top);
636 >            return (n >= 0 ||
637 >                    (n == -1 &&
638 >                     ((a = array) == null ||
639 >                      (m = a.length - 1) < 0 ||
640 >                      U.getObjectVolatile
641 >                      (a, ((m & (s - 1)) << ASHIFT) + ABASE) == null)));
642 >        }
643 >
644 >        /**
645 >         * Pushes a task. Call only by owner in unshared queues.
646 >         *
647 >         * @param task the task. Caller must ensure non-null.
648 >         * @throw RejectedExecutionException if array cannot be resized
649 >         */
650 >        final void push(ForkJoinTask<?> task) {
651 >            ForkJoinTask<?>[] a; ForkJoinPool p;
652 >            int s = top, m, n;
653 >            if ((a = array) != null) {    // ignore if queue removed
654 >                U.putOrderedObject
655 >                    (a, (((m = a.length - 1) & s) << ASHIFT) + ABASE, task);
656 >                if ((n = (top = s + 1) - base) <= 2) {
657 >                    if ((p = pool) != null)
658 >                        p.signalWork();
659 >                }
660 >                else if (n >= m)
661 >                    growArray(true);
662 >            }
663 >        }
664 >
665 >        /**
666 >         * Pushes a task if lock is free and array is either big
667 >         * enough or can be resized to be big enough.
668 >         *
669 >         * @param task the task. Caller must ensure non-null.
670 >         * @return true if submitted
671 >         */
672 >        final boolean trySharedPush(ForkJoinTask<?> task) {
673 >            boolean submitted = false;
674 >            if (runState == 0 && U.compareAndSwapInt(this, RUNSTATE, 0, 1)) {
675 >                ForkJoinTask<?>[] a = array;
676 >                int s = top;
677 >                try {
678 >                    if ((a != null && a.length > s + 1 - base) ||
679 >                        (a = growArray(false)) != null) { // must presize
680 >                        int j = (((a.length - 1) & s) << ASHIFT) + ABASE;
681 >                        U.putObject(a, (long)j, task);    // don't need "ordered"
682 >                        top = s + 1;
683 >                        submitted = true;
684 >                    }
685 >                } finally {
686 >                    runState = 0;                         // unlock
687 >                }
688 >            }
689 >            return submitted;
690 >        }
691 >
692 >        /**
693 >         * Takes next task, if one exists, in LIFO order.  Call only
694 >         * by owner in unshared queues.
695 >         */
696 >        final ForkJoinTask<?> pop() {
697 >            ForkJoinTask<?>[] a; ForkJoinTask<?> t; int m;
698 >            if ((a = array) != null && (m = a.length - 1) >= 0) {
699 >                for (int s; (s = top - 1) - base >= 0;) {
700 >                    long j = ((m & s) << ASHIFT) + ABASE;
701 >                    if ((t = (ForkJoinTask<?>)U.getObject(a, j)) == null)
702 >                        break;
703 >                    if (U.compareAndSwapObject(a, j, t, null)) {
704 >                        top = s;
705 >                        return t;
706 >                    }
707 >                }
708 >            }
709 >            return null;
710 >        }
711 >
712 >        final ForkJoinTask<?> sharedPop() {
713 >            ForkJoinTask<?> task = null;
714 >            if (runState == 0 && U.compareAndSwapInt(this, RUNSTATE, 0, 1)) {
715 >                try {
716 >                    ForkJoinTask<?>[] a; int m;
717 >                    if ((a = array) != null && (m = a.length - 1) >= 0) {
718 >                        for (int s; (s = top - 1) - base >= 0;) {
719 >                            long j = ((m & s) << ASHIFT) + ABASE;
720 >                            ForkJoinTask<?> t =
721 >                                (ForkJoinTask<?>)U.getObject(a, j);
722 >                            if (t == null)
723 >                                break;
724 >                            if (U.compareAndSwapObject(a, j, t, null)) {
725 >                                top = s;
726 >                                task = t;
727 >                                break;
728 >                            }
729 >                        }
730 >                    }
731 >                } finally {
732 >                    runState = 0;
733 >                }
734 >            }
735 >            return task;
736 >        }
737 >
738 >
739 >        /**
740 >         * Takes a task in FIFO order if b is base of queue and a task
741 >         * can be claimed without contention. Specialized versions
742 >         * appear in ForkJoinPool methods scan and tryHelpStealer.
743 >         */
744 >        final ForkJoinTask<?> pollAt(int b) {
745 >            ForkJoinTask<?> t; ForkJoinTask<?>[] a;
746 >            if ((a = array) != null) {
747 >                int j = (((a.length - 1) & b) << ASHIFT) + ABASE;
748 >                if ((t = (ForkJoinTask<?>)U.getObjectVolatile(a, j)) != null &&
749 >                    base == b &&
750 >                    U.compareAndSwapObject(a, j, t, null)) {
751 >                    base = b + 1;
752 >                    return t;
753 >                }
754 >            }
755 >            return null;
756 >        }
757 >
758 >        /**
759 >         * Takes next task, if one exists, in FIFO order.
760 >         */
761 >        final ForkJoinTask<?> poll() {
762 >            ForkJoinTask<?>[] a; int b; ForkJoinTask<?> t;
763 >            while ((b = base) - top < 0 && (a = array) != null) {
764 >                int j = (((a.length - 1) & b) << ASHIFT) + ABASE;
765 >                t = (ForkJoinTask<?>)U.getObjectVolatile(a, j);
766 >                if (t != null) {
767 >                    if (base == b &&
768 >                        U.compareAndSwapObject(a, j, t, null)) {
769 >                        base = b + 1;
770 >                        return t;
771 >                    }
772 >                }
773 >                else if (base == b) {
774 >                    if (b + 1 == top)
775 >                        break;
776 >                    Thread.yield(); // wait for lagging update
777 >                }
778 >            }
779 >            return null;
780 >        }
781 >
782 >        /**
783 >         * Takes next task, if one exists, in order specified by mode.
784 >         */
785 >        final ForkJoinTask<?> nextLocalTask() {
786 >            return mode == 0 ? pop() : poll();
787 >        }
788 >
789 >        /**
790 >         * Returns next task, if one exists, in order specified by mode.
791 >         */
792 >        final ForkJoinTask<?> peek() {
793 >            ForkJoinTask<?>[] a = array; int m;
794 >            if (a == null || (m = a.length - 1) < 0)
795 >                return null;
796 >            int i = mode == 0 ? top - 1 : base;
797 >            int j = ((i & m) << ASHIFT) + ABASE;
798 >            return (ForkJoinTask<?>)U.getObjectVolatile(a, j);
799 >        }
800 >
801 >        /**
802 >         * Pops the given task only if it is at the current top.
803 >         */
804 >        final boolean tryUnpush(ForkJoinTask<?> t) {
805 >            ForkJoinTask<?>[] a; int s;
806 >            if ((a = array) != null && (s = top) != base &&
807 >                U.compareAndSwapObject
808 >                (a, (((a.length - 1) & --s) << ASHIFT) + ABASE, t, null)) {
809 >                top = s;
810 >                return true;
811 >            }
812 >            return false;
813 >        }
814 >
815 >        /**
816 >         * Version of tryUnpush for shared queues; called by non-FJ
817 >         * submitters after prechecking that task probably exists.
818 >         */
819 >        final boolean trySharedUnpush(ForkJoinTask<?> t) {
820 >            boolean success = false;
821 >            if (runState == 0 && U.compareAndSwapInt(this, RUNSTATE, 0, 1)) {
822 >                try {
823 >                    ForkJoinTask<?>[] a; int s;
824 >                    if ((a = array) != null && (s = top) != base &&
825 >                        U.compareAndSwapObject
826 >                        (a, (((a.length - 1) & --s) << ASHIFT) + ABASE, t, null)) {
827 >                        top = s;
828 >                        success = true;
829 >                    }
830 >                } finally {
831 >                    runState = 0;                         // unlock
832 >                }
833 >            }
834 >            return success;
835 >        }
836 >
837 >        /**
838 >         * Polls the given task only if it is at the current base.
839 >         */
840 >        final boolean pollFor(ForkJoinTask<?> task) {
841 >            ForkJoinTask<?>[] a; int b;
842 >            if ((b = base) - top < 0 && (a = array) != null) {
843 >                int j = (((a.length - 1) & b) << ASHIFT) + ABASE;
844 >                if (U.getObjectVolatile(a, j) == task && base == b &&
845 >                    U.compareAndSwapObject(a, j, task, null)) {
846 >                    base = b + 1;
847 >                    return true;
848 >                }
849 >            }
850 >            return false;
851 >        }
852 >
853 >        /**
854 >         * Initializes or doubles the capacity of array. Call either
855 >         * by owner or with lock held -- it is OK for base, but not
856 >         * top, to move while resizings are in progress.
857 >         *
858 >         * @param rejectOnFailure if true, throw exception if capacity
859 >         * exceeded (relayed ultimately to user); else return null.
860 >         */
861 >        final ForkJoinTask<?>[] growArray(boolean rejectOnFailure) {
862 >            ForkJoinTask<?>[] oldA = array;
863 >            int size = oldA != null ? oldA.length << 1 : INITIAL_QUEUE_CAPACITY;
864 >            if (size <= MAXIMUM_QUEUE_CAPACITY) {
865 >                int oldMask, t, b;
866 >                ForkJoinTask<?>[] a = array = new ForkJoinTask<?>[size];
867 >                if (oldA != null && (oldMask = oldA.length - 1) >= 0 &&
868 >                    (t = top) - (b = base) > 0) {
869 >                    int mask = size - 1;
870 >                    do {
871 >                        ForkJoinTask<?> x;
872 >                        int oldj = ((b & oldMask) << ASHIFT) + ABASE;
873 >                        int j    = ((b &    mask) << ASHIFT) + ABASE;
874 >                        x = (ForkJoinTask<?>)U.getObjectVolatile(oldA, oldj);
875 >                        if (x != null &&
876 >                            U.compareAndSwapObject(oldA, oldj, x, null))
877 >                            U.putObjectVolatile(a, j, x);
878 >                    } while (++b != t);
879 >                }
880 >                return a;
881 >            }
882 >            else if (!rejectOnFailure)
883 >                return null;
884 >            else
885 >                throw new RejectedExecutionException("Queue capacity exceeded");
886 >        }
887 >
888 >        /**
889 >         * Removes and cancels all known tasks, ignoring any exceptions.
890 >         */
891 >        final void cancelAll() {
892 >            ForkJoinTask.cancelIgnoringExceptions(currentJoin);
893 >            ForkJoinTask.cancelIgnoringExceptions(currentSteal);
894 >            for (ForkJoinTask<?> t; (t = poll()) != null; )
895 >                ForkJoinTask.cancelIgnoringExceptions(t);
896 >        }
897 >
898 >        /**
899 >         * Computes next value for random probes.  Scans don't require
900 >         * a very high quality generator, but also not a crummy one.
901 >         * Marsaglia xor-shift is cheap and works well enough.  Note:
902 >         * This is manually inlined in its usages in ForkJoinPool to
903 >         * avoid writes inside busy scan loops.
904 >         */
905 >        final int nextSeed() {
906 >            int r = seed;
907 >            r ^= r << 13;
908 >            r ^= r >>> 17;
909 >            return seed = r ^= r << 5;
910 >        }
911 >
912 >        // Specialized execution methods
913 >
914 >        /**
915 >         * Pops and runs tasks until empty.
916 >         */
917 >        private void popAndExecAll() {
918 >            // A bit faster than repeated pop calls
919 >            ForkJoinTask<?>[] a; int m, s; long j; ForkJoinTask<?> t;
920 >            while ((a = array) != null && (m = a.length - 1) >= 0 &&
921 >                   (s = top - 1) - base >= 0 &&
922 >                   (t = ((ForkJoinTask<?>)
923 >                         U.getObject(a, j = ((m & s) << ASHIFT) + ABASE)))
924 >                   != null) {
925 >                if (U.compareAndSwapObject(a, j, t, null)) {
926 >                    top = s;
927 >                    t.doExec();
928 >                }
929 >            }
930 >        }
931 >
932 >        /**
933 >         * Polls and runs tasks until empty.
934 >         */
935 >        private void pollAndExecAll() {
936 >            for (ForkJoinTask<?> t; (t = poll()) != null;)
937 >                t.doExec();
938 >        }
939 >
940 >        /**
941 >         * If present, removes from queue and executes the given task, or
942 >         * any other cancelled task. Returns (true) immediately on any CAS
943 >         * or consistency check failure so caller can retry.
944 >         *
945 >         * @return 0 if no progress can be made, else positive
946 >         * (this unusual convention simplifies use with tryHelpStealer.)
947 >         */
948 >        final int tryRemoveAndExec(ForkJoinTask<?> task) {
949 >            int stat = 1;
950 >            boolean removed = false, empty = true;
951 >            ForkJoinTask<?>[] a; int m, s, b, n;
952 >            if ((a = array) != null && (m = a.length - 1) >= 0 &&
953 >                (n = (s = top) - (b = base)) > 0) {
954 >                for (ForkJoinTask<?> t;;) {           // traverse from s to b
955 >                    int j = ((--s & m) << ASHIFT) + ABASE;
956 >                    t = (ForkJoinTask<?>)U.getObjectVolatile(a, j);
957 >                    if (t == null)                    // inconsistent length
958 >                        break;
959 >                    else if (t == task) {
960 >                        if (s + 1 == top) {           // pop
961 >                            if (!U.compareAndSwapObject(a, j, task, null))
962 >                                break;
963 >                            top = s;
964 >                            removed = true;
965 >                        }
966 >                        else if (base == b)           // replace with proxy
967 >                            removed = U.compareAndSwapObject(a, j, task,
968 >                                                             new EmptyTask());
969 >                        break;
970 >                    }
971 >                    else if (t.status >= 0)
972 >                        empty = false;
973 >                    else if (s + 1 == top) {          // pop and throw away
974 >                        if (U.compareAndSwapObject(a, j, t, null))
975 >                            top = s;
976 >                        break;
977 >                    }
978 >                    if (--n == 0) {
979 >                        if (!empty && base == b)
980 >                            stat = 0;
981 >                        break;
982 >                    }
983 >                }
984 >            }
985 >            if (removed)
986 >                task.doExec();
987 >            return stat;
988 >        }
989 >
990 >        /**
991 >         * Version of shared pop that takes top element only if it
992 >         * its root is the given CountedCompleter.
993 >         */
994 >        final CountedCompleter<?> sharedPopCC(CountedCompleter<?> root) {
995 >            CountedCompleter<?> task = null;
996 >            if (runState == 0 && U.compareAndSwapInt(this, RUNSTATE, 0, 1)) {
997 >                try {
998 >                    ForkJoinTask<?>[] a; int m;
999 >                    if ((a = array) != null && (m = a.length - 1) >= 0) {
1000 >                        outer:for (int s; (s = top - 1) - base >= 0;) {
1001 >                            long j = ((m & s) << ASHIFT) + ABASE;
1002 >                            ForkJoinTask<?> t =
1003 >                                (ForkJoinTask<?>)U.getObject(a, j);
1004 >                            if (t == null || !(t instanceof CountedCompleter))
1005 >                                break;
1006 >                            CountedCompleter<?> cc = (CountedCompleter<?>)t;
1007 >                            for (CountedCompleter<?> q = cc, p;;) {
1008 >                                if (q == root) {
1009 >                                    if (U.compareAndSwapObject(a, j, cc, null)) {
1010 >                                        top = s;
1011 >                                        task = cc;
1012 >                                        break outer;
1013 >                                    }
1014 >                                    break;
1015 >                                }
1016 >                                if ((p = q.completer) == null)
1017 >                                    break outer;
1018 >                                q = p;
1019 >                            }
1020 >                        }
1021 >                    }
1022 >                } finally {
1023 >                    runState = 0;
1024 >                }
1025 >            }
1026 >            return task;
1027 >        }
1028 >
1029 >        /**
1030 >         * Executes a top-level task and any local tasks remaining
1031 >         * after execution.
1032 >         */
1033 >        final void runTask(ForkJoinTask<?> t) {
1034 >            if (t != null) {
1035 >                currentSteal = t;
1036 >                t.doExec();
1037 >                if (top != base) {       // process remaining local tasks
1038 >                    if (mode == 0)
1039 >                        popAndExecAll();
1040 >                    else
1041 >                        pollAndExecAll();
1042 >                }
1043 >                ++nsteals;
1044 >                currentSteal = null;
1045 >            }
1046 >        }
1047 >
1048 >        /**
1049 >         * Executes a non-top-level (stolen) task.
1050 >         */
1051 >        final void runSubtask(ForkJoinTask<?> t) {
1052 >            if (t != null) {
1053 >                ForkJoinTask<?> ps = currentSteal;
1054 >                currentSteal = t;
1055 >                t.doExec();
1056 >                currentSteal = ps;
1057 >            }
1058 >        }
1059 >
1060 >        /**
1061 >         * Returns true if owned and not known to be blocked.
1062 >         */
1063 >        final boolean isApparentlyUnblocked() {
1064 >            Thread wt; Thread.State s;
1065 >            return (eventCount >= 0 &&
1066 >                    (wt = owner) != null &&
1067 >                    (s = wt.getState()) != Thread.State.BLOCKED &&
1068 >                    s != Thread.State.WAITING &&
1069 >                    s != Thread.State.TIMED_WAITING);
1070 >        }
1071 >
1072 >        /**
1073 >         * If this owned and is not already interrupted, try to
1074 >         * interrupt and/or unpark, ignoring exceptions.
1075 >         */
1076 >        final void interruptOwner() {
1077 >            Thread wt, p;
1078 >            if ((wt = owner) != null && !wt.isInterrupted()) {
1079 >                try {
1080 >                    wt.interrupt();
1081 >                } catch (SecurityException ignore) {
1082 >                }
1083 >            }
1084 >            if ((p = parker) != null)
1085 >                U.unpark(p);
1086 >        }
1087 >
1088 >        // Unsafe mechanics
1089 >        private static final sun.misc.Unsafe U;
1090 >        private static final long RUNSTATE;
1091 >        private static final int ABASE;
1092 >        private static final int ASHIFT;
1093 >        static {
1094 >            int s;
1095 >            try {
1096 >                U = getUnsafe();
1097 >                Class<?> k = WorkQueue.class;
1098 >                Class<?> ak = ForkJoinTask[].class;
1099 >                RUNSTATE = U.objectFieldOffset
1100 >                    (k.getDeclaredField("runState"));
1101 >                ABASE = U.arrayBaseOffset(ak);
1102 >                s = U.arrayIndexScale(ak);
1103 >            } catch (Exception e) {
1104 >                throw new Error(e);
1105 >            }
1106 >            if ((s & (s-1)) != 0)
1107 >                throw new Error("data type scale not a power of two");
1108 >            ASHIFT = 31 - Integer.numberOfLeadingZeros(s);
1109 >        }
1110      }
1111  
1112      /**
1113 <     * Generator for assigning sequence numbers as pool names.
1113 >     * Per-thread records for threads that submit to pools. Currently
1114 >     * holds only pseudo-random seed / index that is used to choose
1115 >     * submission queues in method doSubmit. In the future, this may
1116 >     * also incorporate a means to implement different task rejection
1117 >     * and resubmission policies.
1118 >     *
1119 >     * Seeds for submitters and workers/workQueues work in basically
1120 >     * the same way but are initialized and updated using slightly
1121 >     * different mechanics. Both are initialized using the same
1122 >     * approach as in class ThreadLocal, where successive values are
1123 >     * unlikely to collide with previous values. This is done during
1124 >     * registration for workers, but requires a separate AtomicInteger
1125 >     * for submitters. Seeds are then randomly modified upon
1126 >     * collisions using xorshifts, which requires a non-zero seed.
1127       */
1128 <    private static final AtomicInteger poolNumberGenerator =
1129 <        new AtomicInteger();
1128 >    static final class Submitter {
1129 >        int seed;
1130 >        Submitter() {
1131 >            int s = nextSubmitterSeed.getAndAdd(SEED_INCREMENT);
1132 >            seed = (s == 0) ? 1 : s; // ensure non-zero
1133 >        }
1134 >    }
1135 >
1136 >    /** ThreadLocal class for Submitters */
1137 >    static final class ThreadSubmitter extends ThreadLocal<Submitter> {
1138 >        public Submitter initialValue() { return new Submitter(); }
1139 >    }
1140 >
1141 >    // static fields (initialized in static initializer below)
1142  
1143      /**
1144 <     * The time to block in a join (see awaitJoin) before checking if
1145 <     * a new worker should be (re)started to maintain parallelism
423 <     * level. The value should be short enough to maintain global
424 <     * responsiveness and progress but long enough to avoid
425 <     * counterproductive firings during GC stalls or unrelated system
426 <     * activity, and to not bog down systems with continual re-firings
427 <     * on GCs or legitimately long waits.
1144 >     * Creates a new ForkJoinWorkerThread. This factory is used unless
1145 >     * overridden in ForkJoinPool constructors.
1146       */
1147 <    private static final long JOIN_TIMEOUT_MILLIS = 250L; // 4 per second
1147 >    public static final ForkJoinWorkerThreadFactory
1148 >        defaultForkJoinWorkerThreadFactory;
1149 >
1150 >    /** Property prefix for constructing common pool */
1151 >    private static final String propPrefix =
1152 >        "java.util.concurrent.ForkJoinPool.common.";
1153  
1154      /**
1155 <     * The wakeup interval (in nanoseconds) for the oldest worker
1156 <     * worker waiting for an event invokes tryShutdownUnusedWorker to shrink
1157 <     * the number of workers.  The exact value does not matter too
435 <     * much, but should be long enough to slowly release resources
436 <     * during long periods without use without disrupting normal use.
1155 >     * Common (static) pool. Non-null for public use unless a static
1156 >     * construction exception, but internal usages must null-check on
1157 >     * use.
1158       */
1159 <    private static final long SHRINK_RATE_NANOS =
439 <        30L * 1000L * 1000L * 1000L; // 2 per minute
1159 >    static final ForkJoinPool commonPool;
1160  
1161      /**
1162 <     * Absolute bound for parallelism level. Twice this number plus
443 <     * one (i.e., 0xfff) must fit into a 16bit field to enable
444 <     * word-packing for some counts and indices.
1162 >     * Common pool parallelism. Must equal commonPool.parallelism.
1163       */
1164 <    private static final int MAX_WORKERS   = 0x7fff;
1164 >    static final int commonPoolParallelism;
1165  
1166      /**
1167 <     * Array holding all worker threads in the pool.  Array size must
450 <     * be a power of two.  Updates and replacements are protected by
451 <     * workerLock, but the array is always kept in a consistent enough
452 <     * state to be randomly accessed without locking by workers
453 <     * performing work-stealing, as well as other traversal-based
454 <     * methods in this class. All readers must tolerate that some
455 <     * array slots may be null.
1167 >     * Generator for assigning sequence numbers as pool names.
1168       */
1169 <    volatile ForkJoinWorkerThread[] workers;
1169 >    private static final AtomicInteger poolNumberGenerator;
1170  
1171      /**
1172 <     * Queue for external submissions.
1172 >     * Generator for initial hashes/seeds for submitters. Accessed by
1173 >     * Submitter class constructor.
1174       */
1175 <    private final LinkedTransferQueue<ForkJoinTask<?>> submissionQueue;
1175 >    static final AtomicInteger nextSubmitterSeed;
1176  
1177      /**
1178 <     * Lock protecting updates to workers array.
1178 >     * Permission required for callers of methods that may start or
1179 >     * kill threads.
1180       */
1181 <    private final ReentrantLock workerLock;
1181 >    private static final RuntimePermission modifyThreadPermission;
1182  
1183      /**
1184 <     * Latch released upon termination.
1184 >     * Per-thread submission bookkeeping. Shared across all pools
1185 >     * to reduce ThreadLocal pollution and because random motion
1186 >     * to avoid contention in one pool is likely to hold for others.
1187       */
1188 <    private final Phaser termination;
1188 >    private static final ThreadSubmitter submitters;
1189 >
1190 >    // static constants
1191  
1192      /**
1193 <     * Creation factory for worker threads.
1193 >     * Initial timeout value (in nanoseconds) for the thread triggering
1194 >     * quiescence to park waiting for new work. On timeout, the thread
1195 >     * will instead try to shrink the number of workers.
1196       */
1197 <    private final ForkJoinWorkerThreadFactory factory;
1197 >    private static final long IDLE_TIMEOUT      = 1000L * 1000L * 1000L; // 1sec
1198  
1199      /**
1200 <     * Sum of per-thread steal counts, updated only when threads are
481 <     * idle or terminating.
1200 >     * Timeout value when there are more threads than parallelism level
1201       */
1202 <    private volatile long stealCount;
1202 >    private static final long FAST_IDLE_TIMEOUT =  100L * 1000L * 1000L;
1203  
1204      /**
1205 <     * Encoded record of top of Treiber stack of threads waiting for
1206 <     * events. The top 32 bits contain the count being waited for. The
1207 <     * bottom 16 bits contains one plus the pool index of waiting
1208 <     * worker thread. (Bits 16-31 are unused.)
1205 >     * The maximum stolen->joining link depth allowed in method
1206 >     * tryHelpStealer.  Must be a power of two. This value also
1207 >     * controls the maximum number of times to try to help join a task
1208 >     * without any apparent progress or change in pool state before
1209 >     * giving up and blocking (see awaitJoin).  Depths for legitimate
1210 >     * chains are unbounded, but we use a fixed constant to avoid
1211 >     * (otherwise unchecked) cycles and to bound staleness of
1212 >     * traversal parameters at the expense of sometimes blocking when
1213 >     * we could be helping.
1214       */
1215 <    private volatile long eventWaiters;
492 <
493 <    private static final int  EVENT_COUNT_SHIFT = 32;
494 <    private static final long WAITER_ID_MASK    = (1L << 16) - 1L;
1215 >    private static final int MAX_HELP = 64;
1216  
1217      /**
1218 <     * A counter for events that may wake up worker threads:
1219 <     *   - Submission of a new task to the pool
1220 <     *   - A worker pushing a task on an empty queue
1221 <     *   - termination
1218 >     * Secondary time-based bound (in nanosecs) for helping attempts
1219 >     * before trying compensated blocking in awaitJoin. Used in
1220 >     * conjunction with MAX_HELP to reduce variance due to different
1221 >     * polling rates associated with different helping options. The
1222 >     * value should roughly approximate the time required to create
1223 >     * and/or activate a worker thread.
1224       */
1225 <    private volatile int eventCount;
1225 >    private static final long COMPENSATION_DELAY = 1L << 18; // ~0.25 millisec
1226  
1227      /**
1228 <     * Encoded record of top of Treiber stack of spare threads waiting
1229 <     * for resumption. The top 16 bits contain an arbitrary count to
507 <     * avoid ABA effects. The bottom 16bits contains one plus the pool
508 <     * index of waiting worker thread.
1228 >     * Increment for seed generators. See class ThreadLocal for
1229 >     * explanation.
1230       */
1231 <    private volatile int spareWaiters;
511 <
512 <    private static final int SPARE_COUNT_SHIFT = 16;
513 <    private static final int SPARE_ID_MASK     = (1 << 16) - 1;
1231 >    private static final int SEED_INCREMENT = 0x61c88647;
1232  
1233      /**
1234 <     * Lifecycle control. The low word contains the number of workers
1235 <     * that are (probably) executing tasks. This value is atomically
1236 <     * incremented before a worker gets a task to run, and decremented
1237 <     * when worker has no tasks and cannot find any.  Bits 16-18
1238 <     * contain runLevel value. When all are zero, the pool is
1239 <     * running. Level transitions are monotonic (running -> shutdown
1240 <     * -> terminating -> terminated) so each transition adds a bit.
1241 <     * These are bundled together to ensure consistent read for
1242 <     * termination checks (i.e., that runLevel is at least SHUTDOWN
1243 <     * and active threads is zero).
1234 >     * Bits and masks for control variables
1235 >     *
1236 >     * Field ctl is a long packed with:
1237 >     * AC: Number of active running workers minus target parallelism (16 bits)
1238 >     * TC: Number of total workers minus target parallelism (16 bits)
1239 >     * ST: true if pool is terminating (1 bit)
1240 >     * EC: the wait count of top waiting thread (15 bits)
1241 >     * ID: poolIndex of top of Treiber stack of waiters (16 bits)
1242 >     *
1243 >     * When convenient, we can extract the upper 32 bits of counts and
1244 >     * the lower 32 bits of queue state, u = (int)(ctl >>> 32) and e =
1245 >     * (int)ctl.  The ec field is never accessed alone, but always
1246 >     * together with id and st. The offsets of counts by the target
1247 >     * parallelism and the positionings of fields makes it possible to
1248 >     * perform the most common checks via sign tests of fields: When
1249 >     * ac is negative, there are not enough active workers, when tc is
1250 >     * negative, there are not enough total workers, and when e is
1251 >     * negative, the pool is terminating.  To deal with these possibly
1252 >     * negative fields, we use casts in and out of "short" and/or
1253 >     * signed shifts to maintain signedness.
1254 >     *
1255 >     * When a thread is queued (inactivated), its eventCount field is
1256 >     * set negative, which is the only way to tell if a worker is
1257 >     * prevented from executing tasks, even though it must continue to
1258 >     * scan for them to avoid queuing races. Note however that
1259 >     * eventCount updates lag releases so usage requires care.
1260       *
1261 <     * Notes: Most direct CASes are dependent on these bitfield
1262 <     * positions.  Also, this field is non-private to enable direct
1263 <     * performance-sensitive CASes in ForkJoinWorkerThread.
1261 >     * Field runState is an int packed with:
1262 >     * SHUTDOWN: true if shutdown is enabled (1 bit)
1263 >     * SEQ:  a sequence number updated upon (de)registering workers (30 bits)
1264 >     * INIT: set true after workQueues array construction (1 bit)
1265 >     *
1266 >     * The sequence number enables simple consistency checks:
1267 >     * Staleness of read-only operations on the workQueues array can
1268 >     * be checked by comparing runState before vs after the reads.
1269       */
531    volatile int runState;
1270  
1271 <    // Note: The order among run level values matters.
1272 <    private static final int RUNLEVEL_SHIFT     = 16;
1273 <    private static final int SHUTDOWN           = 1 << RUNLEVEL_SHIFT;
1274 <    private static final int TERMINATING        = 1 << (RUNLEVEL_SHIFT + 1);
1275 <    private static final int TERMINATED         = 1 << (RUNLEVEL_SHIFT + 2);
538 <    private static final int ACTIVE_COUNT_MASK  = (1 << RUNLEVEL_SHIFT) - 1;
1271 >    // bit positions/shifts for fields
1272 >    private static final int  AC_SHIFT   = 48;
1273 >    private static final int  TC_SHIFT   = 32;
1274 >    private static final int  ST_SHIFT   = 31;
1275 >    private static final int  EC_SHIFT   = 16;
1276  
1277 <    /**
1278 <     * Holds number of total (i.e., created and not yet terminated)
1279 <     * and running (i.e., not blocked on joins or other managed sync)
1280 <     * threads, packed together to ensure consistent snapshot when
1281 <     * making decisions about creating and suspending spare
1282 <     * threads. Updated only by CAS. Note that adding a new worker
546 <     * requires incrementing both counts, since workers start off in
547 <     * running state.
548 <     */
549 <    private volatile int workerCounts;
1277 >    // bounds
1278 >    private static final int  SMASK      = 0xffff;  // short bits
1279 >    private static final int  MAX_CAP    = 0x7fff;  // max #workers - 1
1280 >    private static final int  SQMASK     = 0xfffe;  // even short bits
1281 >    private static final int  SHORT_SIGN = 1 << 15;
1282 >    private static final int  INT_SIGN   = 1 << 31;
1283  
1284 <    private static final int TOTAL_COUNT_SHIFT  = 16;
1285 <    private static final int RUNNING_COUNT_MASK = (1 << TOTAL_COUNT_SHIFT) - 1;
1286 <    private static final int ONE_RUNNING        = 1;
1287 <    private static final int ONE_TOTAL          = 1 << TOTAL_COUNT_SHIFT;
1284 >    // masks
1285 >    private static final long STOP_BIT   = 0x0001L << ST_SHIFT;
1286 >    private static final long AC_MASK    = ((long)SMASK) << AC_SHIFT;
1287 >    private static final long TC_MASK    = ((long)SMASK) << TC_SHIFT;
1288  
1289 <    /**
1290 <     * The target parallelism level.
1291 <     * Accessed directly by ForkJoinWorkerThreads.
559 <     */
560 <    final int parallelism;
1289 >    // units for incrementing and decrementing
1290 >    private static final long TC_UNIT    = 1L << TC_SHIFT;
1291 >    private static final long AC_UNIT    = 1L << AC_SHIFT;
1292  
1293 <    /**
1294 <     * True if use local fifo, not default lifo, for local polling
1295 <     * Read by, and replicated by ForkJoinWorkerThreads
1296 <     */
1297 <    final boolean locallyFifo;
1293 >    // masks and units for dealing with u = (int)(ctl >>> 32)
1294 >    private static final int  UAC_SHIFT  = AC_SHIFT - 32;
1295 >    private static final int  UTC_SHIFT  = TC_SHIFT - 32;
1296 >    private static final int  UAC_MASK   = SMASK << UAC_SHIFT;
1297 >    private static final int  UTC_MASK   = SMASK << UTC_SHIFT;
1298 >    private static final int  UAC_UNIT   = 1 << UAC_SHIFT;
1299 >    private static final int  UTC_UNIT   = 1 << UTC_SHIFT;
1300  
1301 <    /**
1302 <     * The uncaught exception handler used when any worker abruptly
1303 <     * terminates.
571 <     */
572 <    private final Thread.UncaughtExceptionHandler ueh;
1301 >    // masks and units for dealing with e = (int)ctl
1302 >    private static final int E_MASK      = 0x7fffffff; // no STOP_BIT
1303 >    private static final int E_SEQ       = 1 << EC_SHIFT;
1304  
1305 <    /**
1306 <     * Pool number, just for assigning useful names to worker threads
576 <     */
577 <    private final int poolNumber;
1305 >    // runState bits
1306 >    private static final int SHUTDOWN    = 1 << 31;
1307  
1308 <    // Utilities for CASing fields. Note that most of these
1309 <    // are usually manually inlined by callers
1308 >    // access mode for WorkQueue
1309 >    static final int LIFO_QUEUE          =  0;
1310 >    static final int FIFO_QUEUE          =  1;
1311 >    static final int SHARED_QUEUE        = -1;
1312  
1313 <    /**
583 <     * Increments running count part of workerCounts
584 <     */
585 <    final void incrementRunningCount() {
586 <        int c;
587 <        do {} while (!UNSAFE.compareAndSwapInt(this, workerCountsOffset,
588 <                                               c = workerCounts,
589 <                                               c + ONE_RUNNING));
590 <    }
1313 >    // Instance fields
1314  
1315 <    /**
1316 <     * Tries to decrement running count unless already zero
1317 <     */
1318 <    final boolean tryDecrementRunningCount() {
1319 <        int wc = workerCounts;
1320 <        if ((wc & RUNNING_COUNT_MASK) == 0)
1321 <            return false;
1322 <        return UNSAFE.compareAndSwapInt(this, workerCountsOffset,
1323 <                                        wc, wc - ONE_RUNNING);
1324 <    }
1315 >    /*
1316 >     * Field layout order in this class tends to matter more than one
1317 >     * would like. Runtime layout order is only loosely related to
1318 >     * declaration order and may differ across JVMs, but the following
1319 >     * empirically works OK on current JVMs.
1320 >     */
1321 >
1322 >    volatile long stealCount;                  // collects worker counts
1323 >    volatile long ctl;                         // main pool control
1324 >    final int parallelism;                     // parallelism level
1325 >    final int localMode;                       // per-worker scheduling mode
1326 >    volatile int nextWorkerNumber;             // to create worker name string
1327 >    final int submitMask;                      // submit queue index bound
1328 >    int nextSeed;                              // for initializing worker seeds
1329 >    volatile int mainLock;                     // spinlock for array updates
1330 >    volatile int runState;                     // shutdown status and seq
1331 >    WorkQueue[] workQueues;                    // main registry
1332 >    final ForkJoinWorkerThreadFactory factory; // factory for new workers
1333 >    final Thread.UncaughtExceptionHandler ueh; // per-worker UEH
1334 >    final String workerNamePrefix;             // to create worker name string
1335  
1336 <    /**
1337 <     * Forces decrement of encoded workerCounts, awaiting nonzero if
1338 <     * (rarely) necessary when other count updates lag.
1339 <     *
1340 <     * @param dr -- either zero or ONE_RUNNING
1341 <     * @param dt == either zero or ONE_TOTAL
1342 <     */
1343 <    private void decrementWorkerCounts(int dr, int dt) {
1344 <        for (;;) {
1345 <            int wc = workerCounts;
1346 <            if ((wc & RUNNING_COUNT_MASK)  - dr < 0 ||
1347 <                (wc >>> TOTAL_COUNT_SHIFT) - dt < 0) {
1348 <                if ((runState & TERMINATED) != 0)
1349 <                    return; // lagging termination on a backout
1350 <                Thread.yield();
1336 >    /*
1337 >     * Mechanics for main lock protecting worker array updates.  Uses
1338 >     * the same strategy as ConcurrentHashMap bins -- a spinLock for
1339 >     * normal cases, but falling back to builtin lock when (rarely)
1340 >     * needed.  See internal ConcurrentHashMap documentation for
1341 >     * explanation.
1342 >     */
1343 >
1344 >    static final int LOCK_WAITING = 2; // bit to indicate need for signal
1345 >    static final int MAX_LOCK_SPINS = 1 << 8;
1346 >
1347 >    private void tryAwaitMainLock() {
1348 >        int spins = MAX_LOCK_SPINS, r = 0, h;
1349 >        while (((h = mainLock) & 1) != 0) {
1350 >            if (r == 0)
1351 >                r = ThreadLocalRandom.current().nextInt(); // randomize spins
1352 >            else if (spins >= 0) {
1353 >                r ^= r << 1; r ^= r >>> 3; r ^= r << 10; // xorshift
1354 >                if (r >= 0)
1355 >                    --spins;
1356 >            }
1357 >            else if (U.compareAndSwapInt(this, MAINLOCK, h, h | LOCK_WAITING)) {
1358 >                synchronized (this) {
1359 >                    if ((mainLock & LOCK_WAITING) != 0) {
1360 >                        try {
1361 >                            wait();
1362 >                        } catch (InterruptedException ie) {
1363 >                            try {
1364 >                                Thread.currentThread().interrupt();
1365 >                            } catch (SecurityException ignore) {
1366 >                            }
1367 >                        }
1368 >                    }
1369 >                    else
1370 >                        notifyAll(); // possibly won race vs signaller
1371 >                }
1372 >                break;
1373              }
619            if (UNSAFE.compareAndSwapInt(this, workerCountsOffset,
620                                         wc, wc - (dr + dt)))
621                return;
1374          }
1375      }
1376  
1377 <    /**
626 <     * Tries decrementing active count; fails on contention.
627 <     * Called when workers cannot find tasks to run.
628 <     */
629 <    final boolean tryDecrementActiveCount() {
630 <        int c;
631 <        return UNSAFE.compareAndSwapInt(this, runStateOffset,
632 <                                        c = runState, c - 1);
633 <    }
1377 >    //  Creating, registering, and deregistering workers
1378  
1379      /**
1380 <     * Advances to at least the given level. Returns true if not
637 <     * already in at least the given level.
1380 >     * Tries to create and start a worker
1381       */
1382 <    private boolean advanceRunLevel(int level) {
1383 <        for (;;) {
1384 <            int s = runState;
1385 <            if ((s & level) != 0)
1386 <                return false;
1387 <            if (UNSAFE.compareAndSwapInt(this, runStateOffset, s, s | level))
1388 <                return true;
1382 >    private void addWorker() {
1383 >        Throwable ex = null;
1384 >        ForkJoinWorkerThread wt = null;
1385 >        try {
1386 >            if ((wt = factory.newThread(this)) != null) {
1387 >                wt.start();
1388 >                return;
1389 >            }
1390 >        } catch (Throwable e) {
1391 >            ex = e;
1392          }
1393 +        deregisterWorker(wt, ex); // adjust counts etc on failure
1394      }
1395  
649    // workers array maintenance
650
1396      /**
1397 <     * Records and returns a workers array index for new worker.
1397 >     * Callback from ForkJoinWorkerThread constructor to assign a
1398 >     * public name. This must be separate from registerWorker because
1399 >     * it is called during the "super" constructor call in
1400 >     * ForkJoinWorkerThread.
1401       */
1402 <    private int recordWorker(ForkJoinWorkerThread w) {
1403 <        // Try using slot totalCount-1. If not available, scan and/or resize
1404 <        int k = (workerCounts >>> TOTAL_COUNT_SHIFT) - 1;
1405 <        final ReentrantLock lock = this.workerLock;
1406 <        lock.lock();
659 <        try {
660 <            ForkJoinWorkerThread[] ws = workers;
661 <            int n = ws.length;
662 <            if (k < 0 || k >= n || ws[k] != null) {
663 <                for (k = 0; k < n && ws[k] != null; ++k)
664 <                    ;
665 <                if (k == n)
666 <                    ws = Arrays.copyOf(ws, n << 1);
667 <            }
668 <            ws[k] = w;
669 <            workers = ws; // volatile array write ensures slot visibility
670 <        } finally {
671 <            lock.unlock();
672 <        }
673 <        return k;
1402 >    final String nextWorkerName() {
1403 >        int n;
1404 >        do {} while (!U.compareAndSwapInt(this, NEXTWORKERNUMBER,
1405 >                                          n = nextWorkerNumber, ++n));
1406 >        return workerNamePrefix.concat(Integer.toString(n));
1407      }
1408  
1409      /**
1410 <     * Nulls out record of worker in workers array
1410 >     * Callback from ForkJoinWorkerThread constructor to establish its
1411 >     * poolIndex and record its WorkQueue. To avoid scanning bias due
1412 >     * to packing entries in front of the workQueues array, we treat
1413 >     * the array as a simple power-of-two hash table using per-thread
1414 >     * seed as hash, expanding as needed.
1415 >     *
1416 >     * @param w the worker's queue
1417       */
1418 <    private void forgetWorker(ForkJoinWorkerThread w) {
1419 <        int idx = w.poolIndex;
1420 <        // Locking helps method recordWorker avoid unnecessary expansion
682 <        final ReentrantLock lock = this.workerLock;
683 <        lock.lock();
1418 >    final void registerWorker(WorkQueue w) {
1419 >        while (!U.compareAndSwapInt(this, MAINLOCK, 0, 1))
1420 >            tryAwaitMainLock();
1421          try {
1422 <            ForkJoinWorkerThread[] ws = workers;
1423 <            if (idx >= 0 && idx < ws.length && ws[idx] == w) // verify
1424 <                ws[idx] = null;
1422 >            WorkQueue[] ws;
1423 >            if ((ws = workQueues) == null)
1424 >                ws = workQueues = new WorkQueue[submitMask + 1];
1425 >            if (w != null) {
1426 >                int rs, n =  ws.length, m = n - 1;
1427 >                int s = nextSeed += SEED_INCREMENT; // rarely-colliding sequence
1428 >                w.seed = (s == 0) ? 1 : s;          // ensure non-zero seed
1429 >                int r = (s << 1) | 1;               // use odd-numbered indices
1430 >                if (ws[r &= m] != null) {           // collision
1431 >                    int probes = 0;                 // step by approx half size
1432 >                    int step = (n <= 4) ? 2 : ((n >>> 1) & SQMASK) + 2;
1433 >                    while (ws[r = (r + step) & m] != null) {
1434 >                        if (++probes >= n) {
1435 >                            workQueues = ws = Arrays.copyOf(ws, n <<= 1);
1436 >                            m = n - 1;
1437 >                            probes = 0;
1438 >                        }
1439 >                    }
1440 >                }
1441 >                w.eventCount = w.poolIndex = r;     // establish before recording
1442 >                ws[r] = w;                          // also update seq
1443 >                runState = ((rs = runState) & SHUTDOWN) | ((rs + 2) & ~SHUTDOWN);
1444 >            }
1445          } finally {
1446 <            lock.unlock();
1446 >            if (!U.compareAndSwapInt(this, MAINLOCK, 1, 0)) {
1447 >                mainLock = 0;
1448 >                synchronized (this) { notifyAll(); };
1449 >            }
1450          }
1451      }
1452  
1453      /**
1454 <     * Final callback from terminating worker.  Removes record of
1454 >     * Final callback from terminating worker, as well as upon failure
1455 >     * to construct or start a worker in addWorker.  Removes record of
1456       * worker from array, and adjusts counts. If pool is shutting
1457       * down, tries to complete termination.
1458       *
1459 <     * @param w the worker
1459 >     * @param wt the worker thread or null if addWorker failed
1460 >     * @param ex the exception causing failure, or null if none
1461       */
1462 <    final void workerTerminated(ForkJoinWorkerThread w) {
1463 <        forgetWorker(w);
1464 <        decrementWorkerCounts(w.isTrimmed()? 0 : ONE_RUNNING, ONE_TOTAL);
1465 <        while (w.stealCount != 0) // collect final count
1466 <            tryAccumulateStealCount(w);
1467 <        tryTerminate(false);
1468 <    }
1469 <
1470 <    // Waiting for and signalling events
1471 <
1472 <    /**
1473 <     * Releases workers blocked on a count not equal to current count.
1474 <     * Normally called after precheck that eventWaiters isn't zero to
1475 <     * avoid wasted array checks. Gives up upon a change in count or
1476 <     * upon releasing two workers, letting others take over.
1477 <     */
1478 <    private void releaseEventWaiters() {
1479 <        ForkJoinWorkerThread[] ws = workers;
1480 <        int n = ws.length;
719 <        long h = eventWaiters;
720 <        int ec = eventCount;
721 <        boolean releasedOne = false;
722 <        ForkJoinWorkerThread w; int id;
723 <        while ((id = ((int)(h & WAITER_ID_MASK)) - 1) >= 0 &&
724 <               (int)(h >>> EVENT_COUNT_SHIFT) != ec &&
725 <               id < n && (w = ws[id]) != null) {
726 <            if (UNSAFE.compareAndSwapLong(this, eventWaitersOffset,
727 <                                          h,  w.nextWaiter)) {
728 <                LockSupport.unpark(w);
729 <                if (releasedOne) // exit on second release
730 <                    break;
731 <                releasedOne = true;
1462 >    final void deregisterWorker(ForkJoinWorkerThread wt, Throwable ex) {
1463 >        WorkQueue w = null;
1464 >        if (wt != null && (w = wt.workQueue) != null) {
1465 >            w.runState = -1;                // ensure runState is set
1466 >            long steals = w.totalSteals + w.nsteals, sc;
1467 >            do {} while (!U.compareAndSwapLong(this, STEALCOUNT,
1468 >                                               sc = stealCount, sc + steals));
1469 >            int idx = w.poolIndex;
1470 >            while (!U.compareAndSwapInt(this, MAINLOCK, 0, 1))
1471 >                tryAwaitMainLock();
1472 >            try {
1473 >                WorkQueue[] ws = workQueues;
1474 >                if (ws != null && idx >= 0 && idx < ws.length && ws[idx] == w)
1475 >                    ws[idx] = null;
1476 >            } finally {
1477 >                if (!U.compareAndSwapInt(this, MAINLOCK, 1, 0)) {
1478 >                    mainLock = 0;
1479 >                    synchronized (this) { notifyAll(); };
1480 >                }
1481              }
1482 <            if (eventCount != ec)
1483 <                break;
1484 <            h = eventWaiters;
1482 >        }
1483 >
1484 >        long c;                             // adjust ctl counts
1485 >        do {} while (!U.compareAndSwapLong
1486 >                     (this, CTL, c = ctl, (((c - AC_UNIT) & AC_MASK) |
1487 >                                           ((c - TC_UNIT) & TC_MASK) |
1488 >                                           (c & ~(AC_MASK|TC_MASK)))));
1489 >
1490 >        if (!tryTerminate(false, false) && w != null) {
1491 >            w.cancelAll();                  // cancel remaining tasks
1492 >            if (w.array != null)            // suppress signal if never ran
1493 >                signalWork();               // wake up or create replacement
1494 >            if (ex == null)                 // help clean refs on way out
1495 >                ForkJoinTask.helpExpungeStaleExceptions();
1496 >        }
1497 >
1498 >        if (ex != null)                     // rethrow
1499 >            ForkJoinTask.rethrow(ex);
1500 >    }
1501 >
1502 >    // Submissions
1503 >
1504 >    /**
1505 >     * Unless shutting down, adds the given task to a submission queue
1506 >     * at submitter's current queue index (modulo submission
1507 >     * range). If no queue exists at the index, one is created.  If
1508 >     * the queue is busy, another index is randomly chosen. The
1509 >     * submitMask bounds the effective number of queues to the
1510 >     * (nearest power of two for) parallelism level.
1511 >     *
1512 >     * @param task the task. Caller must ensure non-null.
1513 >     */
1514 >    private void doSubmit(ForkJoinTask<?> task) {
1515 >        Submitter s = submitters.get();
1516 >        for (int r = s.seed, m = submitMask;;) {
1517 >            WorkQueue[] ws; WorkQueue q;
1518 >            int k = r & m & SQMASK;          // use only even indices
1519 >            if (runState < 0)
1520 >                throw new RejectedExecutionException(); // shutting down
1521 >            else if ((ws = workQueues) == null || ws.length <= k) {
1522 >                while (!U.compareAndSwapInt(this, MAINLOCK, 0, 1))
1523 >                    tryAwaitMainLock();
1524 >                try {
1525 >                    if (workQueues == null)
1526 >                        workQueues = new WorkQueue[submitMask + 1];
1527 >                } finally {
1528 >                    if (!U.compareAndSwapInt(this, MAINLOCK, 1, 0)) {
1529 >                        mainLock = 0;
1530 >                        synchronized (this) { notifyAll(); };
1531 >                    }
1532 >                }
1533 >            }
1534 >            else if ((q = ws[k]) == null) {  // create new queue
1535 >                WorkQueue nq = new WorkQueue(this, null, SHARED_QUEUE);
1536 >                while (!U.compareAndSwapInt(this, MAINLOCK, 0, 1))
1537 >                    tryAwaitMainLock();
1538 >                try {
1539 >                    int rs = runState;       // to update seq
1540 >                    if (ws == workQueues && ws[k] == null) {
1541 >                        ws[k] = nq;
1542 >                        runState = ((rs & SHUTDOWN) | ((rs + 2) & ~SHUTDOWN));
1543 >                    }
1544 >                } finally {
1545 >                    if (!U.compareAndSwapInt(this, MAINLOCK, 1, 0)) {
1546 >                        mainLock = 0;
1547 >                        synchronized (this) { notifyAll(); };
1548 >                    }
1549 >                }
1550 >            }
1551 >            else if (q.trySharedPush(task)) {
1552 >                signalWork();
1553 >                return;
1554 >            }
1555 >            else if (m > 1) {                // move to a different index
1556 >                r ^= r << 13;                // same xorshift as WorkQueues
1557 >                r ^= r >>> 17;
1558 >                s.seed = r ^= r << 5;
1559 >            }
1560 >            else
1561 >                Thread.yield();              // yield if no alternatives
1562          }
1563      }
1564  
1565      /**
1566 <     * Tries to advance eventCount and releases waiters. Called only
741 <     * from workers.
1566 >     * Submits the given (non-null) task to the common pool, if possible.
1567       */
1568 <    final void signalWork() {
1569 <        int c; // try to increment event count -- CAS failure OK
1570 <        UNSAFE.compareAndSwapInt(this, eventCountOffset, c = eventCount, c+1);
1571 <        if (eventWaiters != 0L)
1572 <            releaseEventWaiters();
1568 >    static void submitToCommonPool(ForkJoinTask<?> task) {
1569 >        ForkJoinPool p;
1570 >        if ((p = commonPool) == null)
1571 >            throw new RejectedExecutionException("Common Pool Unavailable");
1572 >        p.doSubmit(task);
1573      }
1574  
1575      /**
1576 <     * Adds the given worker to event queue and blocks until
1577 <     * terminating or event count advances from the given value
1578 <     *
1579 <     * @param w the calling worker thread
1580 <     * @param ec the count
1581 <     */
1582 <    private void eventSync(ForkJoinWorkerThread w, int ec) {
1583 <        long nh = (((long)ec) << EVENT_COUNT_SHIFT) | ((long)(w.poolIndex+1));
1584 <        long h;
1585 <        while ((runState < SHUTDOWN || !tryTerminate(false)) &&
1586 <               (((int)((h = eventWaiters) & WAITER_ID_MASK)) == 0 ||
1587 <                (int)(h >>> EVENT_COUNT_SHIFT) == ec) &&
1588 <               eventCount == ec) {
1589 <            if (UNSAFE.compareAndSwapLong(this, eventWaitersOffset,
1590 <                                          w.nextWaiter = h, nh)) {
1591 <                awaitEvent(w, ec);
1592 <                break;
1576 >     * Returns true if the given task was submitted to common pool
1577 >     * and has not yet commenced execution, and is available for
1578 >     * removal according to execution policies; if so removing the
1579 >     * submission from the pool.
1580 >     *
1581 >     * @param task the task
1582 >     * @return true if successful
1583 >     */
1584 >    static boolean tryUnsubmitFromCommonPool(ForkJoinTask<?> task) {
1585 >        // If not oversaturating platform, peek, looking for task and
1586 >        // eligibility before using trySharedUnpush to actually take
1587 >        // it under lock
1588 >        ForkJoinPool p; WorkQueue[] ws; WorkQueue w, q;
1589 >        ForkJoinTask<?>[] a; int ac, s, m;
1590 >        if ((p = commonPool) != null && (ws = p.workQueues) != null) {
1591 >            int k = submitters.get().seed & p.submitMask & SQMASK;
1592 >            if ((m = ws.length - 1) >= k && (q = ws[k]) != null &&
1593 >                (ac = (int)(p.ctl >> AC_SHIFT)) <= 0) {
1594 >                if (ac == 0) { // double check if all workers active
1595 >                    for (int i = 1; i <= m; i += 2) {
1596 >                        if ((w = ws[i]) != null && w.parker != null) {
1597 >                            ac = -1;
1598 >                            break;
1599 >                        }
1600 >                    }
1601 >                }
1602 >                return (ac < 0 && (a = q.array) != null &&
1603 >                        (s = q.top - 1) - q.base >= 0 &&
1604 >                        s >= 0 && s < a.length &&
1605 >                        a[s] == task &&
1606 >                        q.trySharedUnpush(task));
1607              }
1608          }
1609 +        return false;
1610      }
1611  
1612      /**
1613 <     * Blocks the given worker (that has already been entered as an
1614 <     * event waiter) until terminating or event count advances from
1615 <     * the given value. The oldest (first) waiter uses a timed wait to
1616 <     * occasionally one-by-one shrink the number of workers (to a
1617 <     * minimum of one) if the pool has not been used for extended
1618 <     * periods.
1619 <     *
1620 <     * @param w the calling worker thread
1621 <     * @param ec the count
1622 <     */
1623 <    private void awaitEvent(ForkJoinWorkerThread w, int ec) {
1624 <        while (eventCount == ec) {
1625 <            if (tryAccumulateStealCount(w)) { // transfer while idle
1626 <                boolean untimed = (w.nextWaiter != 0L ||
1627 <                                   (workerCounts & RUNNING_COUNT_MASK) <= 1);
1628 <                long startTime = untimed? 0 : System.nanoTime();
1629 <                Thread.interrupted();         // clear/ignore interrupt
1630 <                if (eventCount != ec || w.runState != 0 ||
791 <                    runState >= TERMINATING)  // recheck after clear
792 <                    break;
793 <                if (untimed)
794 <                    LockSupport.park(w);
795 <                else {
796 <                    LockSupport.parkNanos(w, SHRINK_RATE_NANOS);
797 <                    if (eventCount != ec || w.runState != 0 ||
798 <                        runState >= TERMINATING)
799 <                        break;
800 <                    if (System.nanoTime() - startTime >= SHRINK_RATE_NANOS)
801 <                        tryShutdownUnusedWorker(ec);
1613 >     * Tries to pop and run a task within same computation from common pool
1614 >     */
1615 >    static void popAndExecCCFromCommonPool(CountedCompleter<?> cc) {
1616 >        ForkJoinPool p; WorkQueue[] ws; WorkQueue q, w; int m, ac;
1617 >        CountedCompleter<?> par, task;
1618 >        if ((p = commonPool) != null && (ws = p.workQueues) != null) {
1619 >            while ((par = cc.completer) != null) // find root
1620 >                cc = par;
1621 >            int k = submitters.get().seed & p.submitMask & SQMASK;
1622 >            if ((m = ws.length - 1) >= k && (q = ws[k]) != null &&
1623 >                (ac = (int)(p.ctl >> AC_SHIFT)) <= 0) {
1624 >                if (ac == 0) {
1625 >                    for (int i = 1; i <= m; i += 2) {
1626 >                        if ((w = ws[i]) != null && w.parker != null) {
1627 >                            ac = -1;
1628 >                            break;
1629 >                        }
1630 >                    }
1631                  }
1632 +                if (ac < 0 && q.top - q.base > 0 &&
1633 +                    (task = q.sharedPopCC(cc)) != null)
1634 +                    task.exec();
1635              }
1636          }
1637      }
1638  
1639 <    // Maintaining parallelism
1639 >    // Maintaining ctl counts
1640  
1641      /**
1642 <     * Pushes worker onto the spare stack
1642 >     * Increments active count; mainly called upon return from blocking.
1643       */
1644 <    final void pushSpare(ForkJoinWorkerThread w) {
1645 <        int ns = (++w.spareCount << SPARE_COUNT_SHIFT) | (w.poolIndex + 1);
1646 <        do {} while (!UNSAFE.compareAndSwapInt(this, spareWaitersOffset,
815 <                                               w.nextSpare = spareWaiters,ns));
1644 >    final void incrementActiveCount() {
1645 >        long c;
1646 >        do {} while (!U.compareAndSwapLong(this, CTL, c = ctl, c + AC_UNIT));
1647      }
1648  
1649      /**
1650 <     * Tries (once) to resume a spare if the number of running
820 <     * threads is less than target.
1650 >     * Tries to create one or activate one or more workers if too few are active.
1651       */
1652 <    private void tryResumeSpare() {
1653 <        int sw, id;
1654 <        ForkJoinWorkerThread[] ws = workers;
1655 <        int n = ws.length;
1656 <        ForkJoinWorkerThread w;
1657 <        if ((sw = spareWaiters) != 0 &&
1658 <            (id = (sw & SPARE_ID_MASK) - 1) >= 0 &&
1659 <            id < n && (w = ws[id]) != null &&
1660 <            (workerCounts & RUNNING_COUNT_MASK) < parallelism &&
1661 <            spareWaiters == sw &&
1662 <            UNSAFE.compareAndSwapInt(this, spareWaitersOffset,
1663 <                                     sw, w.nextSpare)) {
1664 <            int c; // increment running count before resume
1665 <            do {} while(!UNSAFE.compareAndSwapInt
1666 <                        (this, workerCountsOffset,
1667 <                         c = workerCounts, c + ONE_RUNNING));
1668 <            if (w.tryUnsuspend())
1669 <                LockSupport.unpark(w);
1670 <            else   // back out if w was shutdown
1671 <                decrementWorkerCounts(ONE_RUNNING, 0);
1652 >    final void signalWork() {
1653 >        long c; int u;
1654 >        while ((u = (int)((c = ctl) >>> 32)) < 0) {     // too few active
1655 >            WorkQueue[] ws = workQueues; int e, i; WorkQueue w; Thread p;
1656 >            if ((e = (int)c) > 0) {                     // at least one waiting
1657 >                if (ws != null && (i = e & SMASK) < ws.length &&
1658 >                    (w = ws[i]) != null && w.eventCount == (e | INT_SIGN)) {
1659 >                    long nc = (((long)(w.nextWait & E_MASK)) |
1660 >                               ((long)(u + UAC_UNIT) << 32));
1661 >                    if (U.compareAndSwapLong(this, CTL, c, nc)) {
1662 >                        w.eventCount = (e + E_SEQ) & E_MASK;
1663 >                        if ((p = w.parker) != null)
1664 >                            U.unpark(p);                // activate and release
1665 >                        break;
1666 >                    }
1667 >                }
1668 >                else
1669 >                    break;
1670 >            }
1671 >            else if (e == 0 && (u & SHORT_SIGN) != 0) { // too few total
1672 >                long nc = (long)(((u + UTC_UNIT) & UTC_MASK) |
1673 >                                 ((u + UAC_UNIT) & UAC_MASK)) << 32;
1674 >                if (U.compareAndSwapLong(this, CTL, c, nc)) {
1675 >                    addWorker();
1676 >                    break;
1677 >                }
1678 >            }
1679 >            else
1680 >                break;
1681          }
1682      }
1683  
1684 +    // Scanning for tasks
1685 +
1686      /**
1687 <     * Tries to increase the number of running workers if below target
847 <     * parallelism: If a spare exists tries to resume it via
848 <     * tryResumeSpare.  Otherwise, if not enough total workers or all
849 <     * existing workers are busy, adds a new worker. In all cases also
850 <     * helps wake up releasable workers waiting for work.
1687 >     * Top-level runloop for workers, called by ForkJoinWorkerThread.run.
1688       */
1689 <    private void helpMaintainParallelism() {
1690 <        int pc = parallelism;
1691 <        int wc, rs, tc;
1692 <        while (((wc = workerCounts) & RUNNING_COUNT_MASK) < pc &&
1693 <               (rs = runState) < TERMINATING) {
1694 <            if (spareWaiters != 0)
1695 <                tryResumeSpare();
1696 <            else if ((tc = wc >>> TOTAL_COUNT_SHIFT) >= MAX_WORKERS ||
1697 <                     (tc >= pc && (rs & ACTIVE_COUNT_MASK) != tc))
1698 <                break;   // enough total
1699 <            else if (runState == rs && workerCounts == wc &&
1700 <                     UNSAFE.compareAndSwapInt(this, workerCountsOffset, wc,
1701 <                                              wc + (ONE_RUNNING|ONE_TOTAL))) {
1702 <                ForkJoinWorkerThread w = null;
1703 <                try {
1704 <                    w = factory.newThread(this);
1705 <                } finally { // adjust on null or exceptional factory return
1706 <                    if (w == null) {
1707 <                        decrementWorkerCounts(ONE_RUNNING, ONE_TOTAL);
1708 <                        tryTerminate(false); // handle failure during shutdown
1689 >    final void runWorker(WorkQueue w) {
1690 >        w.growArray(false);         // initialize queue array in this thread
1691 >        do { w.runTask(scan(w)); } while (w.runState >= 0);
1692 >    }
1693 >
1694 >    /**
1695 >     * Scans for and, if found, returns one task, else possibly
1696 >     * inactivates the worker. This method operates on single reads of
1697 >     * volatile state and is designed to be re-invoked continuously,
1698 >     * in part because it returns upon detecting inconsistencies,
1699 >     * contention, or state changes that indicate possible success on
1700 >     * re-invocation.
1701 >     *
1702 >     * The scan searches for tasks across a random permutation of
1703 >     * queues (starting at a random index and stepping by a random
1704 >     * relative prime, checking each at least once).  The scan
1705 >     * terminates upon either finding a non-empty queue, or completing
1706 >     * the sweep. If the worker is not inactivated, it takes and
1707 >     * returns a task from this queue.  On failure to find a task, we
1708 >     * take one of the following actions, after which the caller will
1709 >     * retry calling this method unless terminated.
1710 >     *
1711 >     * * If pool is terminating, terminate the worker.
1712 >     *
1713 >     * * If not a complete sweep, try to release a waiting worker.  If
1714 >     * the scan terminated because the worker is inactivated, then the
1715 >     * released worker will often be the calling worker, and it can
1716 >     * succeed obtaining a task on the next call. Or maybe it is
1717 >     * another worker, but with same net effect. Releasing in other
1718 >     * cases as well ensures that we have enough workers running.
1719 >     *
1720 >     * * If not already enqueued, try to inactivate and enqueue the
1721 >     * worker on wait queue. Or, if inactivating has caused the pool
1722 >     * to be quiescent, relay to idleAwaitWork to check for
1723 >     * termination and possibly shrink pool.
1724 >     *
1725 >     * * If already inactive, and the caller has run a task since the
1726 >     * last empty scan, return (to allow rescan) unless others are
1727 >     * also inactivated.  Field WorkQueue.rescans counts down on each
1728 >     * scan to ensure eventual inactivation and blocking.
1729 >     *
1730 >     * * If already enqueued and none of the above apply, park
1731 >     * awaiting signal,
1732 >     *
1733 >     * @param w the worker (via its WorkQueue)
1734 >     * @return a task or null if none found
1735 >     */
1736 >    private final ForkJoinTask<?> scan(WorkQueue w) {
1737 >        WorkQueue[] ws;                       // first update random seed
1738 >        int r = w.seed; r ^= r << 13; r ^= r >>> 17; w.seed = r ^= r << 5;
1739 >        int rs = runState, m;                 // volatile read order matters
1740 >        if ((ws = workQueues) != null && (m = ws.length - 1) > 0) {
1741 >            int ec = w.eventCount;            // ec is negative if inactive
1742 >            int step = (r >>> 16) | 1;        // relative prime
1743 >            for (int j = (m + 1) << 2; ; r += step) {
1744 >                WorkQueue q; ForkJoinTask<?> t; ForkJoinTask<?>[] a; int b;
1745 >                if ((q = ws[r & m]) != null && (b = q.base) - q.top < 0 &&
1746 >                    (a = q.array) != null) {  // probably nonempty
1747 >                    int i = (((a.length - 1) & b) << ASHIFT) + ABASE;
1748 >                    t = (ForkJoinTask<?>)U.getObjectVolatile(a, i);
1749 >                    if (q.base == b && ec >= 0 && t != null &&
1750 >                        U.compareAndSwapObject(a, i, t, null)) {
1751 >                        if (q.top - (q.base = b + 1) > 0)
1752 >                            signalWork();    // help pushes signal
1753 >                        return t;
1754 >                    }
1755 >                    else if (ec < 0 || j <= m) {
1756 >                        rs = 0;               // mark scan as imcomplete
1757 >                        break;                // caller can retry after release
1758                      }
1759                  }
1760 <                if (w == null)
875 <                    break;
876 <                w.start(recordWorker(w), ueh);
877 <                if ((workerCounts >>> TOTAL_COUNT_SHIFT) >= pc) {
878 <                    int c; // advance event count
879 <                    UNSAFE.compareAndSwapInt(this, eventCountOffset,
880 <                                             c = eventCount, c+1);
881 <                    break; // add at most one unless total below target
882 <                }
883 <            }
884 <        }
885 <        if (eventWaiters != 0L)
886 <            releaseEventWaiters();
887 <    }
888 <
889 <    /**
890 <     * Callback from the oldest waiter in awaitEvent waking up after a
891 <     * period of non-use. If all workers are idle, tries (once) to
892 <     * shutdown an event waiter or a spare, if one exists. Note that
893 <     * we don't need CAS or locks here because the method is called
894 <     * only from one thread occasionally waking (and even misfires are
895 <     * OK). Note that until the shutdown worker fully terminates,
896 <     * workerCounts will overestimate total count, which is tolerable.
897 <     *
898 <     * @param ec the event count waited on by caller (to abort
899 <     * attempt if count has since changed).
900 <     */
901 <    private void tryShutdownUnusedWorker(int ec) {
902 <        if (runState == 0 && eventCount == ec) { // only trigger if all idle
903 <            ForkJoinWorkerThread[] ws = workers;
904 <            int n = ws.length;
905 <            ForkJoinWorkerThread w = null;
906 <            boolean shutdown = false;
907 <            int sw;
908 <            long h;
909 <            if ((sw = spareWaiters) != 0) { // prefer killing spares
910 <                int id = (sw & SPARE_ID_MASK) - 1;
911 <                if (id >= 0 && id < n && (w = ws[id]) != null &&
912 <                    UNSAFE.compareAndSwapInt(this, spareWaitersOffset,
913 <                                             sw, w.nextSpare))
914 <                    shutdown = true;
915 <            }
916 <            else if ((h = eventWaiters) != 0L) {
917 <                long nh;
918 <                int id = ((int)(h & WAITER_ID_MASK)) - 1;
919 <                if (id >= 0 && id < n && (w = ws[id]) != null &&
920 <                    (nh = w.nextWaiter) != 0L && // keep at least one worker
921 <                    UNSAFE.compareAndSwapLong(this, eventWaitersOffset, h, nh))
922 <                    shutdown = true;
923 <            }
924 <            if (w != null && shutdown) {
925 <                w.shutdown();
926 <                LockSupport.unpark(w);
927 <            }
928 <        }
929 <        releaseEventWaiters(); // in case of interference
930 <    }
931 <
932 <    /**
933 <     * Callback from workers invoked upon each top-level action (i.e.,
934 <     * stealing a task or taking a submission and running it).
935 <     * Performs one or more of the following:
936 <     *
937 <     * 1. If the worker is active and either did not run a task
938 <     *    or there are too many workers, try to set its active status
939 <     *    to inactive and update activeCount. On contention, we may
940 <     *    try again in this or a subsequent call.
941 <     *
942 <     * 2. If not enough total workers, help create some.
943 <     *
944 <     * 3. If there are too many running workers, suspend this worker
945 <     *    (first forcing inactive if necessary).  If it is not needed,
946 <     *    it may be shutdown while suspended (via
947 <     *    tryShutdownUnusedWorker).  Otherwise, upon resume it
948 <     *    rechecks running thread count and need for event sync.
949 <     *
950 <     * 4. If worker did not run a task, await the next task event via
951 <     *    eventSync if necessary (first forcing inactivation), upon
952 <     *    which the worker may be shutdown via
953 <     *    tryShutdownUnusedWorker.  Otherwise, help release any
954 <     *    existing event waiters that are now releasable,
955 <     *
956 <     * @param w the worker
957 <     * @param ran true if worker ran a task since last call to this method
958 <     */
959 <    final void preStep(ForkJoinWorkerThread w, boolean ran) {
960 <        int wec = w.lastEventCount;
961 <        boolean active = w.active;
962 <        boolean inactivate = false;
963 <        int pc = parallelism;
964 <        int rs;
965 <        while (w.runState == 0 && (rs = runState) < TERMINATING) {
966 <            if ((inactivate || (active && (rs & ACTIVE_COUNT_MASK) >= pc)) &&
967 <                UNSAFE.compareAndSwapInt(this, runStateOffset, rs, rs - 1))
968 <                inactivate = active = w.active = false;
969 <            int wc = workerCounts;
970 <            if ((wc & RUNNING_COUNT_MASK) > pc) {
971 <                if (!(inactivate |= active) && // must inactivate to suspend
972 <                    workerCounts == wc &&      // try to suspend as spare
973 <                    UNSAFE.compareAndSwapInt(this, workerCountsOffset,
974 <                                             wc, wc - ONE_RUNNING))
975 <                    w.suspendAsSpare();
976 <            }
977 <            else if ((wc >>> TOTAL_COUNT_SHIFT) < pc)
978 <                helpMaintainParallelism();     // not enough workers
979 <            else if (!ran) {
980 <                long h = eventWaiters;
981 <                int ec = eventCount;
982 <                if (h != 0L && (int)(h >>> EVENT_COUNT_SHIFT) != ec)
983 <                    releaseEventWaiters();     // release others before waiting
984 <                else if (ec != wec) {
985 <                    w.lastEventCount = ec;     // no need to wait
1760 >                if (--j < 0)
1761                      break;
1762 +            }
1763 +
1764 +            long c = ctl; int e = (int)c, a = (int)(c >> AC_SHIFT), nr, ns;
1765 +            if (e < 0)                        // decode ctl on empty scan
1766 +                w.runState = -1;              // pool is terminating
1767 +            else if (rs == 0 || rs != runState) { // incomplete scan
1768 +                WorkQueue v; Thread p;        // try to release a waiter
1769 +                if (e > 0 && a < 0 && w.eventCount == ec &&
1770 +                    (v = ws[e & m]) != null && v.eventCount == (e | INT_SIGN)) {
1771 +                    long nc = ((long)(v.nextWait & E_MASK) |
1772 +                               ((c + AC_UNIT) & (AC_MASK|TC_MASK)));
1773 +                    if (ctl == c && U.compareAndSwapLong(this, CTL, c, nc)) {
1774 +                        v.eventCount = (e + E_SEQ) & E_MASK;
1775 +                        if ((p = v.parker) != null)
1776 +                            U.unpark(p);
1777 +                    }
1778 +                }
1779 +            }
1780 +            else if (ec >= 0) {               // try to enqueue/inactivate
1781 +                long nc = (long)ec | ((c - AC_UNIT) & (AC_MASK|TC_MASK));
1782 +                w.nextWait = e;
1783 +                w.eventCount = ec | INT_SIGN; // mark as inactive
1784 +                if (ctl != c || !U.compareAndSwapLong(this, CTL, c, nc))
1785 +                    w.eventCount = ec;        // unmark on CAS failure
1786 +                else {
1787 +                    if ((ns = w.nsteals) != 0) {
1788 +                        w.nsteals = 0;        // set rescans if ran task
1789 +                        w.rescans = (a > 0) ? 0 : a + parallelism;
1790 +                        w.totalSteals += ns;
1791 +                    }
1792 +                    if (a == 1 - parallelism) // quiescent
1793 +                        idleAwaitWork(w, nc, c);
1794 +                }
1795 +            }
1796 +            else if (w.eventCount < 0) {      // already queued
1797 +                int ac = a + parallelism;
1798 +                if ((nr = w.rescans) > 0)     // continue rescanning
1799 +                    w.rescans = (ac < nr) ? ac : nr - 1;
1800 +                else if (((w.seed >>> 16) & ac) == 0) { // randomize park
1801 +                    Thread.interrupted();     // clear status
1802 +                    Thread wt = Thread.currentThread();
1803 +                    U.putObject(wt, PARKBLOCKER, this);
1804 +                    w.parker = wt;            // emulate LockSupport.park
1805 +                    if (w.eventCount < 0)     // recheck
1806 +                        U.park(false, 0L);
1807 +                    w.parker = null;
1808 +                    U.putObject(wt, PARKBLOCKER, null);
1809                  }
988                else if (!(inactivate |= active))
989                    eventSync(w, wec);         // must inactivate before sync
1810              }
991            else
992                break;
1811          }
1812 +        return null;
1813      }
1814  
1815      /**
1816 <     * Helps and/or blocks awaiting join of the given task.
1817 <     * See above for explanation.
1818 <     *
1819 <     * @param joinMe the task to join
1820 <     * @param worker the current worker thread
1821 <     */
1822 <    final void awaitJoin(ForkJoinTask<?> joinMe, ForkJoinWorkerThread worker) {
1823 <        int retries = 2 + (parallelism >> 2); // #helpJoins before blocking
1824 <        while (joinMe.status >= 0) {
1825 <            int wc;
1826 <            worker.helpJoinTask(joinMe);
1827 <            if (joinMe.status < 0)
1828 <                break;
1829 <            else if (retries > 0)
1830 <                --retries;
1831 <            else if (((wc = workerCounts) & RUNNING_COUNT_MASK) != 0 &&
1832 <                     UNSAFE.compareAndSwapInt(this, workerCountsOffset,
1833 <                                              wc, wc - ONE_RUNNING)) {
1834 <                int stat, c; long h;
1835 <                while ((stat = joinMe.status) >= 0 &&
1836 <                       (h = eventWaiters) != 0L && // help release others
1837 <                       (int)(h >>> EVENT_COUNT_SHIFT) != eventCount)
1838 <                    releaseEventWaiters();
1839 <                if (stat >= 0 &&
1840 <                    ((workerCounts & RUNNING_COUNT_MASK) == 0 ||
1841 <                     (stat =
1842 <                      joinMe.internalAwaitDone(JOIN_TIMEOUT_MILLIS)) >= 0))
1843 <                    helpMaintainParallelism(); // timeout or no running workers
1844 <                do {} while (!UNSAFE.compareAndSwapInt
1845 <                             (this, workerCountsOffset,
1846 <                              c = workerCounts, c + ONE_RUNNING));
1847 <                if (stat < 0)
1848 <                    break;   // else restart
1816 >     * If inactivating worker w has caused the pool to become
1817 >     * quiescent, checks for pool termination, and, so long as this is
1818 >     * not the only worker, waits for event for up to a given
1819 >     * duration.  On timeout, if ctl has not changed, terminates the
1820 >     * worker, which will in turn wake up another worker to possibly
1821 >     * repeat this process.
1822 >     *
1823 >     * @param w the calling worker
1824 >     * @param currentCtl the ctl value triggering possible quiescence
1825 >     * @param prevCtl the ctl value to restore if thread is terminated
1826 >     */
1827 >    private void idleAwaitWork(WorkQueue w, long currentCtl, long prevCtl) {
1828 >        if (w.eventCount < 0 && !tryTerminate(false, false) &&
1829 >            (int)prevCtl != 0 && !hasQueuedSubmissions() && ctl == currentCtl) {
1830 >            int dc = -(short)(currentCtl >>> TC_SHIFT);
1831 >            long parkTime = dc < 0 ? FAST_IDLE_TIMEOUT: (dc + 1) * IDLE_TIMEOUT;
1832 >            long deadline = System.nanoTime() + parkTime - 100000L; // 1ms slop
1833 >            Thread wt = Thread.currentThread();
1834 >            while (ctl == currentCtl) {
1835 >                Thread.interrupted();  // timed variant of version in scan()
1836 >                U.putObject(wt, PARKBLOCKER, this);
1837 >                w.parker = wt;
1838 >                if (ctl == currentCtl)
1839 >                    U.park(false, parkTime);
1840 >                w.parker = null;
1841 >                U.putObject(wt, PARKBLOCKER, null);
1842 >                if (ctl != currentCtl)
1843 >                    break;
1844 >                if (deadline - System.nanoTime() <= 0L &&
1845 >                    U.compareAndSwapLong(this, CTL, currentCtl, prevCtl)) {
1846 >                    w.eventCount = (w.eventCount + E_SEQ) | E_MASK;
1847 >                    w.runState = -1;   // shrink
1848 >                    break;
1849 >                }
1850              }
1851          }
1852      }
1853  
1854      /**
1855 <     * Same idea as awaitJoin, but no helping, retries, or timeouts.
1856 <     */
1857 <    final void awaitBlocker(ManagedBlocker blocker)
1858 <        throws InterruptedException {
1859 <        while (!blocker.isReleasable()) {
1860 <            int wc = workerCounts;
1861 <            if ((wc & RUNNING_COUNT_MASK) != 0 &&
1862 <                UNSAFE.compareAndSwapInt(this, workerCountsOffset,
1863 <                                         wc, wc - ONE_RUNNING)) {
1864 <                try {
1865 <                    while (!blocker.isReleasable()) {
1866 <                        long h = eventWaiters;
1867 <                        if (h != 0L &&
1868 <                            (int)(h >>> EVENT_COUNT_SHIFT) != eventCount)
1869 <                            releaseEventWaiters();
1870 <                        else if ((workerCounts & RUNNING_COUNT_MASK) == 0 &&
1871 <                                 runState < TERMINATING)
1872 <                            helpMaintainParallelism();
1873 <                        else if (blocker.block())
1874 <                            break;
1855 >     * Tries to locate and execute tasks for a stealer of the given
1856 >     * task, or in turn one of its stealers, Traces currentSteal ->
1857 >     * currentJoin links looking for a thread working on a descendant
1858 >     * of the given task and with a non-empty queue to steal back and
1859 >     * execute tasks from. The first call to this method upon a
1860 >     * waiting join will often entail scanning/search, (which is OK
1861 >     * because the joiner has nothing better to do), but this method
1862 >     * leaves hints in workers to speed up subsequent calls. The
1863 >     * implementation is very branchy to cope with potential
1864 >     * inconsistencies or loops encountering chains that are stale,
1865 >     * unknown, or so long that they are likely cyclic.
1866 >     *
1867 >     * @param joiner the joining worker
1868 >     * @param task the task to join
1869 >     * @return 0 if no progress can be made, negative if task
1870 >     * known complete, else positive
1871 >     */
1872 >    private int tryHelpStealer(WorkQueue joiner, ForkJoinTask<?> task) {
1873 >        int stat = 0, steps = 0;                    // bound to avoid cycles
1874 >        if (joiner != null && task != null) {       // hoist null checks
1875 >            restart: for (;;) {
1876 >                ForkJoinTask<?> subtask = task;     // current target
1877 >                for (WorkQueue j = joiner, v;;) {   // v is stealer of subtask
1878 >                    WorkQueue[] ws; int m, s, h;
1879 >                    if ((s = task.status) < 0) {
1880 >                        stat = s;
1881 >                        break restart;
1882 >                    }
1883 >                    if ((ws = workQueues) == null || (m = ws.length - 1) <= 0)
1884 >                        break restart;              // shutting down
1885 >                    if ((v = ws[h = (j.stealHint | 1) & m]) == null ||
1886 >                        v.currentSteal != subtask) {
1887 >                        for (int origin = h;;) {    // find stealer
1888 >                            if (((h = (h + 2) & m) & 15) == 1 &&
1889 >                                (subtask.status < 0 || j.currentJoin != subtask))
1890 >                                continue restart;   // occasional staleness check
1891 >                            if ((v = ws[h]) != null &&
1892 >                                v.currentSteal == subtask) {
1893 >                                j.stealHint = h;    // save hint
1894 >                                break;
1895 >                            }
1896 >                            if (h == origin)
1897 >                                break restart;      // cannot find stealer
1898 >                        }
1899 >                    }
1900 >                    for (;;) { // help stealer or descend to its stealer
1901 >                        ForkJoinTask[] a;  int b;
1902 >                        if (subtask.status < 0)     // surround probes with
1903 >                            continue restart;       //   consistency checks
1904 >                        if ((b = v.base) - v.top < 0 && (a = v.array) != null) {
1905 >                            int i = (((a.length - 1) & b) << ASHIFT) + ABASE;
1906 >                            ForkJoinTask<?> t =
1907 >                                (ForkJoinTask<?>)U.getObjectVolatile(a, i);
1908 >                            if (subtask.status < 0 || j.currentJoin != subtask ||
1909 >                                v.currentSteal != subtask)
1910 >                                continue restart;   // stale
1911 >                            stat = 1;               // apparent progress
1912 >                            if (t != null && v.base == b &&
1913 >                                U.compareAndSwapObject(a, i, t, null)) {
1914 >                                v.base = b + 1;     // help stealer
1915 >                                joiner.runSubtask(t);
1916 >                            }
1917 >                            else if (v.base == b && ++steps == MAX_HELP)
1918 >                                break restart;      // v apparently stalled
1919 >                        }
1920 >                        else {                      // empty -- try to descend
1921 >                            ForkJoinTask<?> next = v.currentJoin;
1922 >                            if (subtask.status < 0 || j.currentJoin != subtask ||
1923 >                                v.currentSteal != subtask)
1924 >                                continue restart;   // stale
1925 >                            else if (next == null || ++steps == MAX_HELP)
1926 >                                break restart;      // dead-end or maybe cyclic
1927 >                            else {
1928 >                                subtask = next;
1929 >                                j = v;
1930 >                                break;
1931 >                            }
1932 >                        }
1933                      }
1056                } finally {
1057                    int c;
1058                    do {} while (!UNSAFE.compareAndSwapInt
1059                                 (this, workerCountsOffset,
1060                                  c = workerCounts, c + ONE_RUNNING));
1934                  }
1062                break;
1935              }
1936          }
1937 +        return stat;
1938      }
1939  
1940      /**
1941 <     * Possibly initiates and/or completes termination.
1941 >     * If task is at base of some steal queue, steals and executes it.
1942       *
1943 <     * @param now if true, unconditionally terminate, else only
1944 <     * if shutdown and empty queue and no active workers
1072 <     * @return true if now terminating or terminated
1943 >     * @param joiner the joining worker
1944 >     * @param task the task
1945       */
1946 <    private boolean tryTerminate(boolean now) {
1947 <        if (now)
1948 <            advanceRunLevel(SHUTDOWN); // ensure at least SHUTDOWN
1949 <        else if (runState < SHUTDOWN ||
1950 <                 !submissionQueue.isEmpty() ||
1951 <                 (runState & ACTIVE_COUNT_MASK) != 0)
1952 <            return false;
1953 <
1954 <        if (advanceRunLevel(TERMINATING))
1955 <            startTerminating();
1946 >    private void tryPollForAndExec(WorkQueue joiner, ForkJoinTask<?> task) {
1947 >        WorkQueue[] ws;
1948 >        if ((ws = workQueues) != null) {
1949 >            for (int j = 1; j < ws.length && task.status >= 0; j += 2) {
1950 >                WorkQueue q = ws[j];
1951 >                if (q != null && q.pollFor(task)) {
1952 >                    joiner.runSubtask(task);
1953 >                    break;
1954 >                }
1955 >            }
1956 >        }
1957 >    }
1958  
1959 <        // Finish now if all threads terminated; else in some subsequent call
1960 <        if ((workerCounts >>> TOTAL_COUNT_SHIFT) == 0) {
1961 <            advanceRunLevel(TERMINATED);
1962 <            termination.arrive();
1963 <        }
1964 <        return true;
1959 >    /**
1960 >     * Tries to decrement active count (sometimes implicitly) and
1961 >     * possibly release or create a compensating worker in preparation
1962 >     * for blocking. Fails on contention or termination. Otherwise,
1963 >     * adds a new thread if no idle workers are available and either
1964 >     * pool would become completely starved or: (at least half
1965 >     * starved, and fewer than 50% spares exist, and there is at least
1966 >     * one task apparently available). Even though the availability
1967 >     * check requires a full scan, it is worthwhile in reducing false
1968 >     * alarms.
1969 >     *
1970 >     * @param task if non-null, a task being waited for
1971 >     * @param blocker if non-null, a blocker being waited for
1972 >     * @return true if the caller can block, else should recheck and retry
1973 >     */
1974 >    final boolean tryCompensate(ForkJoinTask<?> task, ManagedBlocker blocker) {
1975 >        int pc = parallelism, e;
1976 >        long c = ctl;
1977 >        WorkQueue[] ws = workQueues;
1978 >        if ((e = (int)c) >= 0 && ws != null) {
1979 >            int u, a, ac, hc;
1980 >            int tc = (short)((u = (int)(c >>> 32)) >>> UTC_SHIFT) + pc;
1981 >            boolean replace = false;
1982 >            if ((a = u >> UAC_SHIFT) <= 0) {
1983 >                if ((ac = a + pc) <= 1)
1984 >                    replace = true;
1985 >                else if ((e > 0 || (task != null &&
1986 >                                    ac <= (hc = pc >>> 1) && tc < pc + hc))) {
1987 >                    WorkQueue w;
1988 >                    for (int j = 0; j < ws.length; ++j) {
1989 >                        if ((w = ws[j]) != null && !w.isEmpty()) {
1990 >                            replace = true;
1991 >                            break;   // in compensation range and tasks available
1992 >                        }
1993 >                    }
1994 >                }
1995 >            }
1996 >            if ((task == null || task.status >= 0) && // recheck need to block
1997 >                (blocker == null || !blocker.isReleasable()) && ctl == c) {
1998 >                if (!replace) {          // no compensation
1999 >                    long nc = ((c - AC_UNIT) & AC_MASK) | (c & ~AC_MASK);
2000 >                    if (U.compareAndSwapLong(this, CTL, c, nc))
2001 >                        return true;
2002 >                }
2003 >                else if (e != 0) {       // release an idle worker
2004 >                    WorkQueue w; Thread p; int i;
2005 >                    if ((i = e & SMASK) < ws.length && (w = ws[i]) != null) {
2006 >                        long nc = ((long)(w.nextWait & E_MASK) |
2007 >                                   (c & (AC_MASK|TC_MASK)));
2008 >                        if (w.eventCount == (e | INT_SIGN) &&
2009 >                            U.compareAndSwapLong(this, CTL, c, nc)) {
2010 >                            w.eventCount = (e + E_SEQ) & E_MASK;
2011 >                            if ((p = w.parker) != null)
2012 >                                U.unpark(p);
2013 >                            return true;
2014 >                        }
2015 >                    }
2016 >                }
2017 >                else if (tc < MAX_CAP) { // create replacement
2018 >                    long nc = ((c + TC_UNIT) & TC_MASK) | (c & ~TC_MASK);
2019 >                    if (U.compareAndSwapLong(this, CTL, c, nc)) {
2020 >                        addWorker();
2021 >                        return true;
2022 >                    }
2023 >                }
2024 >            }
2025 >        }
2026 >        return false;
2027      }
2028  
2029      /**
2030 <     * Actions on transition to TERMINATING
2031 <     *
2032 <     * Runs up to four passes through workers: (0) shutting down each
2033 <     * (without waking up if parked) to quickly spread notifications
2034 <     * without unnecessary bouncing around event queues etc (1) wake
2035 <     * up and help cancel tasks (2) interrupt (3) mop up races with
2036 <     * interrupted workers
2037 <     */
2038 <    private void startTerminating() {
2039 <        cancelSubmissions();
2040 <        for (int passes = 0; passes < 4 && workerCounts != 0; ++passes) {
2041 <            int c; // advance event count
2042 <            UNSAFE.compareAndSwapInt(this, eventCountOffset,
2043 <                                     c = eventCount, c+1);
2044 <            eventWaiters = 0L; // clobber lists
2045 <            spareWaiters = 0;
2046 <            ForkJoinWorkerThread[] ws = workers;
2047 <            int n = ws.length;
2048 <            for (int i = 0; i < n; ++i) {
2049 <                ForkJoinWorkerThread w = ws[i];
2050 <                if (w != null) {
2051 <                    w.shutdown();
2052 <                    if (passes > 0 && !w.isTerminated()) {
2053 <                        w.cancelTasks();
2054 <                        LockSupport.unpark(w);
2055 <                        if (passes > 1) {
2056 <                            try {
2057 <                                w.interrupt();
2058 <                            } catch (SecurityException ignore) {
2030 >     * Helps and/or blocks until the given task is done.
2031 >     *
2032 >     * @param joiner the joining worker
2033 >     * @param task the task
2034 >     * @return task status on exit
2035 >     */
2036 >    final int awaitJoin(WorkQueue joiner, ForkJoinTask<?> task) {
2037 >        int s;
2038 >        if ((s = task.status) >= 0) {
2039 >            ForkJoinTask<?> prevJoin = joiner.currentJoin;
2040 >            joiner.currentJoin = task;
2041 >            long startTime = 0L;
2042 >            for (int k = 0;;) {
2043 >                if ((s = (joiner.isEmpty() ?           // try to help
2044 >                          tryHelpStealer(joiner, task) :
2045 >                          joiner.tryRemoveAndExec(task))) == 0 &&
2046 >                    (s = task.status) >= 0) {
2047 >                    if (k == 0) {
2048 >                        startTime = System.nanoTime();
2049 >                        tryPollForAndExec(joiner, task); // check uncommon case
2050 >                    }
2051 >                    else if ((k & (MAX_HELP - 1)) == 0 &&
2052 >                             System.nanoTime() - startTime >=
2053 >                             COMPENSATION_DELAY &&
2054 >                             tryCompensate(task, null)) {
2055 >                        if (task.trySetSignal()) {
2056 >                            synchronized (task) {
2057 >                                if (task.status >= 0) {
2058 >                                    try {                // see ForkJoinTask
2059 >                                        task.wait();     //  for explanation
2060 >                                    } catch (InterruptedException ie) {
2061 >                                    }
2062 >                                }
2063 >                                else
2064 >                                    task.notifyAll();
2065                              }
2066                          }
2067 +                        long c;                          // re-activate
2068 +                        do {} while (!U.compareAndSwapLong
2069 +                                     (this, CTL, c = ctl, c + AC_UNIT));
2070                      }
2071                  }
2072 +                if (s < 0 || (s = task.status) < 0) {
2073 +                    joiner.currentJoin = prevJoin;
2074 +                    break;
2075 +                }
2076 +                else if ((k++ & (MAX_HELP - 1)) == MAX_HELP >>> 1)
2077 +                    Thread.yield();                     // for politeness
2078              }
2079          }
2080 +        return s;
2081      }
2082  
2083      /**
2084 <     * Clear out and cancel submissions, ignoring exceptions
2084 >     * Stripped-down variant of awaitJoin used by timed joins. Tries
2085 >     * to help join only while there is continuous progress. (Caller
2086 >     * will then enter a timed wait.)
2087 >     *
2088 >     * @param joiner the joining worker
2089 >     * @param task the task
2090 >     * @return task status on exit
2091       */
2092 <    private void cancelSubmissions() {
2093 <        ForkJoinTask<?> task;
2094 <        while ((task = submissionQueue.poll()) != null) {
2095 <            try {
2096 <                task.cancel(false);
2097 <            } catch (Throwable ignore) {
2092 >    final int helpJoinOnce(WorkQueue joiner, ForkJoinTask<?> task) {
2093 >        int s;
2094 >        while ((s = task.status) >= 0 &&
2095 >               (joiner.isEmpty() ?
2096 >                tryHelpStealer(joiner, task) :
2097 >                joiner.tryRemoveAndExec(task)) != 0)
2098 >            ;
2099 >        return s;
2100 >    }
2101 >
2102 >    /**
2103 >     * Returns a (probably) non-empty steal queue, if one is found
2104 >     * during a random, then cyclic scan, else null.  This method must
2105 >     * be retried by caller if, by the time it tries to use the queue,
2106 >     * it is empty.
2107 >     */
2108 >    private WorkQueue findNonEmptyStealQueue(WorkQueue w) {
2109 >        // Similar to loop in scan(), but ignoring submissions
2110 >        int r = w.seed; r ^= r << 13; r ^= r >>> 17; w.seed = r ^= r << 5;
2111 >        int step = (r >>> 16) | 1;
2112 >        for (WorkQueue[] ws;;) {
2113 >            int rs = runState, m;
2114 >            if ((ws = workQueues) == null || (m = ws.length - 1) < 1)
2115 >                return null;
2116 >            for (int j = (m + 1) << 2; ; r += step) {
2117 >                WorkQueue q = ws[((r << 1) | 1) & m];
2118 >                if (q != null && !q.isEmpty())
2119 >                    return q;
2120 >                else if (--j < 0) {
2121 >                    if (runState == rs)
2122 >                        return null;
2123 >                    break;
2124 >                }
2125              }
2126          }
2127      }
2128  
2129 <    // misc support for ForkJoinWorkerThread
2129 >    /**
2130 >     * Runs tasks until {@code isQuiescent()}. We piggyback on
2131 >     * active count ctl maintenance, but rather than blocking
2132 >     * when tasks cannot be found, we rescan until all others cannot
2133 >     * find tasks either.
2134 >     */
2135 >    final void helpQuiescePool(WorkQueue w) {
2136 >        for (boolean active = true;;) {
2137 >            ForkJoinTask<?> localTask; // exhaust local queue
2138 >            while ((localTask = w.nextLocalTask()) != null)
2139 >                localTask.doExec();
2140 >            WorkQueue q = findNonEmptyStealQueue(w);
2141 >            if (q != null) {
2142 >                ForkJoinTask<?> t; int b;
2143 >                if (!active) {      // re-establish active count
2144 >                    long c;
2145 >                    active = true;
2146 >                    do {} while (!U.compareAndSwapLong
2147 >                                 (this, CTL, c = ctl, c + AC_UNIT));
2148 >                }
2149 >                if ((b = q.base) - q.top < 0 && (t = q.pollAt(b)) != null)
2150 >                    w.runSubtask(t);
2151 >            }
2152 >            else {
2153 >                long c;
2154 >                if (active) {       // decrement active count without queuing
2155 >                    active = false;
2156 >                    do {} while (!U.compareAndSwapLong
2157 >                                 (this, CTL, c = ctl, c -= AC_UNIT));
2158 >                }
2159 >                else
2160 >                    c = ctl;        // re-increment on exit
2161 >                if ((int)(c >> AC_SHIFT) + parallelism == 0) {
2162 >                    do {} while (!U.compareAndSwapLong
2163 >                                 (this, CTL, c = ctl, c + AC_UNIT));
2164 >                    break;
2165 >                }
2166 >            }
2167 >        }
2168 >    }
2169  
2170      /**
2171 <     * Returns pool number
2171 >     * Restricted version of helpQuiescePool for non-FJ callers
2172       */
2173 <    final int getPoolNumber() {
2174 <        return poolNumber;
2173 >    static void externalHelpQuiescePool() {
2174 >        ForkJoinPool p; WorkQueue[] ws; WorkQueue q, sq;
2175 >        ForkJoinTask<?>[] a; int b;
2176 >        ForkJoinTask<?> t = null;
2177 >        int k = submitters.get().seed & SQMASK;
2178 >        if ((p = commonPool) != null &&
2179 >            (ws = p.workQueues) != null &&
2180 >            ws.length > (k &= p.submitMask) &&
2181 >            (q = ws[k]) != null) {
2182 >            while (q.top - q.base > 0) {
2183 >                if ((t = q.sharedPop()) != null)
2184 >                    break;
2185 >            }
2186 >            if (t == null && (sq = p.findNonEmptyStealQueue(q)) != null &&
2187 >                (b = sq.base) - sq.top < 0)
2188 >                t = sq.pollAt(b);
2189 >            if (t != null)
2190 >                t.doExec();
2191 >        }
2192      }
2193  
2194      /**
2195 <     * Tries to accumulates steal count from a worker, clearing
1155 <     * the worker's value.
2195 >     * Gets and removes a local or stolen task for the given worker.
2196       *
2197 <     * @return true if worker steal count now zero
2197 >     * @return a task, if available
2198       */
2199 <    final boolean tryAccumulateStealCount(ForkJoinWorkerThread w) {
2200 <        int sc = w.stealCount;
2201 <        long c = stealCount;
2202 <        // CAS even if zero, for fence effects
2203 <        if (UNSAFE.compareAndSwapLong(this, stealCountOffset, c, c + sc)) {
2204 <            if (sc != 0)
2205 <                w.stealCount = 0;
2206 <            return true;
2199 >    final ForkJoinTask<?> nextTaskFor(WorkQueue w) {
2200 >        for (ForkJoinTask<?> t;;) {
2201 >            WorkQueue q; int b;
2202 >            if ((t = w.nextLocalTask()) != null)
2203 >                return t;
2204 >            if ((q = findNonEmptyStealQueue(w)) == null)
2205 >                return null;
2206 >            if ((b = q.base) - q.top < 0 && (t = q.pollAt(b)) != null)
2207 >                return t;
2208          }
1168        return sc == 0;
2209      }
2210  
2211      /**
2212       * Returns the approximate (non-atomic) number of idle threads per
2213 <     * active thread.
2213 >     * active thread to offset steal queue size for method
2214 >     * ForkJoinTask.getSurplusQueuedTaskCount().
2215       */
2216      final int idlePerActive() {
2217 <        int pc = parallelism; // use parallelism, not rc
2218 <        int ac = runState;    // no mask -- artificially boosts during shutdown
2219 <        // Use exact results for small values, saturate past 4
2220 <        return pc <= ac? 0 : pc >>> 1 <= ac? 1 : pc >>> 2 <= ac? 3 : pc >>> 3;
2217 >        // Approximate at powers of two for small values, saturate past 4
2218 >        int p = parallelism;
2219 >        int a = p + (int)(ctl >> AC_SHIFT);
2220 >        return (a > (p >>>= 1) ? 0 :
2221 >                a > (p >>>= 1) ? 1 :
2222 >                a > (p >>>= 1) ? 2 :
2223 >                a > (p >>>= 1) ? 4 :
2224 >                8);
2225 >    }
2226 >
2227 >    /**
2228 >     * Returns approximate submission queue length for the given caller
2229 >     */
2230 >    static int getEstimatedSubmitterQueueLength() {
2231 >        ForkJoinPool p; WorkQueue[] ws; WorkQueue q;
2232 >        int k = submitters.get().seed & SQMASK;
2233 >        return ((p = commonPool) != null && (ws = p.workQueues) != null &&
2234 >                ws.length > (k &= p.submitMask) &&
2235 >                (q = ws[k]) != null) ?
2236 >            q.queueSize() : 0;
2237 >    }
2238 >
2239 >    //  Termination
2240 >
2241 >    /**
2242 >     * Possibly initiates and/or completes termination.  The caller
2243 >     * triggering termination runs three passes through workQueues:
2244 >     * (0) Setting termination status, followed by wakeups of queued
2245 >     * workers; (1) cancelling all tasks; (2) interrupting lagging
2246 >     * threads (likely in external tasks, but possibly also blocked in
2247 >     * joins).  Each pass repeats previous steps because of potential
2248 >     * lagging thread creation.
2249 >     *
2250 >     * @param now if true, unconditionally terminate, else only
2251 >     * if no work and no active workers
2252 >     * @param enable if true, enable shutdown when next possible
2253 >     * @return true if now terminating or terminated
2254 >     */
2255 >    private boolean tryTerminate(boolean now, boolean enable) {
2256 >        for (long c;;) {
2257 >            if (((c = ctl) & STOP_BIT) != 0) {      // already terminating
2258 >                if ((short)(c >>> TC_SHIFT) == -parallelism) {
2259 >                    synchronized (this) {
2260 >                        notifyAll();                // signal when 0 workers
2261 >                    }
2262 >                }
2263 >                return true;
2264 >            }
2265 >            if (runState >= 0) {                    // not yet enabled
2266 >                if (!enable)
2267 >                    return false;
2268 >                while (!U.compareAndSwapInt(this, MAINLOCK, 0, 1))
2269 >                    tryAwaitMainLock();
2270 >                try {
2271 >                    runState |= SHUTDOWN;
2272 >                } finally {
2273 >                    if (!U.compareAndSwapInt(this, MAINLOCK, 1, 0)) {
2274 >                        mainLock = 0;
2275 >                        synchronized (this) { notifyAll(); };
2276 >                    }
2277 >                }
2278 >            }
2279 >            if (!now) {                             // check if idle & no tasks
2280 >                if ((int)(c >> AC_SHIFT) != -parallelism ||
2281 >                    hasQueuedSubmissions())
2282 >                    return false;
2283 >                // Check for unqueued inactive workers. One pass suffices.
2284 >                WorkQueue[] ws = workQueues; WorkQueue w;
2285 >                if (ws != null) {
2286 >                    for (int i = 1; i < ws.length; i += 2) {
2287 >                        if ((w = ws[i]) != null && w.eventCount >= 0)
2288 >                            return false;
2289 >                    }
2290 >                }
2291 >            }
2292 >            if (U.compareAndSwapLong(this, CTL, c, c | STOP_BIT)) {
2293 >                for (int pass = 0; pass < 3; ++pass) {
2294 >                    WorkQueue[] ws = workQueues;
2295 >                    if (ws != null) {
2296 >                        WorkQueue w;
2297 >                        int n = ws.length;
2298 >                        for (int i = 0; i < n; ++i) {
2299 >                            if ((w = ws[i]) != null) {
2300 >                                w.runState = -1;
2301 >                                if (pass > 0) {
2302 >                                    w.cancelAll();
2303 >                                    if (pass > 1)
2304 >                                        w.interruptOwner();
2305 >                                }
2306 >                            }
2307 >                        }
2308 >                        // Wake up workers parked on event queue
2309 >                        int i, e; long cc; Thread p;
2310 >                        while ((e = (int)(cc = ctl) & E_MASK) != 0 &&
2311 >                               (i = e & SMASK) < n &&
2312 >                               (w = ws[i]) != null) {
2313 >                            long nc = ((long)(w.nextWait & E_MASK) |
2314 >                                       ((cc + AC_UNIT) & AC_MASK) |
2315 >                                       (cc & (TC_MASK|STOP_BIT)));
2316 >                            if (w.eventCount == (e | INT_SIGN) &&
2317 >                                U.compareAndSwapLong(this, CTL, cc, nc)) {
2318 >                                w.eventCount = (e + E_SEQ) & E_MASK;
2319 >                                w.runState = -1;
2320 >                                if ((p = w.parker) != null)
2321 >                                    U.unpark(p);
2322 >                            }
2323 >                        }
2324 >                    }
2325 >                }
2326 >            }
2327 >        }
2328      }
2329  
2330 <    // Public and protected methods
2330 >    // Exported methods
2331  
2332      // Constructors
2333  
# Line 1226 | Line 2374 | public class ForkJoinPool extends Abstra
2374       * use {@link #defaultForkJoinWorkerThreadFactory}.
2375       * @param handler the handler for internal worker threads that
2376       * terminate due to unrecoverable errors encountered while executing
2377 <     * tasks. For default value, use <code>null</code>.
2377 >     * tasks. For default value, use {@code null}.
2378       * @param asyncMode if true,
2379       * establishes local first-in-first-out scheduling mode for forked
2380       * tasks that are never joined. This mode may be more appropriate
2381       * than default locally stack-based mode in applications in which
2382       * worker threads only process event-style asynchronous tasks.
2383 <     * For default value, use <code>false</code>.
2383 >     * For default value, use {@code false}.
2384       * @throws IllegalArgumentException if parallelism less than or
2385       *         equal to zero, or greater than implementation limit
2386       * @throws NullPointerException if the factory is null
# Line 1248 | Line 2396 | public class ForkJoinPool extends Abstra
2396          checkPermission();
2397          if (factory == null)
2398              throw new NullPointerException();
2399 <        if (parallelism <= 0 || parallelism > MAX_WORKERS)
2399 >        if (parallelism <= 0 || parallelism > MAX_CAP)
2400              throw new IllegalArgumentException();
2401          this.parallelism = parallelism;
2402          this.factory = factory;
2403          this.ueh = handler;
2404 <        this.locallyFifo = asyncMode;
2405 <        int arraySize = initialArraySizeFor(parallelism);
2406 <        this.workers = new ForkJoinWorkerThread[arraySize];
2407 <        this.submissionQueue = new LinkedTransferQueue<ForkJoinTask<?>>();
2408 <        this.workerLock = new ReentrantLock();
2409 <        this.termination = new Phaser(1);
2410 <        this.poolNumber = poolNumberGenerator.incrementAndGet();
2404 >        this.localMode = asyncMode ? FIFO_QUEUE : LIFO_QUEUE;
2405 >        long np = (long)(-parallelism); // offset ctl counts
2406 >        this.ctl = ((np << AC_SHIFT) & AC_MASK) | ((np << TC_SHIFT) & TC_MASK);
2407 >        // Use nearest power 2 for workQueues size. See Hackers Delight sec 3.2.
2408 >        int n = parallelism - 1;
2409 >        n |= n >>> 1; n |= n >>> 2; n |= n >>> 4; n |= n >>> 8; n |= n >>> 16;
2410 >        this.submitMask = ((n + 1) << 1) - 1;
2411 >        int pn = poolNumberGenerator.incrementAndGet();
2412 >        StringBuilder sb = new StringBuilder("ForkJoinPool-");
2413 >        sb.append(Integer.toString(pn));
2414 >        sb.append("-worker-");
2415 >        this.workerNamePrefix = sb.toString();
2416 >        this.runState = 1;              // set init flag
2417      }
2418  
2419      /**
2420 <     * Returns initial power of two size for workers array.
2421 <     * @param pc the initial parallelism level
2422 <     */
2423 <    private static int initialArraySizeFor(int pc) {
2424 <        // If possible, initially allocate enough space for one spare
2425 <        int size = pc < MAX_WORKERS ? pc + 1 : MAX_WORKERS;
2426 <        // See Hackers Delight, sec 3.2. We know MAX_WORKERS < (1 >>> 16)
2427 <        size |= size >>> 1;
2428 <        size |= size >>> 2;
2429 <        size |= size >>> 4;
2430 <        size |= size >>> 8;
2431 <        return size + 1;
2420 >     * Constructor for common pool, suitable only for static initialization.
2421 >     * Basically the same as above, but uses smallest possible initial footprint.
2422 >     */
2423 >    ForkJoinPool(int parallelism, int submitMask,
2424 >                 ForkJoinWorkerThreadFactory factory,
2425 >                 Thread.UncaughtExceptionHandler handler) {
2426 >        this.factory = factory;
2427 >        this.ueh = handler;
2428 >        this.submitMask = submitMask;
2429 >        this.parallelism = parallelism;
2430 >        long np = (long)(-parallelism);
2431 >        this.ctl = ((np << AC_SHIFT) & AC_MASK) | ((np << TC_SHIFT) & TC_MASK);
2432 >        this.localMode = LIFO_QUEUE;
2433 >        this.workerNamePrefix = "ForkJoinPool.commonPool-worker-";
2434 >        this.runState = 1;
2435      }
2436  
1280    // Execution methods
1281
2437      /**
2438 <     * Common code for execute, invoke and submit
2438 >     * Returns the common pool instance.
2439 >     *
2440 >     * @return the common pool instance
2441       */
2442 <    private <T> void doSubmit(ForkJoinTask<T> task) {
2443 <        if (task == null)
2444 <            throw new NullPointerException();
2445 <        if (runState >= SHUTDOWN)
2446 <            throw new RejectedExecutionException();
1290 <        submissionQueue.offer(task);
1291 <        int c; // try to increment event count -- CAS failure OK
1292 <        UNSAFE.compareAndSwapInt(this, eventCountOffset, c = eventCount, c+1);
1293 <        helpMaintainParallelism(); // create, start, or resume some workers
2442 >    public static ForkJoinPool commonPool() {
2443 >        ForkJoinPool p;
2444 >        if ((p = commonPool) == null)
2445 >            throw new Error("Common Pool Unavailable");
2446 >        return p;
2447      }
2448  
2449 +    // Execution methods
2450 +
2451      /**
2452       * Performs the given task, returning its result upon completion.
2453 +     * If the computation encounters an unchecked Exception or Error,
2454 +     * it is rethrown as the outcome of this invocation.  Rethrown
2455 +     * exceptions behave in the same way as regular exceptions, but,
2456 +     * when possible, contain stack traces (as displayed for example
2457 +     * using {@code ex.printStackTrace()}) of both the current thread
2458 +     * as well as the thread actually encountering the exception;
2459 +     * minimally only the latter.
2460       *
2461       * @param task the task
2462       * @return the task's result
# Line 1303 | Line 2465 | public class ForkJoinPool extends Abstra
2465       *         scheduled for execution
2466       */
2467      public <T> T invoke(ForkJoinTask<T> task) {
2468 +        if (task == null)
2469 +            throw new NullPointerException();
2470          doSubmit(task);
2471          return task.join();
2472      }
# Line 1316 | Line 2480 | public class ForkJoinPool extends Abstra
2480       *         scheduled for execution
2481       */
2482      public void execute(ForkJoinTask<?> task) {
2483 +        if (task == null)
2484 +            throw new NullPointerException();
2485          doSubmit(task);
2486      }
2487  
# Line 1327 | Line 2493 | public class ForkJoinPool extends Abstra
2493       *         scheduled for execution
2494       */
2495      public void execute(Runnable task) {
2496 +        if (task == null)
2497 +            throw new NullPointerException();
2498          ForkJoinTask<?> job;
2499          if (task instanceof ForkJoinTask<?>) // avoid re-wrap
2500              job = (ForkJoinTask<?>) task;
2501          else
2502 <            job = ForkJoinTask.adapt(task, null);
2502 >            job = new ForkJoinTask.AdaptedRunnableAction(task);
2503          doSubmit(job);
2504      }
2505  
# Line 1345 | Line 2513 | public class ForkJoinPool extends Abstra
2513       *         scheduled for execution
2514       */
2515      public <T> ForkJoinTask<T> submit(ForkJoinTask<T> task) {
2516 +        if (task == null)
2517 +            throw new NullPointerException();
2518          doSubmit(task);
2519          return task;
2520      }
# Line 1355 | Line 2525 | public class ForkJoinPool extends Abstra
2525       *         scheduled for execution
2526       */
2527      public <T> ForkJoinTask<T> submit(Callable<T> task) {
2528 <        ForkJoinTask<T> job = ForkJoinTask.adapt(task);
2528 >        ForkJoinTask<T> job = new ForkJoinTask.AdaptedCallable<T>(task);
2529          doSubmit(job);
2530          return job;
2531      }
# Line 1366 | Line 2536 | public class ForkJoinPool extends Abstra
2536       *         scheduled for execution
2537       */
2538      public <T> ForkJoinTask<T> submit(Runnable task, T result) {
2539 <        ForkJoinTask<T> job = ForkJoinTask.adapt(task, result);
2539 >        ForkJoinTask<T> job = new ForkJoinTask.AdaptedRunnable<T>(task, result);
2540          doSubmit(job);
2541          return job;
2542      }
# Line 1377 | Line 2547 | public class ForkJoinPool extends Abstra
2547       *         scheduled for execution
2548       */
2549      public ForkJoinTask<?> submit(Runnable task) {
2550 +        if (task == null)
2551 +            throw new NullPointerException();
2552          ForkJoinTask<?> job;
2553          if (task instanceof ForkJoinTask<?>) // avoid re-wrap
2554              job = (ForkJoinTask<?>) task;
2555          else
2556 <            job = ForkJoinTask.adapt(task, null);
2556 >            job = new ForkJoinTask.AdaptedRunnableAction(task);
2557          doSubmit(job);
2558          return job;
2559      }
# Line 1391 | Line 2563 | public class ForkJoinPool extends Abstra
2563       * @throws RejectedExecutionException {@inheritDoc}
2564       */
2565      public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) {
2566 <        ArrayList<ForkJoinTask<T>> forkJoinTasks =
2567 <            new ArrayList<ForkJoinTask<T>>(tasks.size());
2568 <        for (Callable<T> task : tasks)
2569 <            forkJoinTasks.add(ForkJoinTask.adapt(task));
2570 <        invoke(new InvokeAll<T>(forkJoinTasks));
2571 <
2566 >        // In previous versions of this class, this method constructed
2567 >        // a task to run ForkJoinTask.invokeAll, but now external
2568 >        // invocation of multiple tasks is at least as efficient.
2569 >        List<ForkJoinTask<T>> fs = new ArrayList<ForkJoinTask<T>>(tasks.size());
2570 >        // Workaround needed because method wasn't declared with
2571 >        // wildcards in return type but should have been.
2572          @SuppressWarnings({"unchecked", "rawtypes"})
2573 <            List<Future<T>> futures = (List<Future<T>>) (List) forkJoinTasks;
1402 <        return futures;
1403 <    }
2573 >            List<Future<T>> futures = (List<Future<T>>) (List) fs;
2574  
2575 <    static final class InvokeAll<T> extends RecursiveAction {
2576 <        final ArrayList<ForkJoinTask<T>> tasks;
2577 <        InvokeAll(ArrayList<ForkJoinTask<T>> tasks) { this.tasks = tasks; }
2578 <        public void compute() {
2579 <            try { invokeAll(tasks); }
2580 <            catch (Exception ignore) {}
2575 >        boolean done = false;
2576 >        try {
2577 >            for (Callable<T> t : tasks) {
2578 >                ForkJoinTask<T> f = new ForkJoinTask.AdaptedCallable<T>(t);
2579 >                doSubmit(f);
2580 >                fs.add(f);
2581 >            }
2582 >            for (ForkJoinTask<T> f : fs)
2583 >                f.quietlyJoin();
2584 >            done = true;
2585 >            return futures;
2586 >        } finally {
2587 >            if (!done)
2588 >                for (ForkJoinTask<T> f : fs)
2589 >                    f.cancel(false);
2590          }
1412        private static final long serialVersionUID = -7914297376763021607L;
2591      }
2592  
2593      /**
# Line 1441 | Line 2619 | public class ForkJoinPool extends Abstra
2619      }
2620  
2621      /**
2622 +     * Returns the targeted parallelism level of the common pool.
2623 +     *
2624 +     * @return the targeted parallelism level of the common pool
2625 +     */
2626 +    public static int getCommonPoolParallelism() {
2627 +        return commonPoolParallelism;
2628 +    }
2629 +
2630 +    /**
2631       * Returns the number of worker threads that have started but not
2632 <     * yet terminated.  This result returned by this method may differ
2632 >     * yet terminated.  The result returned by this method may differ
2633       * from {@link #getParallelism} when threads are created to
2634       * maintain parallelism when others are cooperatively blocked.
2635       *
2636       * @return the number of worker threads
2637       */
2638      public int getPoolSize() {
2639 <        return workerCounts >>> TOTAL_COUNT_SHIFT;
2639 >        return parallelism + (short)(ctl >>> TC_SHIFT);
2640      }
2641  
2642      /**
# Line 1459 | Line 2646 | public class ForkJoinPool extends Abstra
2646       * @return {@code true} if this pool uses async mode
2647       */
2648      public boolean getAsyncMode() {
2649 <        return locallyFifo;
2649 >        return localMode != 0;
2650      }
2651  
2652      /**
# Line 1471 | Line 2658 | public class ForkJoinPool extends Abstra
2658       * @return the number of worker threads
2659       */
2660      public int getRunningThreadCount() {
2661 <        return workerCounts & RUNNING_COUNT_MASK;
2661 >        int rc = 0;
2662 >        WorkQueue[] ws; WorkQueue w;
2663 >        if ((ws = workQueues) != null) {
2664 >            for (int i = 1; i < ws.length; i += 2) {
2665 >                if ((w = ws[i]) != null && w.isApparentlyUnblocked())
2666 >                    ++rc;
2667 >            }
2668 >        }
2669 >        return rc;
2670      }
2671  
2672      /**
# Line 1482 | Line 2677 | public class ForkJoinPool extends Abstra
2677       * @return the number of active threads
2678       */
2679      public int getActiveThreadCount() {
2680 <        return runState & ACTIVE_COUNT_MASK;
2680 >        int r = parallelism + (int)(ctl >> AC_SHIFT);
2681 >        return (r <= 0) ? 0 : r; // suppress momentarily negative values
2682      }
2683  
2684      /**
# Line 1497 | Line 2693 | public class ForkJoinPool extends Abstra
2693       * @return {@code true} if all threads are currently idle
2694       */
2695      public boolean isQuiescent() {
2696 <        return (runState & ACTIVE_COUNT_MASK) == 0;
2696 >        return (int)(ctl >> AC_SHIFT) + parallelism == 0;
2697      }
2698  
2699      /**
# Line 1512 | Line 2708 | public class ForkJoinPool extends Abstra
2708       * @return the number of steals
2709       */
2710      public long getStealCount() {
2711 <        return stealCount;
2711 >        long count = stealCount;
2712 >        WorkQueue[] ws; WorkQueue w;
2713 >        if ((ws = workQueues) != null) {
2714 >            for (int i = 1; i < ws.length; i += 2) {
2715 >                if ((w = ws[i]) != null)
2716 >                    count += w.totalSteals;
2717 >            }
2718 >        }
2719 >        return count;
2720      }
2721  
2722      /**
# Line 1527 | Line 2731 | public class ForkJoinPool extends Abstra
2731       */
2732      public long getQueuedTaskCount() {
2733          long count = 0;
2734 <        ForkJoinWorkerThread[] ws = workers;
2735 <        int n = ws.length;
2736 <        for (int i = 0; i < n; ++i) {
2737 <            ForkJoinWorkerThread w = ws[i];
2738 <            if (w != null)
2739 <                count += w.getQueueSize();
2734 >        WorkQueue[] ws; WorkQueue w;
2735 >        if ((ws = workQueues) != null) {
2736 >            for (int i = 1; i < ws.length; i += 2) {
2737 >                if ((w = ws[i]) != null)
2738 >                    count += w.queueSize();
2739 >            }
2740          }
2741          return count;
2742      }
2743  
2744      /**
2745       * Returns an estimate of the number of tasks submitted to this
2746 <     * pool that have not yet begun executing.  This method takes time
2747 <     * proportional to the number of submissions.
2746 >     * pool that have not yet begun executing.  This method may take
2747 >     * time proportional to the number of submissions.
2748       *
2749       * @return the number of queued submissions
2750       */
2751      public int getQueuedSubmissionCount() {
2752 <        return submissionQueue.size();
2752 >        int count = 0;
2753 >        WorkQueue[] ws; WorkQueue w;
2754 >        if ((ws = workQueues) != null) {
2755 >            for (int i = 0; i < ws.length; i += 2) {
2756 >                if ((w = ws[i]) != null)
2757 >                    count += w.queueSize();
2758 >            }
2759 >        }
2760 >        return count;
2761      }
2762  
2763      /**
# Line 1555 | Line 2767 | public class ForkJoinPool extends Abstra
2767       * @return {@code true} if there are any queued submissions
2768       */
2769      public boolean hasQueuedSubmissions() {
2770 <        return !submissionQueue.isEmpty();
2770 >        WorkQueue[] ws; WorkQueue w;
2771 >        if ((ws = workQueues) != null) {
2772 >            for (int i = 0; i < ws.length; i += 2) {
2773 >                if ((w = ws[i]) != null && !w.isEmpty())
2774 >                    return true;
2775 >            }
2776 >        }
2777 >        return false;
2778      }
2779  
2780      /**
# Line 1566 | Line 2785 | public class ForkJoinPool extends Abstra
2785       * @return the next submission, or {@code null} if none
2786       */
2787      protected ForkJoinTask<?> pollSubmission() {
2788 <        return submissionQueue.poll();
2788 >        WorkQueue[] ws; WorkQueue w; ForkJoinTask<?> t;
2789 >        if ((ws = workQueues) != null) {
2790 >            for (int i = 0; i < ws.length; i += 2) {
2791 >                if ((w = ws[i]) != null && (t = w.poll()) != null)
2792 >                    return t;
2793 >            }
2794 >        }
2795 >        return null;
2796      }
2797  
2798      /**
# Line 1587 | Line 2813 | public class ForkJoinPool extends Abstra
2813       * @return the number of elements transferred
2814       */
2815      protected int drainTasksTo(Collection<? super ForkJoinTask<?>> c) {
2816 <        int count = submissionQueue.drainTo(c);
2817 <        ForkJoinWorkerThread[] ws = workers;
2818 <        int n = ws.length;
2819 <        for (int i = 0; i < n; ++i) {
2820 <            ForkJoinWorkerThread w = ws[i];
2821 <            if (w != null)
2822 <                count += w.drainTasksTo(c);
2816 >        int count = 0;
2817 >        WorkQueue[] ws; WorkQueue w; ForkJoinTask<?> t;
2818 >        if ((ws = workQueues) != null) {
2819 >            for (int i = 0; i < ws.length; ++i) {
2820 >                if ((w = ws[i]) != null) {
2821 >                    while ((t = w.poll()) != null) {
2822 >                        c.add(t);
2823 >                        ++count;
2824 >                    }
2825 >                }
2826 >            }
2827          }
2828          return count;
2829      }
# Line 1606 | Line 2836 | public class ForkJoinPool extends Abstra
2836       * @return a string identifying this pool, as well as its state
2837       */
2838      public String toString() {
2839 <        long st = getStealCount();
2840 <        long qt = getQueuedTaskCount();
2841 <        long qs = getQueuedSubmissionCount();
2842 <        int wc = workerCounts;
2843 <        int tc = wc >>> TOTAL_COUNT_SHIFT;
2844 <        int rc = wc & RUNNING_COUNT_MASK;
2839 >        // Use a single pass through workQueues to collect counts
2840 >        long qt = 0L, qs = 0L; int rc = 0;
2841 >        long st = stealCount;
2842 >        long c = ctl;
2843 >        WorkQueue[] ws; WorkQueue w;
2844 >        if ((ws = workQueues) != null) {
2845 >            for (int i = 0; i < ws.length; ++i) {
2846 >                if ((w = ws[i]) != null) {
2847 >                    int size = w.queueSize();
2848 >                    if ((i & 1) == 0)
2849 >                        qs += size;
2850 >                    else {
2851 >                        qt += size;
2852 >                        st += w.totalSteals;
2853 >                        if (w.isApparentlyUnblocked())
2854 >                            ++rc;
2855 >                    }
2856 >                }
2857 >            }
2858 >        }
2859          int pc = parallelism;
2860 <        int rs = runState;
2861 <        int ac = rs & ACTIVE_COUNT_MASK;
2860 >        int tc = pc + (short)(c >>> TC_SHIFT);
2861 >        int ac = pc + (int)(c >> AC_SHIFT);
2862 >        if (ac < 0) // ignore transient negative
2863 >            ac = 0;
2864 >        String level;
2865 >        if ((c & STOP_BIT) != 0)
2866 >            level = (tc == 0) ? "Terminated" : "Terminating";
2867 >        else
2868 >            level = runState < 0 ? "Shutting down" : "Running";
2869          return super.toString() +
2870 <            "[" + runLevelToString(rs) +
2870 >            "[" + level +
2871              ", parallelism = " + pc +
2872              ", size = " + tc +
2873              ", active = " + ac +
# Line 1627 | Line 2878 | public class ForkJoinPool extends Abstra
2878              "]";
2879      }
2880  
1630    private static String runLevelToString(int s) {
1631        return ((s & TERMINATED) != 0 ? "Terminated" :
1632                ((s & TERMINATING) != 0 ? "Terminating" :
1633                 ((s & SHUTDOWN) != 0 ? "Shutting down" :
1634                  "Running")));
1635    }
1636
2881      /**
2882 <     * Initiates an orderly shutdown in which previously submitted
2883 <     * tasks are executed, but no new tasks will be accepted.
2884 <     * Invocation has no additional effect if already shut down.
2885 <     * Tasks that are in the process of being submitted concurrently
2886 <     * during the course of this method may or may not be rejected.
2882 >     * Possibly initiates an orderly shutdown in which previously
2883 >     * submitted tasks are executed, but no new tasks will be
2884 >     * accepted. Invocation has no effect on execution state if this
2885 >     * is the {@link #commonPool}, and no additional effect if
2886 >     * already shut down.  Tasks that are in the process of being
2887 >     * submitted concurrently during the course of this method may or
2888 >     * may not be rejected.
2889       *
2890       * @throws SecurityException if a security manager exists and
2891       *         the caller is not permitted to modify threads
# Line 1648 | Line 2894 | public class ForkJoinPool extends Abstra
2894       */
2895      public void shutdown() {
2896          checkPermission();
2897 <        advanceRunLevel(SHUTDOWN);
2898 <        tryTerminate(false);
2897 >        if (this != commonPool)
2898 >            tryTerminate(false, true);
2899      }
2900  
2901      /**
2902 <     * Attempts to cancel and/or stop all tasks, and reject all
2903 <     * subsequently submitted tasks.  Tasks that are in the process of
2904 <     * being submitted or executed concurrently during the course of
2905 <     * this method may or may not be rejected. This method cancels
2906 <     * both existing and unexecuted tasks, in order to permit
2907 <     * termination in the presence of task dependencies. So the method
2908 <     * always returns an empty list (unlike the case for some other
2909 <     * Executors).
2902 >     * Possibly attempts to cancel and/or stop all tasks, and reject
2903 >     * all subsequently submitted tasks.  Invocation has no effect on
2904 >     * execution state if this is the {@link #commonPool}, and no
2905 >     * additional effect if already shut down. Otherwise, tasks that
2906 >     * are in the process of being submitted or executed concurrently
2907 >     * during the course of this method may or may not be
2908 >     * rejected. This method cancels both existing and unexecuted
2909 >     * tasks, in order to permit termination in the presence of task
2910 >     * dependencies. So the method always returns an empty list
2911 >     * (unlike the case for some other Executors).
2912       *
2913       * @return an empty list
2914       * @throws SecurityException if a security manager exists and
# Line 1670 | Line 2918 | public class ForkJoinPool extends Abstra
2918       */
2919      public List<Runnable> shutdownNow() {
2920          checkPermission();
2921 <        tryTerminate(true);
2921 >        if (this != commonPool)
2922 >            tryTerminate(true, true);
2923          return Collections.emptyList();
2924      }
2925  
# Line 1680 | Line 2929 | public class ForkJoinPool extends Abstra
2929       * @return {@code true} if all tasks have completed following shut down
2930       */
2931      public boolean isTerminated() {
2932 <        return runState >= TERMINATED;
2932 >        long c = ctl;
2933 >        return ((c & STOP_BIT) != 0L &&
2934 >                (short)(c >>> TC_SHIFT) == -parallelism);
2935      }
2936  
2937      /**
# Line 1688 | Line 2939 | public class ForkJoinPool extends Abstra
2939       * commenced but not yet completed.  This method may be useful for
2940       * debugging. A return of {@code true} reported a sufficient
2941       * period after shutdown may indicate that submitted tasks have
2942 <     * ignored or suppressed interruption, causing this executor not
2943 <     * to properly terminate.
2942 >     * ignored or suppressed interruption, or are waiting for IO,
2943 >     * causing this executor not to properly terminate. (See the
2944 >     * advisory notes for class {@link ForkJoinTask} stating that
2945 >     * tasks should not normally entail blocking operations.  But if
2946 >     * they do, they must abort them on interrupt.)
2947       *
2948       * @return {@code true} if terminating but not yet terminated
2949       */
2950      public boolean isTerminating() {
2951 <        return (runState & (TERMINATING|TERMINATED)) == TERMINATING;
2951 >        long c = ctl;
2952 >        return ((c & STOP_BIT) != 0L &&
2953 >                (short)(c >>> TC_SHIFT) != -parallelism);
2954      }
2955  
2956      /**
# Line 1703 | Line 2959 | public class ForkJoinPool extends Abstra
2959       * @return {@code true} if this pool has been shut down
2960       */
2961      public boolean isShutdown() {
2962 <        return runState >= SHUTDOWN;
2962 >        return runState < 0;
2963      }
2964  
2965      /**
# Line 1719 | Line 2975 | public class ForkJoinPool extends Abstra
2975       */
2976      public boolean awaitTermination(long timeout, TimeUnit unit)
2977          throws InterruptedException {
2978 <        try {
2979 <            return termination.awaitAdvanceInterruptibly(0, timeout, unit) > 0;
2980 <        } catch(TimeoutException ex) {
2981 <            return false;
2978 >        long nanos = unit.toNanos(timeout);
2979 >        if (isTerminated())
2980 >            return true;
2981 >        long startTime = System.nanoTime();
2982 >        boolean terminated = false;
2983 >        synchronized (this) {
2984 >            for (long waitTime = nanos, millis = 0L;;) {
2985 >                if (terminated = isTerminated() ||
2986 >                    waitTime <= 0L ||
2987 >                    (millis = unit.toMillis(waitTime)) <= 0L)
2988 >                    break;
2989 >                wait(millis);
2990 >                waitTime = nanos - (System.nanoTime() - startTime);
2991 >            }
2992          }
2993 +        return terminated;
2994      }
2995  
2996      /**
# Line 1734 | Line 3001 | public class ForkJoinPool extends Abstra
3001       * {@code isReleasable} must return {@code true} if blocking is
3002       * not necessary. Method {@code block} blocks the current thread
3003       * if necessary (perhaps internally invoking {@code isReleasable}
3004 <     * before actually blocking). The unusual methods in this API
3005 <     * accommodate synchronizers that may, but don't usually, block
3006 <     * for long periods. Similarly, they allow more efficient internal
3007 <     * handling of cases in which additional workers may be, but
3008 <     * usually are not, needed to ensure sufficient parallelism.
3009 <     * Toward this end, implementations of method {@code isReleasable}
3010 <     * must be amenable to repeated invocation.
3004 >     * before actually blocking). These actions are performed by any
3005 >     * thread invoking {@link ForkJoinPool#managedBlock}.  The
3006 >     * unusual methods in this API accommodate synchronizers that may,
3007 >     * but don't usually, block for long periods. Similarly, they
3008 >     * allow more efficient internal handling of cases in which
3009 >     * additional workers may be, but usually are not, needed to
3010 >     * ensure sufficient parallelism.  Toward this end,
3011 >     * implementations of method {@code isReleasable} must be amenable
3012 >     * to repeated invocation.
3013       *
3014       * <p>For example, here is a ManagedBlocker based on a
3015       * ReentrantLock:
# Line 1820 | Line 3089 | public class ForkJoinPool extends Abstra
3089      public static void managedBlock(ManagedBlocker blocker)
3090          throws InterruptedException {
3091          Thread t = Thread.currentThread();
3092 <        if (t instanceof ForkJoinWorkerThread) {
3093 <            ForkJoinWorkerThread w = (ForkJoinWorkerThread) t;
3094 <            w.pool.awaitBlocker(blocker);
3095 <        }
3096 <        else {
3097 <            do {} while (!blocker.isReleasable() && !blocker.block());
3092 >        ForkJoinPool p = ((t instanceof ForkJoinWorkerThread) ?
3093 >                          ((ForkJoinWorkerThread)t).pool : null);
3094 >        while (!blocker.isReleasable()) {
3095 >            if (p == null || p.tryCompensate(null, blocker)) {
3096 >                try {
3097 >                    do {} while (!blocker.isReleasable() && !blocker.block());
3098 >                } finally {
3099 >                    if (p != null)
3100 >                        p.incrementActiveCount();
3101 >                }
3102 >                break;
3103 >            }
3104          }
3105      }
3106  
# Line 1834 | Line 3109 | public class ForkJoinPool extends Abstra
3109      // implement RunnableFuture.
3110  
3111      protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
3112 <        return (RunnableFuture<T>) ForkJoinTask.adapt(runnable, value);
3112 >        return new ForkJoinTask.AdaptedRunnable<T>(runnable, value);
3113      }
3114  
3115      protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
3116 <        return (RunnableFuture<T>) ForkJoinTask.adapt(callable);
3116 >        return new ForkJoinTask.AdaptedCallable<T>(callable);
3117      }
3118  
3119      // Unsafe mechanics
3120 <
3121 <    private static final sun.misc.Unsafe UNSAFE = getUnsafe();
3122 <    private static final long workerCountsOffset =
3123 <        objectFieldOffset("workerCounts", ForkJoinPool.class);
3124 <    private static final long runStateOffset =
3125 <        objectFieldOffset("runState", ForkJoinPool.class);
3126 <    private static final long eventCountOffset =
3127 <        objectFieldOffset("eventCount", ForkJoinPool.class);
3128 <    private static final long eventWaitersOffset =
3129 <        objectFieldOffset("eventWaiters",ForkJoinPool.class);
3130 <    private static final long stealCountOffset =
3131 <        objectFieldOffset("stealCount",ForkJoinPool.class);
3132 <    private static final long spareWaitersOffset =
3133 <        objectFieldOffset("spareWaiters",ForkJoinPool.class);
3134 <
3135 <    private static long objectFieldOffset(String field, Class<?> klazz) {
3120 >    private static final sun.misc.Unsafe U;
3121 >    private static final long CTL;
3122 >    private static final long PARKBLOCKER;
3123 >    private static final int ABASE;
3124 >    private static final int ASHIFT;
3125 >    private static final long NEXTWORKERNUMBER;
3126 >    private static final long STEALCOUNT;
3127 >    private static final long MAINLOCK;
3128 >
3129 >    static {
3130 >        poolNumberGenerator = new AtomicInteger();
3131 >        nextSubmitterSeed = new AtomicInteger(0x55555555);
3132 >        modifyThreadPermission = new RuntimePermission("modifyThread");
3133 >        defaultForkJoinWorkerThreadFactory =
3134 >            new DefaultForkJoinWorkerThreadFactory();
3135 >        submitters = new ThreadSubmitter();
3136 >        int s;
3137          try {
3138 <            return UNSAFE.objectFieldOffset(klazz.getDeclaredField(field));
3139 <        } catch (NoSuchFieldException e) {
3140 <            // Convert Exception to corresponding Error
3141 <            NoSuchFieldError error = new NoSuchFieldError(field);
3142 <            error.initCause(e);
3143 <            throw error;
3138 >            U = getUnsafe();
3139 >            Class<?> k = ForkJoinPool.class;
3140 >            Class<?> ak = ForkJoinTask[].class;
3141 >            CTL = U.objectFieldOffset
3142 >                (k.getDeclaredField("ctl"));
3143 >            NEXTWORKERNUMBER = U.objectFieldOffset
3144 >                (k.getDeclaredField("nextWorkerNumber"));
3145 >            STEALCOUNT = U.objectFieldOffset
3146 >                (k.getDeclaredField("stealCount"));
3147 >            MAINLOCK = U.objectFieldOffset
3148 >                (k.getDeclaredField("mainLock"));
3149 >            Class<?> tk = Thread.class;
3150 >            PARKBLOCKER = U.objectFieldOffset
3151 >                (tk.getDeclaredField("parkBlocker"));
3152 >            ABASE = U.arrayBaseOffset(ak);
3153 >            s = U.arrayIndexScale(ak);
3154 >            ASHIFT = 31 - Integer.numberOfLeadingZeros(s);
3155 >        } catch (Exception e) {
3156 >            throw new Error(e);
3157 >        }
3158 >        if ((s & (s-1)) != 0)
3159 >            throw new Error("data type scale not a power of two");
3160 >        try { // Establish common pool
3161 >            String pp = System.getProperty(propPrefix + "parallelism");
3162 >            String fp = System.getProperty(propPrefix + "threadFactory");
3163 >            String up = System.getProperty(propPrefix + "exceptionHandler");
3164 >            ForkJoinWorkerThreadFactory fac = (fp == null) ?
3165 >                defaultForkJoinWorkerThreadFactory :
3166 >                ((ForkJoinWorkerThreadFactory)ClassLoader.
3167 >                 getSystemClassLoader().loadClass(fp).newInstance());
3168 >            Thread.UncaughtExceptionHandler ueh = (up == null) ? null :
3169 >                ((Thread.UncaughtExceptionHandler)ClassLoader.
3170 >                 getSystemClassLoader().loadClass(up).newInstance());
3171 >            int par;
3172 >            if ((pp == null || (par = Integer.parseInt(pp)) <= 0))
3173 >                par = Runtime.getRuntime().availableProcessors();
3174 >            if (par > MAX_CAP)
3175 >                par = MAX_CAP;
3176 >            commonPoolParallelism = par;
3177 >            int n = par - 1; // precompute submit mask
3178 >            n |= n >>> 1; n |= n >>> 2; n |= n >>> 4;
3179 >            n |= n >>> 8; n |= n >>> 16;
3180 >            int mask = ((n + 1) << 1) - 1;
3181 >            commonPool = new ForkJoinPool(par, mask, fac, ueh);
3182 >        } catch (Exception e) {
3183 >            throw new Error(e);
3184          }
3185      }
3186  
# Line 1895 | Line 3211 | public class ForkJoinPool extends Abstra
3211              }
3212          }
3213      }
3214 +
3215   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines