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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines