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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines