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.81 by jsr166, Mon Sep 20 20:42:36 2010 UTC vs.
Revision 1.134 by jsr166, Sun Oct 21 06:40:20 2012 UTC

# Line 1 | Line 1
1   /*
2   * Written by Doug Lea with assistance from members of JCP JSR-166
3   * Expert Group and released to the public domain, as explained at
4 < * http://creativecommons.org/licenses/publicdomain
4 > * http://creativecommons.org/publicdomain/zero/1.0/
5   */
6  
7   package jsr166y;
8
8   import java.util.ArrayList;
9   import java.util.Arrays;
10   import java.util.Collection;
11   import java.util.Collections;
12   import java.util.List;
13 + import java.util.Random;
14   import java.util.concurrent.AbstractExecutorService;
15   import java.util.concurrent.Callable;
16   import java.util.concurrent.ExecutorService;
# Line 18 | Line 18 | import java.util.concurrent.Future;
18   import java.util.concurrent.RejectedExecutionException;
19   import java.util.concurrent.RunnableFuture;
20   import java.util.concurrent.TimeUnit;
21 import java.util.concurrent.TimeoutException;
21   import java.util.concurrent.atomic.AtomicInteger;
22 < import java.util.concurrent.locks.LockSupport;
23 < import java.util.concurrent.locks.ReentrantLock;
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 32 | Line 32 | import java.util.concurrent.locks.Reentr
32   * <p>A {@code ForkJoinPool} differs from other kinds of {@link
33   * ExecutorService} mainly by virtue of employing
34   * <em>work-stealing</em>: all threads in the pool attempt to find and
35 < * execute subtasks created by other active tasks (eventually blocking
36 < * waiting for work if none exist). This enables efficient processing
37 < * when most tasks spawn other subtasks (as do most {@code
38 < * ForkJoinTask}s). When setting <em>asyncMode</em> to true in
39 < * constructors, {@code ForkJoinPool}s may also be appropriate for use
40 < * with event-style tasks that are never joined.
35 > * execute tasks submitted to the pool and/or created by other active
36 > * tasks (eventually blocking waiting for work if none exist). This
37 > * enables efficient processing when most tasks spawn other subtasks
38 > * (as do most {@code ForkJoinTask}s), as well as when many small
39 > * tasks are submitted to the pool from external clients.  Especially
40 > * when setting <em>asyncMode</em> to true in constructors, {@code
41 > * ForkJoinPool}s may also be appropriate for use with event-style
42 > * tasks that are never joined.
43   *
44   * <p>A {@code ForkJoinPool} is constructed with a given target
45   * parallelism level; by default, equal to the number of available
# Line 57 | Line 59 | import java.util.concurrent.locks.Reentr
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 following
63 < * table. These are designed to be used by clients not already engaged
64 < * in fork/join computations in the current pool.  The main forms of
65 < * these methods accept instances of {@code ForkJoinTask}, but
66 < * overloaded forms also allow mixed execution of plain {@code
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.
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 100 | Line 103 | import java.util.concurrent.locks.Reentr
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 < * }
109 < * </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 125 | 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.)
146 <     *
147 <     * Beyond work-stealing support and essential bookkeeping, the
148 <     * main responsibility of this framework is to take actions when
149 <     * one worker is waiting to join a task stolen (or always held by)
150 <     * another.  Because we are multiplexing many tasks on to a pool
151 <     * of workers, we can't just let them block (as in Thread.join).
152 <     * We also cannot just reassign the joiner's run-time stack with
153 <     * another and replace it later, which would be a form of
154 <     * "continuation", that even if possible is not necessarily a good
155 <     * idea. Given that the creation costs of most threads on most
156 <     * systems mainly surrounds setting up runtime stacks, thread
157 <     * creation and switching is usually not much more expensive than
158 <     * stack creation and switching, and is more flexible). Instead we
159 <     * combine two tactics:
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 take tasks from
220 >     * themselves or each other. We cannot negate this in the
221 >     * implementation of other management responsibilities. The main
222 >     * tactic for avoiding bottlenecks is packing nearly all
223 >     * essentially atomic control state into two volatile variables
224 >     * that are by far most often read (not written) as status and
225 >     * consistency checks.
226 >     *
227 >     * Field "ctl" contains 64 bits holding all the information needed
228 >     * to atomically decide to add, inactivate, enqueue (on an event
229 >     * queue), dequeue, and/or re-activate workers.  To enable this
230 >     * packing, we restrict maximum parallelism to (1<<15)-1 (which is
231 >     * far in excess of normal operating range) to allow ids, counts,
232 >     * and their negations (used for thresholding) to fit into 16bit
233 >     * fields.
234 >     *
235 >     * Field "runState" contains 32 bits needed to register and
236 >     * deregister WorkQueues, as well as to enable shutdown. It is
237 >     * only modified under a lock (normally briefly held, but
238 >     * occasionally protecting allocations and resizings) but even
239 >     * when locked remains available to check consistency.
240 >     *
241 >     * Recording WorkQueues.  WorkQueues are recorded in the
242 >     * "workQueues" array that is created upon pool construction and
243 >     * expanded if necessary.  Updates to the array while recording
244 >     * new workers and unrecording terminated ones are protected from
245 >     * each other by a lock but the array is otherwise concurrently
246 >     * readable, and accessed directly.  To simplify index-based
247 >     * operations, the array size is always a power of two, and all
248 >     * readers must tolerate null slots. Shared (submission) queues
249 >     * are at even indices, worker queues at odd indices. Grouping
250 >     * them together in this way simplifies and speeds up task
251 >     * scanning.
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.  Method
161 <     *      ForkJoinWorkerThread.helpJoinTask tracks joining->stealing
162 <     *      links to try to find such a task.
351 >     *      would be running if the steal had not occurred.
352       *
353       *   Compensating: Unless there are already enough live threads,
354 <     *      method helpMaintainParallelism() may create or
355 <     *      re-activate a spare thread to compensate for blocked
167 <     *      joiners until they unblock.
354 >     *      method tryCompensate() may create or re-activate a spare
355 >     *      thread to compensate for blocked joiners until they unblock.
356       *
357 <     * It is impossible to keep exactly the target (parallelism)
358 <     * number of threads running at any given time.  Determining
359 <     * existence of conservatively safe helping targets, the
360 <     * availability of already-created spares, and the apparent need
361 <     * to create new spares are all racy and require heuristic
362 <     * guidance, so we rely on multiple retries of each.  Compensation
363 <     * occurs in slow-motion. It is triggered only upon timeouts of
176 <     * Object.wait used for joins. This reduces poor decisions that
177 <     * would otherwise be made when threads are waiting for others
178 <     * that are stalled because of unrelated activities such as
179 <     * garbage collection.
357 >     * A third form (implemented in tryRemoveAndExec and
358 >     * tryPollForAndExec) amounts to helping a hypothetical
359 >     * compensator: If we can readily tell that a possible action of a
360 >     * compensator is to steal and execute the task being joined, the
361 >     * joining thread can do so directly, without the need for a
362 >     * compensation thread (although at the expense of larger run-time
363 >     * stacks, but the tradeoff is typically worthwhile).
364       *
365       * The ManagedBlocker extension API can't use helping so relies
366       * only on compensation in method awaitBlocker.
367       *
368 <     * The main throughput advantages of work-stealing stem from
369 <     * decentralized control -- workers mostly steal tasks from each
370 <     * other. We do not want to negate this by creating bottlenecks
371 <     * implementing other management responsibilities. So we use a
372 <     * collection of techniques that avoid, reduce, or cope well with
373 <     * contention. These entail several instances of bit-packing into
374 <     * CASable fields to maintain only the minimally required
375 <     * atomicity. To enable such packing, we restrict maximum
376 <     * parallelism to (1<<15)-1 (enabling twice this (to accommodate
377 <     * unbalanced increments and decrements) to fit into a 16 bit
378 <     * field, which is far in excess of normal operating range.  Even
379 <     * though updates to some of these bookkeeping fields do sometimes
380 <     * contend with each other, they don't normally cache-contend with
381 <     * updates to others enough to warrant memory padding or
382 <     * isolation. So they are all held as fields of ForkJoinPool
383 <     * objects.  The main capabilities are as follows:
384 <     *
385 <     * 1. Creating and removing workers. Workers are recorded in the
386 <     * "workers" array. This is an array as opposed to some other data
387 <     * structure to support index-based random steals by workers.
388 <     * Updates to the array recording new workers and unrecording
389 <     * terminated ones are protected from each other by a lock
390 <     * (workerLock) but the array is otherwise concurrently readable,
391 <     * and accessed directly by workers. To simplify index-based
392 <     * operations, the array size is always a power of two, and all
393 <     * readers must tolerate null slots. Currently, all worker thread
394 <     * creation is on-demand, triggered by task submissions,
395 <     * replacement of terminated workers, and/or compensation for
396 <     * blocked workers. However, all other support code is set up to
213 <     * work with other policies.
214 <     *
215 <     * To ensure that we do not hold on to worker references that
216 <     * would prevent GC, ALL accesses to workers are via indices into
217 <     * the workers array (which is one source of some of the unusual
218 <     * code constructions here). In essence, the workers array serves
219 <     * as a WeakReference mechanism. Thus for example the event queue
220 <     * stores worker indices, not worker references. Access to the
221 <     * workers in associated methods (for example releaseEventWaiters)
222 <     * must both index-check and null-check the IDs. All such accesses
223 <     * ignore bad IDs by returning out early from what they are doing,
224 <     * since this can only be associated with shutdown, in which case
225 <     * it is OK to give up. On termination, we just clobber these
226 <     * data structures without trying to use them.
227 <     *
228 <     * 2. Bookkeeping for dynamically adding and removing workers. We
229 <     * aim to approximately maintain the given level of parallelism.
230 <     * When some workers are known to be blocked (on joins or via
231 <     * ManagedBlocker), we may create or resume others to take their
232 <     * place until they unblock (see below). Implementing this
233 <     * requires counts of the number of "running" threads (i.e., those
234 <     * that are neither blocked nor artificially suspended) as well as
235 <     * the total number.  These two values are packed into one field,
236 <     * "workerCounts" because we need accurate snapshots when deciding
237 <     * to create, resume or suspend.  Note however that the
238 <     * correspondence of these counts to reality is not guaranteed. In
239 <     * particular updates for unblocked threads may lag until they
240 <     * actually wake up.
241 <     *
242 <     * 3. Maintaining global run state. The run state of the pool
243 <     * consists of a runLevel (SHUTDOWN, TERMINATING, etc) similar to
244 <     * those in other Executor implementations, as well as a count of
245 <     * "active" workers -- those that are, or soon will be, or
246 <     * recently were executing tasks. The runLevel and active count
247 <     * are packed together in order to correctly trigger shutdown and
248 <     * termination. Without care, active counts can be subject to very
249 <     * high contention.  We substantially reduce this contention by
250 <     * relaxing update rules.  A worker must claim active status
251 <     * prospectively, by activating if it sees that a submitted or
252 <     * stealable task exists (it may find after activating that the
253 <     * task no longer exists). It stays active while processing this
254 <     * task (if it exists) and any other local subtasks it produces,
255 <     * until it cannot find any other tasks. It then tries
256 <     * inactivating (see method preStep), but upon update contention
257 <     * instead scans for more tasks, later retrying inactivation if it
258 <     * doesn't find any.
259 <     *
260 <     * 4. Managing idle workers waiting for tasks. We cannot let
261 <     * workers spin indefinitely scanning for tasks when none are
262 <     * available. On the other hand, we must quickly prod them into
263 <     * action when new tasks are submitted or generated.  We
264 <     * park/unpark these idle workers using an event-count scheme.
265 <     * Field eventCount is incremented upon events that may enable
266 <     * workers that previously could not find a task to now find one:
267 <     * Submission of a new task to the pool, or another worker pushing
268 <     * a task onto a previously empty queue.  (We also use this
269 <     * mechanism for configuration and termination actions that
270 <     * require wakeups of idle workers).  Each worker maintains its
271 <     * last known event count, and blocks when a scan for work did not
272 <     * find a task AND its lastEventCount matches the current
273 <     * eventCount. Waiting idle workers are recorded in a variant of
274 <     * Treiber stack headed by field eventWaiters which, when nonzero,
275 <     * encodes the thread index and count awaited for by the worker
276 <     * thread most recently calling eventSync. This thread in turn has
277 <     * a record (field nextEventWaiter) for the next waiting worker.
278 <     * In addition to allowing simpler decisions about need for
279 <     * wakeup, the event count bits in eventWaiters serve the role of
280 <     * tags to avoid ABA errors in Treiber stacks. Upon any wakeup,
281 <     * released threads also try to release at most two others.  The
282 <     * net effect is a tree-like diffusion of signals, where released
283 <     * threads (and possibly others) help with unparks.  To further
284 <     * reduce contention effects a bit, failed CASes to increment
285 <     * field eventCount are tolerated without retries in signalWork.
286 <     * Conceptually they are merged into the same event, which is OK
287 <     * when their only purpose is to enable workers to scan for work.
288 <     *
289 <     * 5. Managing suspension of extra workers. When a worker notices
290 <     * (usually upon timeout of a wait()) that there are too few
291 <     * running threads, we may create a new thread to maintain
292 <     * parallelism level, or at least avoid starvation. Usually, extra
293 <     * threads are needed for only very short periods, yet join
294 <     * dependencies are such that we sometimes need them in
295 <     * bursts. Rather than create new threads each time this happens,
296 <     * we suspend no-longer-needed extra ones as "spares". For most
297 <     * purposes, we don't distinguish "extra" spare threads from
298 <     * normal "core" threads: On each call to preStep (the only point
299 <     * at which we can do this) a worker checks to see if there are
300 <     * now too many running workers, and if so, suspends itself.
301 <     * Method helpMaintainParallelism looks for suspended threads to
302 <     * resume before considering creating a new replacement. The
303 <     * spares themselves are encoded on another variant of a Treiber
304 <     * Stack, headed at field "spareWaiters".  Note that the use of
305 <     * spares is intrinsically racy.  One thread may become a spare at
306 <     * about the same time as another is needlessly being created. We
307 <     * counteract this and related slop in part by requiring resumed
308 <     * spares to immediately recheck (in preStep) to see whether they
309 <     * should re-suspend.
310 <     *
311 <     * 6. Killing off unneeded workers. A timeout mechanism is used to
312 <     * shed unused workers: The oldest (first) event queue waiter uses
313 <     * a timed rather than hard wait. When this wait times out without
314 <     * a normal wakeup, it tries to shutdown any one (for convenience
315 <     * the newest) other spare or event waiter via
316 <     * tryShutdownUnusedWorker. This eventually reduces the number of
317 <     * worker threads to a minimum of one after a long enough period
318 <     * without use.
319 <     *
320 <     * 7. Deciding when to create new workers. The main dynamic
321 <     * control in this class is deciding when to create extra threads
322 <     * in method helpMaintainParallelism. We would like to keep
323 <     * exactly #parallelism threads running, which is an impossible
324 <     * task. We always need to create one when the number of running
325 <     * threads would become zero and all workers are busy. Beyond
326 <     * this, we must rely on heuristics that work well in the
327 <     * presence of transient phenomena such as GC stalls, dynamic
328 <     * compilation, and wake-up lags. These transients are extremely
329 <     * common -- we are normally trying to fully saturate the CPUs on
330 <     * a machine, so almost any activity other than running tasks
331 <     * impedes accuracy. Our main defense is to allow parallelism to
332 <     * lapse for a while during joins, and use a timeout to see if,
333 <     * after the resulting settling, there is still a need for
334 <     * additional workers.  This also better copes with the fact that
335 <     * some of the methods in this class tend to never become compiled
336 <     * (but are interpreted), so some components of the entire set of
337 <     * controls might execute 100 times faster than others. And
338 <     * similarly for cases where the apparent lack of work is just due
339 <     * to GC stalls and other transient system activity.
368 >     * The algorithm in tryHelpStealer entails a form of "linear"
369 >     * helping: Each worker records (in field currentSteal) the most
370 >     * recent task it stole from some other worker. Plus, it records
371 >     * (in field currentJoin) the task it is currently actively
372 >     * joining. Method tryHelpStealer uses these markers to try to
373 >     * find a worker to help (i.e., steal back a task from and execute
374 >     * it) that could hasten completion of the actively joined task.
375 >     * In essence, the joiner executes a task that would be on its own
376 >     * local deque had the to-be-joined task not been stolen. This may
377 >     * be seen as a conservative variant of the approach in Wagner &
378 >     * Calder "Leapfrogging: a portable technique for implementing
379 >     * efficient futures" SIGPLAN Notices, 1993
380 >     * (http://portal.acm.org/citation.cfm?id=155354). It differs in
381 >     * that: (1) We only maintain dependency links across workers upon
382 >     * steals, rather than use per-task bookkeeping.  This sometimes
383 >     * requires a linear scan of 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 <     * Beware that there is a lot of representation-level coupling
398 >     * It is impossible to keep exactly the target parallelism number
399 >     * of threads running at any given time.  Determining the
400 >     * existence of conservatively safe helping targets, the
401 >     * availability of already-created spares, and the apparent need
402 >     * to create new spares are all racy, so we rely on multiple
403 >     * retries of each.  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 >     * 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 the required read orderings (which are sometimes
445 <     * critical). Also several occurrences of the unusual "do {}
446 <     * while (!cas...)" which is the simplest way to force an update of
447 <     * a CAS'ed variable. There are also other coding oddities that
448 <     * help some methods perform reasonably even when interpreted (not
449 <     * compiled), at the expense of some messy constructions that
450 <     * reduce byte code counts.
451 <     *
452 <     * The order of declarations in this file is: (1) statics (2)
453 <     * fields (along with constants used when unpacking some of them)
454 <     * (3) internal control methods (4) callbacks and other support
455 <     * for ForkJoinTask and ForkJoinWorkerThread classes, (5) exported
456 <     * 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 392 | 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 >        volatile 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 <     * The time to block in a join (see awaitJoin) before checking if
656 <     * a new worker should be (re)started to maintain parallelism
657 <     * level. The value should be short enough to maintain global
658 <     * responsiveness and progress but long enough to avoid
659 <     * counterproductive firings during GC stalls or unrelated system
660 <     * activity, and to not bog down systems with continual re-firings
661 <     * on GCs or legitimately long waits.
662 <     */
663 <    private static final long JOIN_TIMEOUT_MILLIS = 250L; // 4 per second
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 <     * The wakeup interval (in nanoseconds) for the oldest worker
672 <     * waiting for an event to invoke tryShutdownUnusedWorker to
673 <     * shrink the number of workers.  The exact value does not matter
674 <     * too much. It must be short enough to release resources during
675 <     * sustained periods of idleness, but not so short that threads
676 <     * are continually re-created.
677 <     */
678 <    private static final long SHRINK_RATE_NANOS =
679 <        30L * 1000L * 1000L * 1000L; // 2 per minute
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 <     * Absolute bound for parallelism level. Twice this number plus
693 <     * one (i.e., 0xfff) must fit into a 16bit field to enable
694 <     * word-packing for some counts and indices.
695 <     */
696 <    private static final int MAX_WORKERS   = 0x7fff;
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 <     * Array holding all worker threads in the pool.  Array size must
720 <     * be a power of two.  Updates and replacements are protected by
721 <     * workerLock, but the array is always kept in a consistent enough
722 <     * state to be randomly accessed without locking by workers
723 <     * performing work-stealing, as well as other traversal-based
724 <     * methods in this class. All readers must tolerate that some
725 <     * array slots may be null.
726 <     */
727 <    volatile ForkJoinWorkerThread[] workers;
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 <     * Queue for external submissions.
741 <     */
742 <    private final LinkedTransferQueue<ForkJoinTask<?>> submissionQueue;
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 <     * Lock protecting updates to workers array.
760 <     */
761 <    private final ReentrantLock workerLock;
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 <     * Latch released upon termination.
784 <     */
785 <    private final Phaser termination;
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 <     * Creation factory for worker threads.
791 <     */
792 <    private final ForkJoinWorkerThreadFactory factory;
789 >        /**
790 >         * Returns next task, if one exists, in order specified by mode.
791 >         */
792 >        final ForkJoinTask<?> peek() {
793 >            ForkJoinTask<?>[] a = array; int m;
794 >            if (a == null || (m = a.length - 1) < 0)
795 >                return null;
796 >            int i = mode == 0 ? top - 1 : base;
797 >            int j = ((i & m) << ASHIFT) + ABASE;
798 >            return (ForkJoinTask<?>)U.getObjectVolatile(a, j);
799 >        }
800  
801 <    /**
802 <     * Sum of per-thread steal counts, updated only when threads are
803 <     * idle or terminating.
804 <     */
805 <    private volatile long stealCount;
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 <     * Encoded record of top of Treiber stack of threads waiting for
817 <     * events. The top 32 bits contain the count being waited for. The
818 <     * bottom 16 bits contains one plus the pool index of waiting
819 <     * worker thread. (Bits 16-31 are unused.)
820 <     */
821 <    private volatile long eventWaiters;
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 <    private static final int  EVENT_COUNT_SHIFT = 32;
832 <    private static final long WAITER_ID_MASK    = (1L << 16) - 1L;
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 <    /**
867 <     * A counter for events that may wake up worker threads:
868 <     *   - Submission of a new task to the pool
869 <     *   - A worker pushing a task on an empty queue
870 <     *   - termination
871 <     */
872 <    private volatile int eventCount;
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 <     * Encoded record of top of Treiber stack of spare threads waiting
878 <     * for resumption. The top 16 bits contain an arbitrary count to
879 <     * avoid ABA effects. The bottom 16bits contains one plus the pool
880 <     * index of waiting worker thread.
881 <     */
882 <    private volatile int spareWaiters;
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 0 if no progress can be made, else positive
924 >         * (this unusual convention simplifies use with tryHelpStealer.)
925 >         */
926 >        final int tryRemoveAndExec(ForkJoinTask<?> task) {
927 >            int stat = 1;
928 >            boolean removed = false, empty = true;
929 >            ForkJoinTask<?>[] a; int m, s, b, n;
930 >            if ((a = array) != null && (m = a.length - 1) >= 0 &&
931 >                (n = (s = top) - (b = base)) > 0) {
932 >                for (ForkJoinTask<?> t;;) {           // traverse from s to b
933 >                    int j = ((--s & m) << ASHIFT) + ABASE;
934 >                    t = (ForkJoinTask<?>)U.getObjectVolatile(a, j);
935 >                    if (t == null)                    // inconsistent length
936 >                        break;
937 >                    else if (t == task) {
938 >                        if (s + 1 == top) {           // pop
939 >                            if (!U.compareAndSwapObject(a, j, task, null))
940 >                                break;
941 >                            top = s;
942 >                            removed = true;
943 >                        }
944 >                        else if (base == b)           // replace with proxy
945 >                            removed = U.compareAndSwapObject(a, j, task,
946 >                                                             new EmptyTask());
947 >                        break;
948 >                    }
949 >                    else if (t.status >= 0)
950 >                        empty = false;
951 >                    else if (s + 1 == top) {          // pop and throw away
952 >                        if (U.compareAndSwapObject(a, j, t, null))
953 >                            top = s;
954 >                        break;
955 >                    }
956 >                    if (--n == 0) {
957 >                        if (!empty && base == b)
958 >                            stat = 0;
959 >                        break;
960 >                    }
961 >                }
962 >            }
963 >            if (removed)
964 >                task.doExec();
965 >            return stat;
966 >        }
967  
968 <    private static final int SPARE_COUNT_SHIFT = 16;
969 <    private static final int SPARE_ID_MASK     = (1 << 16) - 1;
968 >        /**
969 >         * Executes a top-level task and any local tasks remaining
970 >         * after execution.
971 >         */
972 >        final void runTask(ForkJoinTask<?> t) {
973 >            if (t != null) {
974 >                currentSteal = t;
975 >                t.doExec();
976 >                if (top != base) {       // process remaining local tasks
977 >                    if (mode == 0)
978 >                        popAndExecAll();
979 >                    else
980 >                        pollAndExecAll();
981 >                }
982 >                ++nsteals;
983 >                currentSteal = null;
984 >            }
985 >        }
986 >
987 >        /**
988 >         * Executes a non-top-level (stolen) task.
989 >         */
990 >        final void runSubtask(ForkJoinTask<?> t) {
991 >            if (t != null) {
992 >                ForkJoinTask<?> ps = currentSteal;
993 >                currentSteal = t;
994 >                t.doExec();
995 >                currentSteal = ps;
996 >            }
997 >        }
998 >
999 >        /**
1000 >         * Returns true if owned and not known to be blocked.
1001 >         */
1002 >        final boolean isApparentlyUnblocked() {
1003 >            Thread wt; Thread.State s;
1004 >            return (eventCount >= 0 &&
1005 >                    (wt = owner) != null &&
1006 >                    (s = wt.getState()) != Thread.State.BLOCKED &&
1007 >                    s != Thread.State.WAITING &&
1008 >                    s != Thread.State.TIMED_WAITING);
1009 >        }
1010 >
1011 >        /**
1012 >         * If this owned and is not already interrupted, try to
1013 >         * interrupt and/or unpark, ignoring exceptions.
1014 >         */
1015 >        final void interruptOwner() {
1016 >            Thread wt, p;
1017 >            if ((wt = owner) != null && !wt.isInterrupted()) {
1018 >                try {
1019 >                    wt.interrupt();
1020 >                } catch (SecurityException ignore) {
1021 >                }
1022 >            }
1023 >            if ((p = parker) != null)
1024 >                U.unpark(p);
1025 >        }
1026 >
1027 >        // Unsafe mechanics
1028 >        private static final sun.misc.Unsafe U;
1029 >        private static final long RUNSTATE;
1030 >        private static final int ABASE;
1031 >        private static final int ASHIFT;
1032 >        static {
1033 >            int s;
1034 >            try {
1035 >                U = getUnsafe();
1036 >                Class<?> k = WorkQueue.class;
1037 >                Class<?> ak = ForkJoinTask[].class;
1038 >                RUNSTATE = U.objectFieldOffset
1039 >                    (k.getDeclaredField("runState"));
1040 >                ABASE = U.arrayBaseOffset(ak);
1041 >                s = U.arrayIndexScale(ak);
1042 >            } catch (Exception e) {
1043 >                throw new Error(e);
1044 >            }
1045 >            if ((s & (s-1)) != 0)
1046 >                throw new Error("data type scale not a power of two");
1047 >            ASHIFT = 31 - Integer.numberOfLeadingZeros(s);
1048 >        }
1049 >    }
1050  
1051      /**
1052 <     * Lifecycle control. The low word contains the number of workers
1053 <     * that are (probably) executing tasks. This value is atomically
1054 <     * incremented before a worker gets a task to run, and decremented
1055 <     * when a worker has no tasks and cannot find any.  Bits 16-18
1056 <     * contain runLevel value. When all are zero, the pool is
527 <     * running. Level transitions are monotonic (running -> shutdown
528 <     * -> terminating -> terminated) so each transition adds a bit.
529 <     * These are bundled together to ensure consistent read for
530 <     * termination checks (i.e., that runLevel is at least SHUTDOWN
531 <     * and active threads is zero).
1052 >     * Per-thread records for threads that submit to pools. Currently
1053 >     * holds only pseudo-random seed / index that is used to choose
1054 >     * submission queues in method doSubmit. In the future, this may
1055 >     * also incorporate a means to implement different task rejection
1056 >     * and resubmission policies.
1057       *
1058 <     * Notes: Most direct CASes are dependent on these bitfield
1059 <     * positions.  Also, this field is non-private to enable direct
1060 <     * performance-sensitive CASes in ForkJoinWorkerThread.
1058 >     * Seeds for submitters and workers/workQueues work in basically
1059 >     * the same way but are initialized and updated using slightly
1060 >     * different mechanics. Both are initialized using the same
1061 >     * approach as in class ThreadLocal, where successive values are
1062 >     * unlikely to collide with previous values. This is done during
1063 >     * registration for workers, but requires a separate AtomicInteger
1064 >     * for submitters. Seeds are then randomly modified upon
1065 >     * collisions using xorshifts, which requires a non-zero seed.
1066       */
1067 <    volatile int runState;
1067 >    static final class Submitter {
1068 >        int seed;
1069 >        Submitter() {
1070 >            int s = nextSubmitterSeed.getAndAdd(SEED_INCREMENT);
1071 >            seed = (s == 0) ? 1 : s; // ensure non-zero
1072 >        }
1073 >    }
1074 >
1075 >    /** ThreadLocal class for Submitters */
1076 >    static final class ThreadSubmitter extends ThreadLocal<Submitter> {
1077 >        public Submitter initialValue() { return new Submitter(); }
1078 >    }
1079  
1080 <    // Note: The order among run level values matters.
540 <    private static final int RUNLEVEL_SHIFT     = 16;
541 <    private static final int SHUTDOWN           = 1 << RUNLEVEL_SHIFT;
542 <    private static final int TERMINATING        = 1 << (RUNLEVEL_SHIFT + 1);
543 <    private static final int TERMINATED         = 1 << (RUNLEVEL_SHIFT + 2);
544 <    private static final int ACTIVE_COUNT_MASK  = (1 << RUNLEVEL_SHIFT) - 1;
1080 >    // static fields (initialized in static initializer below)
1081  
1082      /**
1083 <     * Holds number of total (i.e., created and not yet terminated)
1084 <     * and running (i.e., not blocked on joins or other managed sync)
549 <     * threads, packed together to ensure consistent snapshot when
550 <     * making decisions about creating and suspending spare
551 <     * threads. Updated only by CAS. Note that adding a new worker
552 <     * requires incrementing both counts, since workers start off in
553 <     * running state.
1083 >     * Creates a new ForkJoinWorkerThread. This factory is used unless
1084 >     * overridden in ForkJoinPool constructors.
1085       */
1086 <    private volatile int workerCounts;
1087 <
557 <    private static final int TOTAL_COUNT_SHIFT  = 16;
558 <    private static final int RUNNING_COUNT_MASK = (1 << TOTAL_COUNT_SHIFT) - 1;
559 <    private static final int ONE_RUNNING        = 1;
560 <    private static final int ONE_TOTAL          = 1 << TOTAL_COUNT_SHIFT;
1086 >    public static final ForkJoinWorkerThreadFactory
1087 >        defaultForkJoinWorkerThreadFactory;
1088  
1089      /**
1090 <     * The target parallelism level.
564 <     * Accessed directly by ForkJoinWorkerThreads.
1090 >     * Generator for assigning sequence numbers as pool names.
1091       */
1092 <    final int parallelism;
1092 >    private static final AtomicInteger poolNumberGenerator;
1093  
1094      /**
1095 <     * True if use local fifo, not default lifo, for local polling
1096 <     * Read by, and replicated by ForkJoinWorkerThreads
1095 >     * Generator for initial hashes/seeds for submitters. Accessed by
1096 >     * Submitter class constructor.
1097       */
1098 <    final boolean locallyFifo;
1098 >    static final AtomicInteger nextSubmitterSeed;
1099  
1100      /**
1101 <     * The uncaught exception handler used when any worker abruptly
1102 <     * terminates.
1101 >     * Permission required for callers of methods that may start or
1102 >     * kill threads.
1103       */
1104 <    private final Thread.UncaughtExceptionHandler ueh;
1104 >    private static final RuntimePermission modifyThreadPermission;
1105  
1106      /**
1107 <     * Pool number, just for assigning useful names to worker threads
1107 >     * Per-thread submission bookkeeping. Shared across all pools
1108 >     * to reduce ThreadLocal pollution and because random motion
1109 >     * to avoid contention in one pool is likely to hold for others.
1110       */
1111 <    private final int poolNumber;
1111 >    private static final ThreadSubmitter submitters;
1112  
1113 <    // Utilities for CASing fields. Note that most of these
586 <    // are usually manually inlined by callers
1113 >    // static constants
1114  
1115      /**
1116 <     * Increments running count part of workerCounts
1116 >     * The wakeup interval (in nanoseconds) for a worker waiting for a
1117 >     * task when the pool is quiescent to instead try to shrink the
1118 >     * number of workers.  The exact value does not matter too
1119 >     * much. It must be short enough to release resources during
1120 >     * sustained periods of idleness, but not so short that threads
1121 >     * are continually re-created.
1122       */
1123 <    final void incrementRunningCount() {
1124 <        int c;
593 <        do {} while (!UNSAFE.compareAndSwapInt(this, workerCountsOffset,
594 <                                               c = workerCounts,
595 <                                               c + ONE_RUNNING));
596 <    }
1123 >    private static final long SHRINK_RATE =
1124 >        4L * 1000L * 1000L * 1000L; // 4 seconds
1125  
1126      /**
1127 <     * Tries to decrement running count unless already zero
1127 >     * The timeout value for attempted shrinkage, includes
1128 >     * some slop to cope with system timer imprecision.
1129       */
1130 <    final boolean tryDecrementRunningCount() {
602 <        int wc = workerCounts;
603 <        if ((wc & RUNNING_COUNT_MASK) == 0)
604 <            return false;
605 <        return UNSAFE.compareAndSwapInt(this, workerCountsOffset,
606 <                                        wc, wc - ONE_RUNNING);
607 <    }
1130 >    private static final long SHRINK_TIMEOUT = SHRINK_RATE - (SHRINK_RATE / 10);
1131  
1132      /**
1133 <     * Forces decrement of encoded workerCounts, awaiting nonzero if
1134 <     * (rarely) necessary when other count updates lag.
1135 <     *
1136 <     * @param dr -- either zero or ONE_RUNNING
1137 <     * @param dt -- either zero or ONE_TOTAL
1138 <     */
1139 <    private void decrementWorkerCounts(int dr, int dt) {
1140 <        for (;;) {
1141 <            int wc = workerCounts;
1142 <            if ((wc & RUNNING_COUNT_MASK)  - dr < 0 ||
1143 <                (wc >>> TOTAL_COUNT_SHIFT) - dt < 0) {
1144 <                if ((runState & TERMINATED) != 0)
1145 <                    return; // lagging termination on a backout
1146 <                Thread.yield();
1147 <            }
1148 <            if (UNSAFE.compareAndSwapInt(this, workerCountsOffset,
1149 <                                         wc, wc - (dr + dt)))
1150 <                return;
1151 <        }
1152 <    }
1133 >     * The maximum stolen->joining link depth allowed in method
1134 >     * tryHelpStealer.  Must be a power of two. This value also
1135 >     * controls the maximum number of times to try to help join a task
1136 >     * without any apparent progress or change in pool state before
1137 >     * giving up and blocking (see awaitJoin).  Depths for legitimate
1138 >     * chains are unbounded, but we use a fixed constant to avoid
1139 >     * (otherwise unchecked) cycles and to bound staleness of
1140 >     * traversal parameters at the expense of sometimes blocking when
1141 >     * we could be helping.
1142 >     */
1143 >    private static final int MAX_HELP = 64;
1144 >
1145 >    /**
1146 >     * Secondary time-based bound (in nanosecs) for helping attempts
1147 >     * before trying compensated blocking in awaitJoin. Used in
1148 >     * conjunction with MAX_HELP to reduce variance due to different
1149 >     * polling rates associated with different helping options. The
1150 >     * value should roughly approximate the time required to create
1151 >     * and/or activate a worker thread.
1152 >     */
1153 >    private static final long COMPENSATION_DELAY = 1L << 18; // ~0.25 millisec
1154 >
1155 >    /**
1156 >     * Increment for seed generators. See class ThreadLocal for
1157 >     * explanation.
1158 >     */
1159 >    private static final int SEED_INCREMENT = 0x61c88647;
1160 >
1161 >    /**
1162 >     * Bits and masks for control variables
1163 >     *
1164 >     * Field ctl is a long packed with:
1165 >     * AC: Number of active running workers minus target parallelism (16 bits)
1166 >     * TC: Number of total workers minus target parallelism (16 bits)
1167 >     * ST: true if pool is terminating (1 bit)
1168 >     * EC: the wait count of top waiting thread (15 bits)
1169 >     * ID: poolIndex of top of Treiber stack of waiters (16 bits)
1170 >     *
1171 >     * When convenient, we can extract the upper 32 bits of counts and
1172 >     * the lower 32 bits of queue state, u = (int)(ctl >>> 32) and e =
1173 >     * (int)ctl.  The ec field is never accessed alone, but always
1174 >     * together with id and st. The offsets of counts by the target
1175 >     * parallelism and the positionings of fields makes it possible to
1176 >     * perform the most common checks via sign tests of fields: When
1177 >     * ac is negative, there are not enough active workers, when tc is
1178 >     * negative, there are not enough total workers, and when e is
1179 >     * negative, the pool is terminating.  To deal with these possibly
1180 >     * negative fields, we use casts in and out of "short" and/or
1181 >     * signed shifts to maintain signedness.
1182 >     *
1183 >     * When a thread is queued (inactivated), its eventCount field is
1184 >     * set negative, which is the only way to tell if a worker is
1185 >     * prevented from executing tasks, even though it must continue to
1186 >     * scan for them to avoid queuing races. Note however that
1187 >     * eventCount updates lag releases so usage requires care.
1188 >     *
1189 >     * Field runState is an int packed with:
1190 >     * SHUTDOWN: true if shutdown is enabled (1 bit)
1191 >     * SEQ:  a sequence number updated upon (de)registering workers (30 bits)
1192 >     * INIT: set true after workQueues array construction (1 bit)
1193 >     *
1194 >     * The sequence number enables simple consistency checks:
1195 >     * Staleness of read-only operations on the workQueues array can
1196 >     * be checked by comparing runState before vs after the reads.
1197 >     */
1198 >
1199 >    // bit positions/shifts for fields
1200 >    private static final int  AC_SHIFT   = 48;
1201 >    private static final int  TC_SHIFT   = 32;
1202 >    private static final int  ST_SHIFT   = 31;
1203 >    private static final int  EC_SHIFT   = 16;
1204 >
1205 >    // bounds
1206 >    private static final int  SMASK      = 0xffff;  // short bits
1207 >    private static final int  MAX_CAP    = 0x7fff;  // max #workers - 1
1208 >    private static final int  SQMASK     = 0xfffe;  // even short bits
1209 >    private static final int  SHORT_SIGN = 1 << 15;
1210 >    private static final int  INT_SIGN   = 1 << 31;
1211 >
1212 >    // masks
1213 >    private static final long STOP_BIT   = 0x0001L << ST_SHIFT;
1214 >    private static final long AC_MASK    = ((long)SMASK) << AC_SHIFT;
1215 >    private static final long TC_MASK    = ((long)SMASK) << TC_SHIFT;
1216 >
1217 >    // units for incrementing and decrementing
1218 >    private static final long TC_UNIT    = 1L << TC_SHIFT;
1219 >    private static final long AC_UNIT    = 1L << AC_SHIFT;
1220 >
1221 >    // masks and units for dealing with u = (int)(ctl >>> 32)
1222 >    private static final int  UAC_SHIFT  = AC_SHIFT - 32;
1223 >    private static final int  UTC_SHIFT  = TC_SHIFT - 32;
1224 >    private static final int  UAC_MASK   = SMASK << UAC_SHIFT;
1225 >    private static final int  UTC_MASK   = SMASK << UTC_SHIFT;
1226 >    private static final int  UAC_UNIT   = 1 << UAC_SHIFT;
1227 >    private static final int  UTC_UNIT   = 1 << UTC_SHIFT;
1228 >
1229 >    // masks and units for dealing with e = (int)ctl
1230 >    private static final int E_MASK      = 0x7fffffff; // no STOP_BIT
1231 >    private static final int E_SEQ       = 1 << EC_SHIFT;
1232 >
1233 >    // runState bits
1234 >    private static final int SHUTDOWN    = 1 << 31;
1235 >
1236 >    // access mode for WorkQueue
1237 >    static final int LIFO_QUEUE          =  0;
1238 >    static final int FIFO_QUEUE          =  1;
1239 >    static final int SHARED_QUEUE        = -1;
1240  
1241 <    /**
632 <     * Tries decrementing active count; fails on contention.
633 <     * Called when workers cannot find tasks to run.
634 <     */
635 <    final boolean tryDecrementActiveCount() {
636 <        int c;
637 <        return UNSAFE.compareAndSwapInt(this, runStateOffset,
638 <                                        c = runState, c - 1);
639 <    }
1241 >    // Instance fields
1242  
1243 <    /**
1244 <     * Advances to at least the given level. Returns true if not
1245 <     * already in at least the given level.
1246 <     */
1247 <    private boolean advanceRunLevel(int level) {
1248 <        for (;;) {
1249 <            int s = runState;
1250 <            if ((s & level) != 0)
1251 <                return false;
1252 <            if (UNSAFE.compareAndSwapInt(this, runStateOffset, s, s | level))
1253 <                return true;
1243 >    /*
1244 >     * Field layout order in this class tends to matter more than one
1245 >     * would like. Runtime layout order is only loosely related to
1246 >     * declaration order and may differ across JVMs, but the following
1247 >     * empirically works OK on current JVMs.
1248 >     */
1249 >
1250 >    volatile long ctl;                         // main pool control
1251 >    final int parallelism;                     // parallelism level
1252 >    final int localMode;                       // per-worker scheduling mode
1253 >    final int submitMask;                      // submit queue index bound
1254 >    int nextSeed;                              // for initializing worker seeds
1255 >    volatile int runState;                     // shutdown status and seq
1256 >    WorkQueue[] workQueues;                    // main registry
1257 >    final Mutex lock;                          // for registration
1258 >    final Condition termination;               // for awaitTermination
1259 >    final ForkJoinWorkerThreadFactory factory; // factory for new workers
1260 >    final Thread.UncaughtExceptionHandler ueh; // per-worker UEH
1261 >    final AtomicLong stealCount;               // collect counts when terminated
1262 >    final AtomicInteger nextWorkerNumber;      // to create worker name string
1263 >    final String workerNamePrefix;             // to create worker name string
1264 >
1265 >    //  Creating, registering, and deregistering workers
1266 >
1267 >    /**
1268 >     * Tries to create and start a worker
1269 >     */
1270 >    private void addWorker() {
1271 >        Throwable ex = null;
1272 >        ForkJoinWorkerThread wt = null;
1273 >        try {
1274 >            if ((wt = factory.newThread(this)) != null) {
1275 >                wt.start();
1276 >                return;
1277 >            }
1278 >        } catch (Throwable e) {
1279 >            ex = e;
1280          }
1281 +        deregisterWorker(wt, ex); // adjust counts etc on failure
1282      }
1283  
655    // workers array maintenance
656
1284      /**
1285 <     * Records and returns a workers array index for new worker.
1285 >     * Callback from ForkJoinWorkerThread constructor to assign a
1286 >     * public name. This must be separate from registerWorker because
1287 >     * it is called during the "super" constructor call in
1288 >     * ForkJoinWorkerThread.
1289       */
1290 <    private int recordWorker(ForkJoinWorkerThread w) {
1291 <        // Try using slot totalCount-1. If not available, scan and/or resize
1292 <        int k = (workerCounts >>> TOTAL_COUNT_SHIFT) - 1;
663 <        final ReentrantLock lock = this.workerLock;
664 <        lock.lock();
665 <        try {
666 <            ForkJoinWorkerThread[] ws = workers;
667 <            int n = ws.length;
668 <            if (k < 0 || k >= n || ws[k] != null) {
669 <                for (k = 0; k < n && ws[k] != null; ++k)
670 <                    ;
671 <                if (k == n)
672 <                    ws = Arrays.copyOf(ws, n << 1);
673 <            }
674 <            ws[k] = w;
675 <            workers = ws; // volatile array write ensures slot visibility
676 <        } finally {
677 <            lock.unlock();
678 <        }
679 <        return k;
1290 >    final String nextWorkerName() {
1291 >        return workerNamePrefix.concat
1292 >            (Integer.toString(nextWorkerNumber.addAndGet(1)));
1293      }
1294  
1295      /**
1296 <     * Nulls out record of worker in workers array.
1296 >     * Callback from ForkJoinWorkerThread constructor to establish its
1297 >     * poolIndex and record its WorkQueue. To avoid scanning bias due
1298 >     * to packing entries in front of the workQueues array, we treat
1299 >     * the array as a simple power-of-two hash table using per-thread
1300 >     * seed as hash, expanding as needed.
1301 >     *
1302 >     * @param w the worker's queue
1303       */
1304 <    private void forgetWorker(ForkJoinWorkerThread w) {
1305 <        int idx = w.poolIndex;
687 <        // Locking helps method recordWorker avoid unnecessary expansion
688 <        final ReentrantLock lock = this.workerLock;
1304 >    final void registerWorker(WorkQueue w) {
1305 >        Mutex lock = this.lock;
1306          lock.lock();
1307          try {
1308 <            ForkJoinWorkerThread[] ws = workers;
1309 <            if (idx >= 0 && idx < ws.length && ws[idx] == w) // verify
1310 <                ws[idx] = null;
1308 >            WorkQueue[] ws = workQueues;
1309 >            if (w != null && ws != null) {          // skip on shutdown/failure
1310 >                int rs, n = ws.length, m = n - 1;
1311 >                int s = nextSeed += SEED_INCREMENT; // rarely-colliding sequence
1312 >                w.seed = (s == 0) ? 1 : s;          // ensure non-zero seed
1313 >                int r = (s << 1) | 1;               // use odd-numbered indices
1314 >                if (ws[r &= m] != null) {           // collision
1315 >                    int probes = 0;                 // step by approx half size
1316 >                    int step = (n <= 4) ? 2 : ((n >>> 1) & SQMASK) + 2;
1317 >                    while (ws[r = (r + step) & m] != null) {
1318 >                        if (++probes >= n) {
1319 >                            workQueues = ws = Arrays.copyOf(ws, n <<= 1);
1320 >                            m = n - 1;
1321 >                            probes = 0;
1322 >                        }
1323 >                    }
1324 >                }
1325 >                w.eventCount = w.poolIndex = r;     // establish before recording
1326 >                ws[r] = w;                          // also update seq
1327 >                runState = ((rs = runState) & SHUTDOWN) | ((rs + 2) & ~SHUTDOWN);
1328 >            }
1329          } finally {
1330              lock.unlock();
1331          }
1332      }
1333  
1334      /**
1335 <     * Final callback from terminating worker.  Removes record of
1335 >     * Final callback from terminating worker, as well as upon failure
1336 >     * to construct or start a worker in addWorker.  Removes record of
1337       * worker from array, and adjusts counts. If pool is shutting
1338       * down, tries to complete termination.
1339       *
1340 <     * @param w the worker
1340 >     * @param wt the worker thread or null if addWorker failed
1341 >     * @param ex the exception causing failure, or null if none
1342       */
1343 <    final void workerTerminated(ForkJoinWorkerThread w) {
1344 <        forgetWorker(w);
1345 <        decrementWorkerCounts(w.isTrimmed()? 0 : ONE_RUNNING, ONE_TOTAL);
1346 <        while (w.stealCount != 0) // collect final count
1347 <            tryAccumulateStealCount(w);
1348 <        tryTerminate(false);
1349 <    }
1350 <
1351 <    // Waiting for and signalling events
1352 <
1353 <    /**
1354 <     * Releases workers blocked on a count not equal to current count.
1355 <     * Normally called after precheck that eventWaiters isn't zero to
1356 <     * avoid wasted array checks. Gives up upon a change in count or
720 <     * upon releasing two workers, letting others take over.
721 <     */
722 <    private void releaseEventWaiters() {
723 <        ForkJoinWorkerThread[] ws = workers;
724 <        int n = ws.length;
725 <        long h = eventWaiters;
726 <        int ec = eventCount;
727 <        boolean releasedOne = false;
728 <        ForkJoinWorkerThread w; int id;
729 <        while ((id = ((int)(h & WAITER_ID_MASK)) - 1) >= 0 &&
730 <               (int)(h >>> EVENT_COUNT_SHIFT) != ec &&
731 <               id < n && (w = ws[id]) != null) {
732 <            if (UNSAFE.compareAndSwapLong(this, eventWaitersOffset,
733 <                                          h,  w.nextWaiter)) {
734 <                LockSupport.unpark(w);
735 <                if (releasedOne) // exit on second release
736 <                    break;
737 <                releasedOne = true;
1343 >    final void deregisterWorker(ForkJoinWorkerThread wt, Throwable ex) {
1344 >        Mutex lock = this.lock;
1345 >        WorkQueue w = null;
1346 >        if (wt != null && (w = wt.workQueue) != null) {
1347 >            w.runState = -1;                // ensure runState is set
1348 >            stealCount.getAndAdd(w.totalSteals + w.nsteals);
1349 >            int idx = w.poolIndex;
1350 >            lock.lock();
1351 >            try {                           // remove record from array
1352 >                WorkQueue[] ws = workQueues;
1353 >                if (ws != null && idx >= 0 && idx < ws.length && ws[idx] == w)
1354 >                    ws[idx] = null;
1355 >            } finally {
1356 >                lock.unlock();
1357              }
739            if (eventCount != ec)
740                break;
741            h = eventWaiters;
1358          }
743    }
1359  
1360 <    /**
1361 <     * Tries to advance eventCount and releases waiters. Called only
1362 <     * from workers.
1363 <     */
1364 <    final void signalWork() {
1365 <        int c; // try to increment event count -- CAS failure OK
1366 <        UNSAFE.compareAndSwapInt(this, eventCountOffset, c = eventCount, c+1);
1367 <        if (eventWaiters != 0L)
1368 <            releaseEventWaiters();
1360 >        long c;                             // adjust ctl counts
1361 >        do {} while (!U.compareAndSwapLong
1362 >                     (this, CTL, c = ctl, (((c - AC_UNIT) & AC_MASK) |
1363 >                                           ((c - TC_UNIT) & TC_MASK) |
1364 >                                           (c & ~(AC_MASK|TC_MASK)))));
1365 >
1366 >        if (!tryTerminate(false, false) && w != null) {
1367 >            w.cancelAll();                  // cancel remaining tasks
1368 >            if (w.array != null)            // suppress signal if never ran
1369 >                signalWork();               // wake up or create replacement
1370 >            if (ex == null)                 // help clean refs on way out
1371 >                ForkJoinTask.helpExpungeStaleExceptions();
1372 >        }
1373 >
1374 >        if (ex != null)                     // rethrow
1375 >            U.throwException(ex);
1376      }
1377  
756    /**
757     * Adds the given worker to event queue and blocks until
758     * terminating or event count advances from the given value
759     *
760     * @param w the calling worker thread
761     * @param ec the count
762     */
763    private void eventSync(ForkJoinWorkerThread w, int ec) {
764        long nh = (((long)ec) << EVENT_COUNT_SHIFT) | ((long)(w.poolIndex+1));
765        long h;
766        while ((runState < SHUTDOWN || !tryTerminate(false)) &&
767               (((int)((h = eventWaiters) & WAITER_ID_MASK)) == 0 ||
768                (int)(h >>> EVENT_COUNT_SHIFT) == ec) &&
769               eventCount == ec) {
770            if (UNSAFE.compareAndSwapLong(this, eventWaitersOffset,
771                                          w.nextWaiter = h, nh)) {
772                awaitEvent(w, ec);
773                break;
774            }
775        }
776    }
1378  
1379 <    /**
1380 <     * Blocks the given worker (that has already been entered as an
1381 <     * event waiter) until terminating or event count advances from
1382 <     * the given value. The oldest (first) waiter uses a timed wait to
1383 <     * occasionally one-by-one shrink the number of workers (to a
1384 <     * minimum of one) if the pool has not been used for extended
1385 <     * periods.
1386 <     *
1387 <     * @param w the calling worker thread
1388 <     * @param ec the count
1389 <     */
1390 <    private void awaitEvent(ForkJoinWorkerThread w, int ec) {
1391 <        while (eventCount == ec) {
1392 <            if (tryAccumulateStealCount(w)) { // transfer while idle
1393 <                boolean untimed = (w.nextWaiter != 0L ||
1394 <                                   (workerCounts & RUNNING_COUNT_MASK) <= 1);
1395 <                long startTime = untimed? 0 : System.nanoTime();
1396 <                Thread.interrupted();         // clear/ignore interrupt
1397 <                if (eventCount != ec || w.isTerminating())
1398 <                    break;                    // recheck after clear
1399 <                if (untimed)
1400 <                    LockSupport.park(w);
1401 <                else {
1402 <                    LockSupport.parkNanos(w, SHRINK_RATE_NANOS);
1403 <                    if (eventCount != ec || w.isTerminating())
1404 <                        break;
1405 <                    if (System.nanoTime() - startTime >= SHRINK_RATE_NANOS)
1406 <                        tryShutdownUnusedWorker(ec);
1379 >    // Submissions
1380 >
1381 >    /**
1382 >     * Unless shutting down, adds the given task to a submission queue
1383 >     * at submitter's current queue index (modulo submission
1384 >     * range). If no queue exists at the index, one is created.  If
1385 >     * the queue is busy, another index is randomly chosen. The
1386 >     * submitMask bounds the effective number of queues to the
1387 >     * (nearest power of two for) parallelism level.
1388 >     *
1389 >     * @param task the task. Caller must ensure non-null.
1390 >     */
1391 >    private void doSubmit(ForkJoinTask<?> task) {
1392 >        Submitter s = submitters.get();
1393 >        for (int r = s.seed, m = submitMask;;) {
1394 >            WorkQueue[] ws; WorkQueue q;
1395 >            int k = r & m & SQMASK;          // use only even indices
1396 >            if (runState < 0 || (ws = workQueues) == null || ws.length <= k)
1397 >                throw new RejectedExecutionException(); // shutting down
1398 >            else if ((q = ws[k]) == null) {  // create new queue
1399 >                WorkQueue nq = new WorkQueue(this, null, SHARED_QUEUE);
1400 >                Mutex lock = this.lock;      // construct outside lock
1401 >                lock.lock();
1402 >                try {                        // recheck under lock
1403 >                    int rs = runState;       // to update seq
1404 >                    if (ws == workQueues && ws[k] == null) {
1405 >                        ws[k] = nq;
1406 >                        runState = ((rs & SHUTDOWN) | ((rs + 2) & ~SHUTDOWN));
1407 >                    }
1408 >                } finally {
1409 >                    lock.unlock();
1410                  }
1411              }
1412 +            else if (q.trySharedPush(task)) {
1413 +                signalWork();
1414 +                return;
1415 +            }
1416 +            else if (m > 1) {                // move to a different index
1417 +                r ^= r << 13;                // same xorshift as WorkQueues
1418 +                r ^= r >>> 17;
1419 +                s.seed = r ^= r << 5;
1420 +            }
1421 +            else
1422 +                Thread.yield();              // yield if no alternatives
1423          }
1424      }
1425  
1426 <    // Maintaining parallelism
1426 >    // Maintaining ctl counts
1427  
1428      /**
1429 <     * Pushes worker onto the spare stack.
1429 >     * Increments active count; mainly called upon return from blocking.
1430       */
1431 <    final void pushSpare(ForkJoinWorkerThread w) {
1432 <        int ns = (++w.spareCount << SPARE_COUNT_SHIFT) | (w.poolIndex + 1);
1433 <        do {} while (!UNSAFE.compareAndSwapInt(this, spareWaitersOffset,
819 <                                               w.nextSpare = spareWaiters,ns));
1431 >    final void incrementActiveCount() {
1432 >        long c;
1433 >        do {} while (!U.compareAndSwapLong(this, CTL, c = ctl, c + AC_UNIT));
1434      }
1435  
1436      /**
1437 <     * Tries (once) to resume a spare if the number of running
824 <     * threads is less than target.
1437 >     * Tries to activate or create a worker if too few are active.
1438       */
1439 <    private void tryResumeSpare() {
1440 <        int sw, id;
1441 <        ForkJoinWorkerThread[] ws = workers;
1442 <        int n = ws.length;
1443 <        ForkJoinWorkerThread w;
1444 <        if ((sw = spareWaiters) != 0 &&
1445 <            (id = (sw & SPARE_ID_MASK) - 1) >= 0 &&
1446 <            id < n && (w = ws[id]) != null &&
1447 <            (workerCounts & RUNNING_COUNT_MASK) < parallelism &&
1448 <            spareWaiters == sw &&
1449 <            UNSAFE.compareAndSwapInt(this, spareWaitersOffset,
1450 <                                     sw, w.nextSpare)) {
1451 <            int c; // increment running count before resume
1452 <            do {} while (!UNSAFE.compareAndSwapInt
1453 <                         (this, workerCountsOffset,
1454 <                          c = workerCounts, c + ONE_RUNNING));
1455 <            if (w.tryUnsuspend())
1456 <                LockSupport.unpark(w);
1457 <            else   // back out if w was shutdown
1458 <                decrementWorkerCounts(ONE_RUNNING, 0);
1439 >    final void signalWork() {
1440 >        long c; int u;
1441 >        while ((u = (int)((c = ctl) >>> 32)) < 0) {     // too few active
1442 >            WorkQueue[] ws = workQueues; int e, i; WorkQueue w; Thread p;
1443 >            if ((e = (int)c) > 0) {                     // at least one waiting
1444 >                if (ws != null && (i = e & SMASK) < ws.length &&
1445 >                    (w = ws[i]) != null && w.eventCount == (e | INT_SIGN)) {
1446 >                    long nc = (((long)(w.nextWait & E_MASK)) |
1447 >                               ((long)(u + UAC_UNIT) << 32));
1448 >                    if (U.compareAndSwapLong(this, CTL, c, nc)) {
1449 >                        w.eventCount = (e + E_SEQ) & E_MASK;
1450 >                        if ((p = w.parker) != null)
1451 >                            U.unpark(p);                // activate and release
1452 >                        break;
1453 >                    }
1454 >                }
1455 >                else
1456 >                    break;
1457 >            }
1458 >            else if (e == 0 && (u & SHORT_SIGN) != 0) { // too few total
1459 >                long nc = (long)(((u + UTC_UNIT) & UTC_MASK) |
1460 >                                 ((u + UAC_UNIT) & UAC_MASK)) << 32;
1461 >                if (U.compareAndSwapLong(this, CTL, c, nc)) {
1462 >                    addWorker();
1463 >                    break;
1464 >                }
1465 >            }
1466 >            else
1467 >                break;
1468          }
1469      }
1470  
1471 +    // Scanning for tasks
1472 +
1473      /**
1474 <     * Tries to increase the number of running workers if below target
851 <     * parallelism: If a spare exists tries to resume it via
852 <     * tryResumeSpare.  Otherwise, if not enough total workers or all
853 <     * existing workers are busy, adds a new worker. In all cases also
854 <     * helps wake up releasable workers waiting for work.
1474 >     * Top-level runloop for workers, called by ForkJoinWorkerThread.run.
1475       */
1476 <    private void helpMaintainParallelism() {
1477 <        int pc = parallelism;
1478 <        int wc, rs, tc;
1479 <        while (((wc = workerCounts) & RUNNING_COUNT_MASK) < pc &&
1480 <               (rs = runState) < TERMINATING) {
1481 <            if (spareWaiters != 0)
1482 <                tryResumeSpare();
1483 <            else if ((tc = wc >>> TOTAL_COUNT_SHIFT) >= MAX_WORKERS ||
1484 <                     (tc >= pc && (rs & ACTIVE_COUNT_MASK) != tc))
1485 <                break;   // enough total
1486 <            else if (runState == rs && workerCounts == wc &&
1487 <                     UNSAFE.compareAndSwapInt(this, workerCountsOffset, wc,
1488 <                                              wc + (ONE_RUNNING|ONE_TOTAL))) {
1489 <                ForkJoinWorkerThread w = null;
1490 <                Throwable fail = null;
1491 <                try {
1492 <                    w = factory.newThread(this);
1493 <                } catch (Throwable ex) {
1494 <                    fail = ex;
1495 <                }
1496 <                if (w == null) { // null or exceptional factory return
1497 <                    decrementWorkerCounts(ONE_RUNNING, ONE_TOTAL);
1498 <                    tryTerminate(false); // handle failure during shutdown
1499 <                    // If originating from an external caller,
1500 <                    // propagate exception, else ignore
1501 <                    if (fail != null && runState < TERMINATING &&
1502 <                        !(Thread.currentThread() instanceof
1503 <                          ForkJoinWorkerThread))
1504 <                        UNSAFE.throwException(fail);
1476 >    final void runWorker(WorkQueue w) {
1477 >        w.growArray(false);         // initialize queue array in this thread
1478 >        do { w.runTask(scan(w)); } while (w.runState >= 0);
1479 >    }
1480 >
1481 >    /**
1482 >     * Scans for and, if found, returns one task, else possibly
1483 >     * inactivates the worker. This method operates on single reads of
1484 >     * volatile state and is designed to be re-invoked continuously,
1485 >     * in part because it returns upon detecting inconsistencies,
1486 >     * contention, or state changes that indicate possible success on
1487 >     * re-invocation.
1488 >     *
1489 >     * The scan searches for tasks across a random permutation of
1490 >     * queues (starting at a random index and stepping by a random
1491 >     * relative prime, checking each at least once).  The scan
1492 >     * terminates upon either finding a non-empty queue, or completing
1493 >     * the sweep. If the worker is not inactivated, it takes and
1494 >     * returns a task from this queue.  On failure to find a task, we
1495 >     * take one of the following actions, after which the caller will
1496 >     * retry calling this method unless terminated.
1497 >     *
1498 >     * * If pool is terminating, terminate the worker.
1499 >     *
1500 >     * * If not a complete sweep, try to release a waiting worker.  If
1501 >     * the scan terminated because the worker is inactivated, then the
1502 >     * released worker will often be the calling worker, and it can
1503 >     * succeed obtaining a task on the next call. Or maybe it is
1504 >     * another worker, but with same net effect. Releasing in other
1505 >     * cases as well ensures that we have enough workers running.
1506 >     *
1507 >     * * If not already enqueued, try to inactivate and enqueue the
1508 >     * worker on wait queue. Or, if inactivating has caused the pool
1509 >     * to be quiescent, relay to idleAwaitWork to check for
1510 >     * termination and possibly shrink pool.
1511 >     *
1512 >     * * If already inactive, and the caller has run a task since the
1513 >     * last empty scan, return (to allow rescan) unless others are
1514 >     * also inactivated.  Field WorkQueue.rescans counts down on each
1515 >     * scan to ensure eventual inactivation and blocking.
1516 >     *
1517 >     * * If already enqueued and none of the above apply, park
1518 >     * awaiting signal,
1519 >     *
1520 >     * @param w the worker (via its WorkQueue)
1521 >     * @return a task or null if none found
1522 >     */
1523 >    private final ForkJoinTask<?> scan(WorkQueue w) {
1524 >        WorkQueue[] ws;                       // first update random seed
1525 >        int r = w.seed; r ^= r << 13; r ^= r >>> 17; w.seed = r ^= r << 5;
1526 >        int rs = runState, m;                 // volatile read order matters
1527 >        if ((ws = workQueues) != null && (m = ws.length - 1) > 0) {
1528 >            int ec = w.eventCount;            // ec is negative if inactive
1529 >            int step = (r >>> 16) | 1;        // relative prime
1530 >            for (int j = (m + 1) << 2; ; r += step) {
1531 >                WorkQueue q; ForkJoinTask<?> t; ForkJoinTask<?>[] a; int b;
1532 >                if ((q = ws[r & m]) != null && (b = q.base) - q.top < 0 &&
1533 >                    (a = q.array) != null) {  // probably nonempty
1534 >                    int i = (((a.length - 1) & b) << ASHIFT) + ABASE;
1535 >                    t = (ForkJoinTask<?>)U.getObjectVolatile(a, i);
1536 >                    if (q.base == b && ec >= 0 && t != null &&
1537 >                        U.compareAndSwapObject(a, i, t, null)) {
1538 >                        if (q.top - (q.base = b + 1) > 1)
1539 >                            signalWork();    // help pushes signal
1540 >                        return t;
1541 >                    }
1542 >                    else if (ec < 0 || j <= m) {
1543 >                        rs = 0;               // mark scan as imcomplete
1544 >                        break;                // caller can retry after release
1545 >                    }
1546 >                }
1547 >                if (--j < 0)
1548                      break;
1549 +            }
1550 +
1551 +            long c = ctl; int e = (int)c, a = (int)(c >> AC_SHIFT), nr, ns;
1552 +            if (e < 0)                        // decode ctl on empty scan
1553 +                w.runState = -1;              // pool is terminating
1554 +            else if (rs == 0 || rs != runState) { // incomplete scan
1555 +                WorkQueue v; Thread p;        // try to release a waiter
1556 +                if (e > 0 && a < 0 && w.eventCount == ec &&
1557 +                    (v = ws[e & m]) != null && v.eventCount == (e | INT_SIGN)) {
1558 +                    long nc = ((long)(v.nextWait & E_MASK) |
1559 +                               ((c + AC_UNIT) & (AC_MASK|TC_MASK)));
1560 +                    if (ctl == c && U.compareAndSwapLong(this, CTL, c, nc)) {
1561 +                        v.eventCount = (e + E_SEQ) & E_MASK;
1562 +                        if ((p = v.parker) != null)
1563 +                            U.unpark(p);
1564 +                    }
1565                  }
887                w.start(recordWorker(w), ueh);
888                if ((workerCounts >>> TOTAL_COUNT_SHIFT) >= pc) {
889                    int c; // advance event count
890                    UNSAFE.compareAndSwapInt(this, eventCountOffset,
891                                             c = eventCount, c+1);
892                    break; // add at most one unless total below target
893                }
894            }
895        }
896        if (eventWaiters != 0L)
897            releaseEventWaiters();
898    }
899
900    /**
901     * Callback from the oldest waiter in awaitEvent waking up after a
902     * period of non-use. If all workers are idle, tries (once) to
903     * shutdown an event waiter or a spare, if one exists. Note that
904     * we don't need CAS or locks here because the method is called
905     * only from one thread occasionally waking (and even misfires are
906     * OK). Note that until the shutdown worker fully terminates,
907     * workerCounts will overestimate total count, which is tolerable.
908     *
909     * @param ec the event count waited on by caller (to abort
910     * attempt if count has since changed).
911     */
912    private void tryShutdownUnusedWorker(int ec) {
913        if (runState == 0 && eventCount == ec) { // only trigger if all idle
914            ForkJoinWorkerThread[] ws = workers;
915            int n = ws.length;
916            ForkJoinWorkerThread w = null;
917            boolean shutdown = false;
918            int sw;
919            long h;
920            if ((sw = spareWaiters) != 0) { // prefer killing spares
921                int id = (sw & SPARE_ID_MASK) - 1;
922                if (id >= 0 && id < n && (w = ws[id]) != null &&
923                    UNSAFE.compareAndSwapInt(this, spareWaitersOffset,
924                                             sw, w.nextSpare))
925                    shutdown = true;
926            }
927            else if ((h = eventWaiters) != 0L) {
928                long nh;
929                int id = ((int)(h & WAITER_ID_MASK)) - 1;
930                if (id >= 0 && id < n && (w = ws[id]) != null &&
931                    (nh = w.nextWaiter) != 0L && // keep at least one worker
932                    UNSAFE.compareAndSwapLong(this, eventWaitersOffset, h, nh))
933                    shutdown = true;
934            }
935            if (w != null && shutdown) {
936                w.shutdown();
937                LockSupport.unpark(w);
938            }
939        }
940        releaseEventWaiters(); // in case of interference
941    }
942
943    /**
944     * Callback from workers invoked upon each top-level action (i.e.,
945     * stealing a task or taking a submission and running it).
946     * Performs one or more of the following:
947     *
948     * 1. If the worker is active and either did not run a task
949     *    or there are too many workers, try to set its active status
950     *    to inactive and update activeCount. On contention, we may
951     *    try again in this or a subsequent call.
952     *
953     * 2. If not enough total workers, help create some.
954     *
955     * 3. If there are too many running workers, suspend this worker
956     *    (first forcing inactive if necessary).  If it is not needed,
957     *    it may be shutdown while suspended (via
958     *    tryShutdownUnusedWorker).  Otherwise, upon resume it
959     *    rechecks running thread count and need for event sync.
960     *
961     * 4. If worker did not run a task, await the next task event via
962     *    eventSync if necessary (first forcing inactivation), upon
963     *    which the worker may be shutdown via
964     *    tryShutdownUnusedWorker.  Otherwise, help release any
965     *    existing event waiters that are now releasable,
966     *
967     * @param w the worker
968     * @param ran true if worker ran a task since last call to this method
969     */
970    final void preStep(ForkJoinWorkerThread w, boolean ran) {
971        int wec = w.lastEventCount;
972        boolean active = w.active;
973        boolean inactivate = false;
974        int pc = parallelism;
975        while (w.runState == 0) {
976            int rs = runState;
977            if (rs >= TERMINATING) { // propagate shutdown
978                w.shutdown();
979                break;
1566              }
1567 <            if ((inactivate || (active && (rs & ACTIVE_COUNT_MASK) >= pc)) &&
1568 <                UNSAFE.compareAndSwapInt(this, runStateOffset, rs, rs - 1))
1569 <                inactivate = active = w.active = false;
1570 <            int wc = workerCounts;
1571 <            if ((wc & RUNNING_COUNT_MASK) > pc) {
1572 <                if (!(inactivate |= active) && // must inactivate to suspend
1573 <                    workerCounts == wc &&      // try to suspend as spare
1574 <                    UNSAFE.compareAndSwapInt(this, workerCountsOffset,
1575 <                                             wc, wc - ONE_RUNNING))
1576 <                    w.suspendAsSpare();
1577 <            }
1578 <            else if ((wc >>> TOTAL_COUNT_SHIFT) < pc)
1579 <                helpMaintainParallelism();     // not enough workers
1580 <            else if (!ran) {
1581 <                long h = eventWaiters;
1582 <                int ec = eventCount;
1583 <                if (h != 0L && (int)(h >>> EVENT_COUNT_SHIFT) != ec)
1584 <                    releaseEventWaiters();     // release others before waiting
1585 <                else if (ec != wec) {
1586 <                    w.lastEventCount = ec;     // no need to wait
1587 <                    break;
1567 >            else if (ec >= 0) {               // try to enqueue/inactivate
1568 >                long nc = (long)ec | ((c - AC_UNIT) & (AC_MASK|TC_MASK));
1569 >                w.nextWait = e;
1570 >                w.eventCount = ec | INT_SIGN; // mark as inactive
1571 >                if (ctl != c || !U.compareAndSwapLong(this, CTL, c, nc))
1572 >                    w.eventCount = ec;        // unmark on CAS failure
1573 >                else {
1574 >                    if ((ns = w.nsteals) != 0) {
1575 >                        w.nsteals = 0;        // set rescans if ran task
1576 >                        w.rescans = (a > 0) ? 0 : a + parallelism;
1577 >                        w.totalSteals += ns;
1578 >                    }
1579 >                    if (a == 1 - parallelism) // quiescent
1580 >                        idleAwaitWork(w, nc, c);
1581 >                }
1582 >            }
1583 >            else if (w.eventCount < 0) {      // already queued
1584 >                if ((nr = w.rescans) > 0) {   // continue rescanning
1585 >                    int ac = a + parallelism;
1586 >                    if (((w.rescans = (ac < nr) ? ac : nr - 1) & 3) == 0)
1587 >                        Thread.yield();       // yield before block
1588 >                }
1589 >                else {
1590 >                    Thread.interrupted();     // clear status
1591 >                    Thread wt = Thread.currentThread();
1592 >                    U.putObject(wt, PARKBLOCKER, this);
1593 >                    w.parker = wt;            // emulate LockSupport.park
1594 >                    if (w.eventCount < 0)     // recheck
1595 >                        U.park(false, 0L);
1596 >                    w.parker = null;
1597 >                    U.putObject(wt, PARKBLOCKER, null);
1598                  }
1003                else if (!(inactivate |= active))
1004                    eventSync(w, wec);         // must inactivate before sync
1599              }
1006            else
1007                break;
1600          }
1601 +        return null;
1602      }
1603  
1604      /**
1605 <     * Helps and/or blocks awaiting join of the given task.
1606 <     * See above for explanation.
1607 <     *
1608 <     * @param joinMe the task to join
1609 <     * @param worker the current worker thread
1610 <     */
1611 <    final void awaitJoin(ForkJoinTask<?> joinMe, ForkJoinWorkerThread worker) {
1612 <        int retries = 2 + (parallelism >> 2); // #helpJoins before blocking
1613 <        while (joinMe.status >= 0) {
1614 <            int wc;
1615 <            worker.helpJoinTask(joinMe);
1616 <            if (joinMe.status < 0)
1617 <                break;
1618 <            else if (retries > 0)
1619 <                --retries;
1620 <            else if (((wc = workerCounts) & RUNNING_COUNT_MASK) != 0 &&
1621 <                     UNSAFE.compareAndSwapInt(this, workerCountsOffset,
1622 <                                              wc, wc - ONE_RUNNING)) {
1623 <                int stat, c; long h;
1624 <                while ((stat = joinMe.status) >= 0 &&
1625 <                       (h = eventWaiters) != 0L && // help release others
1626 <                       (int)(h >>> EVENT_COUNT_SHIFT) != eventCount)
1627 <                    releaseEventWaiters();
1628 <                if (stat >= 0 &&
1629 <                    ((workerCounts & RUNNING_COUNT_MASK) == 0 ||
1630 <                     (stat =
1631 <                      joinMe.internalAwaitDone(JOIN_TIMEOUT_MILLIS)) >= 0))
1632 <                    helpMaintainParallelism(); // timeout or no running workers
1633 <                do {} while (!UNSAFE.compareAndSwapInt
1634 <                             (this, workerCountsOffset,
1635 <                              c = workerCounts, c + ONE_RUNNING));
1636 <                if (stat < 0)
1637 <                    break;   // else restart
1605 >     * If inactivating worker w has caused the pool to become
1606 >     * quiescent, checks for pool termination, and, so long as this is
1607 >     * not the only worker, waits for event for up to SHRINK_RATE
1608 >     * nanosecs.  On timeout, if ctl has not changed, terminates the
1609 >     * worker, which will in turn wake up another worker to possibly
1610 >     * repeat this process.
1611 >     *
1612 >     * @param w the calling worker
1613 >     * @param currentCtl the ctl value triggering possible quiescence
1614 >     * @param prevCtl the ctl value to restore if thread is terminated
1615 >     */
1616 >    private void idleAwaitWork(WorkQueue w, long currentCtl, long prevCtl) {
1617 >        if (w.eventCount < 0 && !tryTerminate(false, false) &&
1618 >            (int)prevCtl != 0 && !hasQueuedSubmissions() && ctl == currentCtl) {
1619 >            Thread wt = Thread.currentThread();
1620 >            Thread.yield();            // yield before block
1621 >            while (ctl == currentCtl) {
1622 >                long startTime = System.nanoTime();
1623 >                Thread.interrupted();  // timed variant of version in scan()
1624 >                U.putObject(wt, PARKBLOCKER, this);
1625 >                w.parker = wt;
1626 >                if (ctl == currentCtl)
1627 >                    U.park(false, SHRINK_RATE);
1628 >                w.parker = null;
1629 >                U.putObject(wt, PARKBLOCKER, null);
1630 >                if (ctl != currentCtl)
1631 >                    break;
1632 >                if (System.nanoTime() - startTime >= SHRINK_TIMEOUT &&
1633 >                    U.compareAndSwapLong(this, CTL, currentCtl, prevCtl)) {
1634 >                    w.eventCount = (w.eventCount + E_SEQ) | E_MASK;
1635 >                    w.runState = -1;   // shrink
1636 >                    break;
1637 >                }
1638              }
1639          }
1640      }
1641  
1642      /**
1643 <     * Same idea as awaitJoin, but no helping, retries, or timeouts.
1644 <     */
1645 <    final void awaitBlocker(ManagedBlocker blocker)
1646 <        throws InterruptedException {
1647 <        while (!blocker.isReleasable()) {
1648 <            int wc = workerCounts;
1649 <            if ((wc & RUNNING_COUNT_MASK) != 0 &&
1650 <                UNSAFE.compareAndSwapInt(this, workerCountsOffset,
1651 <                                         wc, wc - ONE_RUNNING)) {
1652 <                try {
1653 <                    while (!blocker.isReleasable()) {
1654 <                        long h = eventWaiters;
1655 <                        if (h != 0L &&
1656 <                            (int)(h >>> EVENT_COUNT_SHIFT) != eventCount)
1657 <                            releaseEventWaiters();
1658 <                        else if ((workerCounts & RUNNING_COUNT_MASK) == 0 &&
1659 <                                 runState < TERMINATING)
1660 <                            helpMaintainParallelism();
1661 <                        else if (blocker.block())
1662 <                            break;
1643 >     * Tries to locate and execute tasks for a stealer of the given
1644 >     * task, or in turn one of its stealers, Traces currentSteal ->
1645 >     * currentJoin links looking for a thread working on a descendant
1646 >     * of the given task and with a non-empty queue to steal back and
1647 >     * execute tasks from. The first call to this method upon a
1648 >     * waiting join will often entail scanning/search, (which is OK
1649 >     * because the joiner has nothing better to do), but this method
1650 >     * leaves hints in workers to speed up subsequent calls. The
1651 >     * implementation is very branchy to cope with potential
1652 >     * inconsistencies or loops encountering chains that are stale,
1653 >     * unknown, or so long that they are likely cyclic.
1654 >     *
1655 >     * @param joiner the joining worker
1656 >     * @param task the task to join
1657 >     * @return 0 if no progress can be made, negative if task
1658 >     * known complete, else positive
1659 >     */
1660 >    private int tryHelpStealer(WorkQueue joiner, ForkJoinTask<?> task) {
1661 >        int stat = 0, steps = 0;                    // bound to avoid cycles
1662 >        if (joiner != null && task != null) {       // hoist null checks
1663 >            restart: for (;;) {
1664 >                ForkJoinTask<?> subtask = task;     // current target
1665 >                for (WorkQueue j = joiner, v;;) {   // v is stealer of subtask
1666 >                    WorkQueue[] ws; int m, s, h;
1667 >                    if ((s = task.status) < 0) {
1668 >                        stat = s;
1669 >                        break restart;
1670 >                    }
1671 >                    if ((ws = workQueues) == null || (m = ws.length - 1) <= 0)
1672 >                        break restart;              // shutting down
1673 >                    if ((v = ws[h = (j.stealHint | 1) & m]) == null ||
1674 >                        v.currentSteal != subtask) {
1675 >                        for (int origin = h;;) {    // find stealer
1676 >                            if (((h = (h + 2) & m) & 15) == 1 &&
1677 >                                (subtask.status < 0 || j.currentJoin != subtask))
1678 >                                continue restart;   // occasional staleness check
1679 >                            if ((v = ws[h]) != null &&
1680 >                                v.currentSteal == subtask) {
1681 >                                j.stealHint = h;    // save hint
1682 >                                break;
1683 >                            }
1684 >                            if (h == origin)
1685 >                                break restart;      // cannot find stealer
1686 >                        }
1687 >                    }
1688 >                    for (;;) { // help stealer or descend to its stealer
1689 >                        ForkJoinTask[] a;  int b;
1690 >                        if (subtask.status < 0)     // surround probes with
1691 >                            continue restart;       //   consistency checks
1692 >                        if ((b = v.base) - v.top < 0 && (a = v.array) != null) {
1693 >                            int i = (((a.length - 1) & b) << ASHIFT) + ABASE;
1694 >                            ForkJoinTask<?> t =
1695 >                                (ForkJoinTask<?>)U.getObjectVolatile(a, i);
1696 >                            if (subtask.status < 0 || j.currentJoin != subtask ||
1697 >                                v.currentSteal != subtask)
1698 >                                continue restart;   // stale
1699 >                            stat = 1;               // apparent progress
1700 >                            if (t != null && v.base == b &&
1701 >                                U.compareAndSwapObject(a, i, t, null)) {
1702 >                                v.base = b + 1;     // help stealer
1703 >                                joiner.runSubtask(t);
1704 >                            }
1705 >                            else if (v.base == b && ++steps == MAX_HELP)
1706 >                                break restart;      // v apparently stalled
1707 >                        }
1708 >                        else {                      // empty -- try to descend
1709 >                            ForkJoinTask<?> next = v.currentJoin;
1710 >                            if (subtask.status < 0 || j.currentJoin != subtask ||
1711 >                                v.currentSteal != subtask)
1712 >                                continue restart;   // stale
1713 >                            else if (next == null || ++steps == MAX_HELP)
1714 >                                break restart;      // dead-end or maybe cyclic
1715 >                            else {
1716 >                                subtask = next;
1717 >                                j = v;
1718 >                                break;
1719 >                            }
1720 >                        }
1721                      }
1071                } finally {
1072                    int c;
1073                    do {} while (!UNSAFE.compareAndSwapInt
1074                                 (this, workerCountsOffset,
1075                                  c = workerCounts, c + ONE_RUNNING));
1722                  }
1077                break;
1723              }
1724          }
1725 +        return stat;
1726      }
1727  
1728      /**
1729 <     * Possibly initiates and/or completes termination.
1729 >     * If task is at base of some steal queue, steals and executes it.
1730       *
1731 <     * @param now if true, unconditionally terminate, else only
1732 <     * if shutdown and empty queue and no active workers
1087 <     * @return true if now terminating or terminated
1731 >     * @param joiner the joining worker
1732 >     * @param task the task
1733       */
1734 <    private boolean tryTerminate(boolean now) {
1735 <        if (now)
1736 <            advanceRunLevel(SHUTDOWN); // ensure at least SHUTDOWN
1737 <        else if (runState < SHUTDOWN ||
1738 <                 !submissionQueue.isEmpty() ||
1739 <                 (runState & ACTIVE_COUNT_MASK) != 0)
1740 <            return false;
1741 <
1742 <        if (advanceRunLevel(TERMINATING))
1743 <            startTerminating();
1744 <
1100 <        // Finish now if all threads terminated; else in some subsequent call
1101 <        if ((workerCounts >>> TOTAL_COUNT_SHIFT) == 0) {
1102 <            advanceRunLevel(TERMINATED);
1103 <            termination.arrive();
1104 <        }
1105 <        return true;
1734 >    private void tryPollForAndExec(WorkQueue joiner, ForkJoinTask<?> task) {
1735 >        WorkQueue[] ws;
1736 >        if ((ws = workQueues) != null) {
1737 >            for (int j = 1; j < ws.length && task.status >= 0; j += 2) {
1738 >                WorkQueue q = ws[j];
1739 >                if (q != null && q.pollFor(task)) {
1740 >                    joiner.runSubtask(task);
1741 >                    break;
1742 >                }
1743 >            }
1744 >        }
1745      }
1746  
1747 +    /**
1748 +     * Tries to decrement active count (sometimes implicitly) and
1749 +     * possibly release or create a compensating worker in preparation
1750 +     * for blocking. Fails on contention or termination. Otherwise,
1751 +     * adds a new thread if no idle workers are available and either
1752 +     * pool would become completely starved or: (at least half
1753 +     * starved, and fewer than 50% spares exist, and there is at least
1754 +     * one task apparently available). Even though the availability
1755 +     * check requires a full scan, it is worthwhile in reducing false
1756 +     * alarms.
1757 +     *
1758 +     * @param task if non-null, a task being waited for
1759 +     * @param blocker if non-null, a blocker being waited for
1760 +     * @return true if the caller can block, else should recheck and retry
1761 +     */
1762 +    final boolean tryCompensate(ForkJoinTask<?> task, ManagedBlocker blocker) {
1763 +        int pc = parallelism, e;
1764 +        long c = ctl;
1765 +        WorkQueue[] ws = workQueues;
1766 +        if ((e = (int)c) >= 0 && ws != null) {
1767 +            int u, a, ac, hc;
1768 +            int tc = (short)((u = (int)(c >>> 32)) >>> UTC_SHIFT) + pc;
1769 +            boolean replace = false;
1770 +            if ((a = u >> UAC_SHIFT) <= 0) {
1771 +                if ((ac = a + pc) <= 1)
1772 +                    replace = true;
1773 +                else if ((e > 0 || (task != null &&
1774 +                                    ac <= (hc = pc >>> 1) && tc < pc + hc))) {
1775 +                    WorkQueue w;
1776 +                    for (int j = 0; j < ws.length; ++j) {
1777 +                        if ((w = ws[j]) != null && !w.isEmpty()) {
1778 +                            replace = true;
1779 +                            break;   // in compensation range and tasks available
1780 +                        }
1781 +                    }
1782 +                }
1783 +            }
1784 +            if ((task == null || task.status >= 0) && // recheck need to block
1785 +                (blocker == null || !blocker.isReleasable()) && ctl == c) {
1786 +                if (!replace) {          // no compensation
1787 +                    long nc = ((c - AC_UNIT) & AC_MASK) | (c & ~AC_MASK);
1788 +                    if (U.compareAndSwapLong(this, CTL, c, nc))
1789 +                        return true;
1790 +                }
1791 +                else if (e != 0) {       // release an idle worker
1792 +                    WorkQueue w; Thread p; int i;
1793 +                    if ((i = e & SMASK) < ws.length && (w = ws[i]) != null) {
1794 +                        long nc = ((long)(w.nextWait & E_MASK) |
1795 +                                   (c & (AC_MASK|TC_MASK)));
1796 +                        if (w.eventCount == (e | INT_SIGN) &&
1797 +                            U.compareAndSwapLong(this, CTL, c, nc)) {
1798 +                            w.eventCount = (e + E_SEQ) & E_MASK;
1799 +                            if ((p = w.parker) != null)
1800 +                                U.unpark(p);
1801 +                            return true;
1802 +                        }
1803 +                    }
1804 +                }
1805 +                else if (tc < MAX_CAP) { // create replacement
1806 +                    long nc = ((c + TC_UNIT) & TC_MASK) | (c & ~TC_MASK);
1807 +                    if (U.compareAndSwapLong(this, CTL, c, nc)) {
1808 +                        addWorker();
1809 +                        return true;
1810 +                    }
1811 +                }
1812 +            }
1813 +        }
1814 +        return false;
1815 +    }
1816  
1817      /**
1818 <     * Actions on transition to TERMINATING
1819 <     *
1820 <     * Runs up to four passes through workers: (0) shutting down each
1821 <     * (without waking up if parked) to quickly spread notifications
1822 <     * without unnecessary bouncing around event queues etc (1) wake
1823 <     * up and help cancel tasks (2) interrupt (3) mop up races with
1824 <     * interrupted workers
1825 <     */
1826 <    private void startTerminating() {
1827 <        cancelSubmissions();
1828 <        for (int passes = 0; passes < 4 && workerCounts != 0; ++passes) {
1829 <            int c; // advance event count
1830 <            UNSAFE.compareAndSwapInt(this, eventCountOffset,
1831 <                                     c = eventCount, c+1);
1832 <            eventWaiters = 0L; // clobber lists
1833 <            spareWaiters = 0;
1834 <            for (ForkJoinWorkerThread w : workers) {
1835 <                if (w != null) {
1836 <                    w.shutdown();
1837 <                    if (passes > 0 && !w.isTerminated()) {
1838 <                        w.cancelTasks();
1839 <                        LockSupport.unpark(w);
1840 <                        if (passes > 1 && !w.isInterrupted()) {
1841 <                            try {
1842 <                                w.interrupt();
1843 <                            } catch (SecurityException ignore) {
1818 >     * Helps and/or blocks until the given task is done.
1819 >     *
1820 >     * @param joiner the joining worker
1821 >     * @param task the task
1822 >     * @return task status on exit
1823 >     */
1824 >    final int awaitJoin(WorkQueue joiner, ForkJoinTask<?> task) {
1825 >        int s;
1826 >        if ((s = task.status) >= 0) {
1827 >            ForkJoinTask<?> prevJoin = joiner.currentJoin;
1828 >            joiner.currentJoin = task;
1829 >            long startTime = 0L;
1830 >            for (int k = 0;;) {
1831 >                if ((s = (joiner.isEmpty() ?           // try to help
1832 >                          tryHelpStealer(joiner, task) :
1833 >                          joiner.tryRemoveAndExec(task))) == 0 &&
1834 >                    (s = task.status) >= 0) {
1835 >                    if (k == 0) {
1836 >                        startTime = System.nanoTime();
1837 >                        tryPollForAndExec(joiner, task); // check uncommon case
1838 >                    }
1839 >                    else if ((k & (MAX_HELP - 1)) == 0 &&
1840 >                             System.nanoTime() - startTime >=
1841 >                             COMPENSATION_DELAY &&
1842 >                             tryCompensate(task, null)) {
1843 >                        if (task.trySetSignal()) {
1844 >                            synchronized (task) {
1845 >                                if (task.status >= 0) {
1846 >                                    try {                // see ForkJoinTask
1847 >                                        task.wait();     //  for explanation
1848 >                                    } catch (InterruptedException ie) {
1849 >                                    }
1850 >                                }
1851 >                                else
1852 >                                    task.notifyAll();
1853                              }
1854                          }
1855 +                        long c;                          // re-activate
1856 +                        do {} while (!U.compareAndSwapLong
1857 +                                     (this, CTL, c = ctl, c + AC_UNIT));
1858                      }
1859                  }
1860 +                if (s < 0 || (s = task.status) < 0) {
1861 +                    joiner.currentJoin = prevJoin;
1862 +                    break;
1863 +                }
1864 +                else if ((k++ & (MAX_HELP - 1)) == MAX_HELP >>> 1)
1865 +                    Thread.yield();                     // for politeness
1866              }
1867          }
1868 +        return s;
1869      }
1870  
1871      /**
1872 <     * Clears out and cancels submissions, ignoring exceptions.
1872 >     * Stripped-down variant of awaitJoin used by timed joins. Tries
1873 >     * to help join only while there is continuous progress. (Caller
1874 >     * will then enter a timed wait.)
1875 >     *
1876 >     * @param joiner the joining worker
1877 >     * @param task the task
1878 >     * @return task status on exit
1879       */
1880 <    private void cancelSubmissions() {
1881 <        ForkJoinTask<?> task;
1882 <        while ((task = submissionQueue.poll()) != null) {
1883 <            try {
1884 <                task.cancel(false);
1885 <            } catch (Throwable ignore) {
1880 >    final int helpJoinOnce(WorkQueue joiner, ForkJoinTask<?> task) {
1881 >        int s;
1882 >        while ((s = task.status) >= 0 &&
1883 >               (joiner.isEmpty() ?
1884 >                tryHelpStealer(joiner, task) :
1885 >                joiner.tryRemoveAndExec(task)) != 0)
1886 >            ;
1887 >        return s;
1888 >    }
1889 >
1890 >    /**
1891 >     * Returns a (probably) non-empty steal queue, if one is found
1892 >     * during a random, then cyclic scan, else null.  This method must
1893 >     * be retried by caller if, by the time it tries to use the queue,
1894 >     * it is empty.
1895 >     */
1896 >    private WorkQueue findNonEmptyStealQueue(WorkQueue w) {
1897 >        // Similar to loop in scan(), but ignoring submissions
1898 >        int r = w.seed; r ^= r << 13; r ^= r >>> 17; w.seed = r ^= r << 5;
1899 >        int step = (r >>> 16) | 1;
1900 >        for (WorkQueue[] ws;;) {
1901 >            int rs = runState, m;
1902 >            if ((ws = workQueues) == null || (m = ws.length - 1) < 1)
1903 >                return null;
1904 >            for (int j = (m + 1) << 2; ; r += step) {
1905 >                WorkQueue q = ws[((r << 1) | 1) & m];
1906 >                if (q != null && !q.isEmpty())
1907 >                    return q;
1908 >                else if (--j < 0) {
1909 >                    if (runState == rs)
1910 >                        return null;
1911 >                    break;
1912 >                }
1913              }
1914          }
1915      }
1916  
1157    // misc support for ForkJoinWorkerThread
1917  
1918      /**
1919 <     * Returns pool number.
1920 <     */
1921 <    final int getPoolNumber() {
1922 <        return poolNumber;
1919 >     * Runs tasks until {@code isQuiescent()}. We piggyback on
1920 >     * active count ctl maintenance, but rather than blocking
1921 >     * when tasks cannot be found, we rescan until all others cannot
1922 >     * find tasks either.
1923 >     */
1924 >    final void helpQuiescePool(WorkQueue w) {
1925 >        for (boolean active = true;;) {
1926 >            ForkJoinTask<?> localTask; // exhaust local queue
1927 >            while ((localTask = w.nextLocalTask()) != null)
1928 >                localTask.doExec();
1929 >            WorkQueue q = findNonEmptyStealQueue(w);
1930 >            if (q != null) {
1931 >                ForkJoinTask<?> t; int b;
1932 >                if (!active) {      // re-establish active count
1933 >                    long c;
1934 >                    active = true;
1935 >                    do {} while (!U.compareAndSwapLong
1936 >                                 (this, CTL, c = ctl, c + AC_UNIT));
1937 >                }
1938 >                if ((b = q.base) - q.top < 0 && (t = q.pollAt(b)) != null)
1939 >                    w.runSubtask(t);
1940 >            }
1941 >            else {
1942 >                long c;
1943 >                if (active) {       // decrement active count without queuing
1944 >                    active = false;
1945 >                    do {} while (!U.compareAndSwapLong
1946 >                                 (this, CTL, c = ctl, c -= AC_UNIT));
1947 >                }
1948 >                else
1949 >                    c = ctl;        // re-increment on exit
1950 >                if ((int)(c >> AC_SHIFT) + parallelism == 0) {
1951 >                    do {} while (!U.compareAndSwapLong
1952 >                                 (this, CTL, c = ctl, c + AC_UNIT));
1953 >                    break;
1954 >                }
1955 >            }
1956 >        }
1957      }
1958  
1959      /**
1960 <     * Tries to accumulate steal count from a worker, clearing
1168 <     * the worker's value if successful.
1960 >     * Gets and removes a local or stolen task for the given worker.
1961       *
1962 <     * @return true if worker steal count now zero
1962 >     * @return a task, if available
1963       */
1964 <    final boolean tryAccumulateStealCount(ForkJoinWorkerThread w) {
1965 <        int sc = w.stealCount;
1966 <        long c = stealCount;
1967 <        // CAS even if zero, for fence effects
1968 <        if (UNSAFE.compareAndSwapLong(this, stealCountOffset, c, c + sc)) {
1969 <            if (sc != 0)
1970 <                w.stealCount = 0;
1971 <            return true;
1964 >    final ForkJoinTask<?> nextTaskFor(WorkQueue w) {
1965 >        for (ForkJoinTask<?> t;;) {
1966 >            WorkQueue q; int b;
1967 >            if ((t = w.nextLocalTask()) != null)
1968 >                return t;
1969 >            if ((q = findNonEmptyStealQueue(w)) == null)
1970 >                return null;
1971 >            if ((b = q.base) - q.top < 0 && (t = q.pollAt(b)) != null)
1972 >                return t;
1973          }
1181        return sc == 0;
1974      }
1975  
1976      /**
1977       * Returns the approximate (non-atomic) number of idle threads per
1978 <     * active thread.
1978 >     * active thread to offset steal queue size for method
1979 >     * ForkJoinTask.getSurplusQueuedTaskCount().
1980       */
1981      final int idlePerActive() {
1982 <        int pc = parallelism; // use parallelism, not rc
1983 <        int ac = runState;    // no mask -- artificially boosts during shutdown
1984 <        // Use exact results for small values, saturate past 4
1985 <        return ((pc <= ac) ? 0 :
1986 <                (pc >>> 1 <= ac) ? 1 :
1987 <                (pc >>> 2 <= ac) ? 3 :
1988 <                pc >>> 3);
1982 >        // Approximate at powers of two for small values, saturate past 4
1983 >        int p = parallelism;
1984 >        int a = p + (int)(ctl >> AC_SHIFT);
1985 >        return (a > (p >>>= 1) ? 0 :
1986 >                a > (p >>>= 1) ? 1 :
1987 >                a > (p >>>= 1) ? 2 :
1988 >                a > (p >>>= 1) ? 4 :
1989 >                8);
1990 >    }
1991 >
1992 >    //  Termination
1993 >
1994 >    /**
1995 >     * Possibly initiates and/or completes termination.  The caller
1996 >     * triggering termination runs three passes through workQueues:
1997 >     * (0) Setting termination status, followed by wakeups of queued
1998 >     * workers; (1) cancelling all tasks; (2) interrupting lagging
1999 >     * threads (likely in external tasks, but possibly also blocked in
2000 >     * joins).  Each pass repeats previous steps because of potential
2001 >     * lagging thread creation.
2002 >     *
2003 >     * @param now if true, unconditionally terminate, else only
2004 >     * if no work and no active workers
2005 >     * @param enable if true, enable shutdown when next possible
2006 >     * @return true if now terminating or terminated
2007 >     */
2008 >    private boolean tryTerminate(boolean now, boolean enable) {
2009 >        Mutex lock = this.lock;
2010 >        for (long c;;) {
2011 >            if (((c = ctl) & STOP_BIT) != 0) {      // already terminating
2012 >                if ((short)(c >>> TC_SHIFT) == -parallelism) {
2013 >                    lock.lock();                    // don't need try/finally
2014 >                    termination.signalAll();        // signal when 0 workers
2015 >                    lock.unlock();
2016 >                }
2017 >                return true;
2018 >            }
2019 >            if (runState >= 0) {                    // not yet enabled
2020 >                if (!enable)
2021 >                    return false;
2022 >                lock.lock();
2023 >                runState |= SHUTDOWN;
2024 >                lock.unlock();
2025 >            }
2026 >            if (!now) {                             // check if idle & no tasks
2027 >                if ((int)(c >> AC_SHIFT) != -parallelism ||
2028 >                    hasQueuedSubmissions())
2029 >                    return false;
2030 >                // Check for unqueued inactive workers. One pass suffices.
2031 >                WorkQueue[] ws = workQueues; WorkQueue w;
2032 >                if (ws != null) {
2033 >                    for (int i = 1; i < ws.length; i += 2) {
2034 >                        if ((w = ws[i]) != null && w.eventCount >= 0)
2035 >                            return false;
2036 >                    }
2037 >                }
2038 >            }
2039 >            if (U.compareAndSwapLong(this, CTL, c, c | STOP_BIT)) {
2040 >                for (int pass = 0; pass < 3; ++pass) {
2041 >                    WorkQueue[] ws = workQueues;
2042 >                    if (ws != null) {
2043 >                        WorkQueue w;
2044 >                        int n = ws.length;
2045 >                        for (int i = 0; i < n; ++i) {
2046 >                            if ((w = ws[i]) != null) {
2047 >                                w.runState = -1;
2048 >                                if (pass > 0) {
2049 >                                    w.cancelAll();
2050 >                                    if (pass > 1)
2051 >                                        w.interruptOwner();
2052 >                                }
2053 >                            }
2054 >                        }
2055 >                        // Wake up workers parked on event queue
2056 >                        int i, e; long cc; Thread p;
2057 >                        while ((e = (int)(cc = ctl) & E_MASK) != 0 &&
2058 >                               (i = e & SMASK) < n &&
2059 >                               (w = ws[i]) != null) {
2060 >                            long nc = ((long)(w.nextWait & E_MASK) |
2061 >                                       ((cc + AC_UNIT) & AC_MASK) |
2062 >                                       (cc & (TC_MASK|STOP_BIT)));
2063 >                            if (w.eventCount == (e | INT_SIGN) &&
2064 >                                U.compareAndSwapLong(this, CTL, cc, nc)) {
2065 >                                w.eventCount = (e + E_SEQ) & E_MASK;
2066 >                                w.runState = -1;
2067 >                                if ((p = w.parker) != null)
2068 >                                    U.unpark(p);
2069 >                            }
2070 >                        }
2071 >                    }
2072 >                }
2073 >            }
2074 >        }
2075      }
2076  
2077 <    // Public and protected methods
2077 >    // Exported methods
2078  
2079      // Constructors
2080  
# Line 1264 | Line 2143 | public class ForkJoinPool extends Abstra
2143          checkPermission();
2144          if (factory == null)
2145              throw new NullPointerException();
2146 <        if (parallelism <= 0 || parallelism > MAX_WORKERS)
2146 >        if (parallelism <= 0 || parallelism > MAX_CAP)
2147              throw new IllegalArgumentException();
2148          this.parallelism = parallelism;
2149          this.factory = factory;
2150          this.ueh = handler;
2151 <        this.locallyFifo = asyncMode;
2152 <        int arraySize = initialArraySizeFor(parallelism);
2153 <        this.workers = new ForkJoinWorkerThread[arraySize];
2154 <        this.submissionQueue = new LinkedTransferQueue<ForkJoinTask<?>>();
2155 <        this.workerLock = new ReentrantLock();
2156 <        this.termination = new Phaser(1);
2157 <        this.poolNumber = poolNumberGenerator.incrementAndGet();
2158 <    }
2159 <
2160 <    /**
2161 <     * Returns initial power of two size for workers array.
2162 <     * @param pc the initial parallelism level
2163 <     */
2164 <    private static int initialArraySizeFor(int pc) {
2165 <        // If possible, initially allocate enough space for one spare
2166 <        int size = pc < MAX_WORKERS ? pc + 1 : MAX_WORKERS;
2167 <        // See Hackers Delight, sec 3.2. We know MAX_WORKERS < (1 >>> 16)
2168 <        size |= size >>> 1;
2169 <        size |= size >>> 2;
2170 <        size |= size >>> 4;
1292 <        size |= size >>> 8;
1293 <        return size + 1;
2151 >        this.localMode = asyncMode ? FIFO_QUEUE : LIFO_QUEUE;
2152 >        long np = (long)(-parallelism); // offset ctl counts
2153 >        this.ctl = ((np << AC_SHIFT) & AC_MASK) | ((np << TC_SHIFT) & TC_MASK);
2154 >        // Use nearest power 2 for workQueues size. See Hackers Delight sec 3.2.
2155 >        int n = parallelism - 1;
2156 >        n |= n >>> 1; n |= n >>> 2; n |= n >>> 4; n |= n >>> 8; n |= n >>> 16;
2157 >        int size = (n + 1) << 1;        // #slots = 2*#workers
2158 >        this.submitMask = size - 1;     // room for max # of submit queues
2159 >        this.workQueues = new WorkQueue[size];
2160 >        this.termination = (this.lock = new Mutex()).newCondition();
2161 >        this.stealCount = new AtomicLong();
2162 >        this.nextWorkerNumber = new AtomicInteger();
2163 >        int pn = poolNumberGenerator.incrementAndGet();
2164 >        StringBuilder sb = new StringBuilder("ForkJoinPool-");
2165 >        sb.append(Integer.toString(pn));
2166 >        sb.append("-worker-");
2167 >        this.workerNamePrefix = sb.toString();
2168 >        lock.lock();
2169 >        this.runState = 1;              // set init flag
2170 >        lock.unlock();
2171      }
2172  
2173      // Execution methods
2174  
2175      /**
1299     * Common code for execute, invoke and submit
1300     */
1301    private <T> void doSubmit(ForkJoinTask<T> task) {
1302        if (task == null)
1303            throw new NullPointerException();
1304        if (runState >= SHUTDOWN)
1305            throw new RejectedExecutionException();
1306        submissionQueue.offer(task);
1307        int c; // try to increment event count -- CAS failure OK
1308        UNSAFE.compareAndSwapInt(this, eventCountOffset, c = eventCount, c+1);
1309        helpMaintainParallelism(); // create, start, or resume some workers
1310    }
1311
1312    /**
2176       * Performs the given task, returning its result upon completion.
2177 +     * If the computation encounters an unchecked Exception or Error,
2178 +     * it is rethrown as the outcome of this invocation.  Rethrown
2179 +     * exceptions behave in the same way as regular exceptions, but,
2180 +     * when possible, contain stack traces (as displayed for example
2181 +     * using {@code ex.printStackTrace()}) of both the current thread
2182 +     * as well as the thread actually encountering the exception;
2183 +     * minimally only the latter.
2184       *
2185       * @param task the task
2186       * @return the task's result
# Line 1319 | Line 2189 | public class ForkJoinPool extends Abstra
2189       *         scheduled for execution
2190       */
2191      public <T> T invoke(ForkJoinTask<T> task) {
2192 +        if (task == null)
2193 +            throw new NullPointerException();
2194          doSubmit(task);
2195          return task.join();
2196      }
# Line 1332 | Line 2204 | public class ForkJoinPool extends Abstra
2204       *         scheduled for execution
2205       */
2206      public void execute(ForkJoinTask<?> task) {
2207 +        if (task == null)
2208 +            throw new NullPointerException();
2209          doSubmit(task);
2210      }
2211  
# Line 1343 | Line 2217 | public class ForkJoinPool extends Abstra
2217       *         scheduled for execution
2218       */
2219      public void execute(Runnable task) {
2220 +        if (task == null)
2221 +            throw new NullPointerException();
2222          ForkJoinTask<?> job;
2223          if (task instanceof ForkJoinTask<?>) // avoid re-wrap
2224              job = (ForkJoinTask<?>) task;
2225          else
2226 <            job = ForkJoinTask.adapt(task, null);
2226 >            job = new ForkJoinTask.AdaptedRunnableAction(task);
2227          doSubmit(job);
2228      }
2229  
# Line 1361 | Line 2237 | public class ForkJoinPool extends Abstra
2237       *         scheduled for execution
2238       */
2239      public <T> ForkJoinTask<T> submit(ForkJoinTask<T> task) {
2240 +        if (task == null)
2241 +            throw new NullPointerException();
2242          doSubmit(task);
2243          return task;
2244      }
# Line 1371 | Line 2249 | public class ForkJoinPool extends Abstra
2249       *         scheduled for execution
2250       */
2251      public <T> ForkJoinTask<T> submit(Callable<T> task) {
2252 <        ForkJoinTask<T> job = ForkJoinTask.adapt(task);
2252 >        ForkJoinTask<T> job = new ForkJoinTask.AdaptedCallable<T>(task);
2253          doSubmit(job);
2254          return job;
2255      }
# Line 1382 | Line 2260 | public class ForkJoinPool extends Abstra
2260       *         scheduled for execution
2261       */
2262      public <T> ForkJoinTask<T> submit(Runnable task, T result) {
2263 <        ForkJoinTask<T> job = ForkJoinTask.adapt(task, result);
2263 >        ForkJoinTask<T> job = new ForkJoinTask.AdaptedRunnable<T>(task, result);
2264          doSubmit(job);
2265          return job;
2266      }
# Line 1393 | Line 2271 | public class ForkJoinPool extends Abstra
2271       *         scheduled for execution
2272       */
2273      public ForkJoinTask<?> submit(Runnable task) {
2274 +        if (task == null)
2275 +            throw new NullPointerException();
2276          ForkJoinTask<?> job;
2277          if (task instanceof ForkJoinTask<?>) // avoid re-wrap
2278              job = (ForkJoinTask<?>) task;
2279          else
2280 <            job = ForkJoinTask.adapt(task, null);
2280 >            job = new ForkJoinTask.AdaptedRunnableAction(task);
2281          doSubmit(job);
2282          return job;
2283      }
# Line 1407 | Line 2287 | public class ForkJoinPool extends Abstra
2287       * @throws RejectedExecutionException {@inheritDoc}
2288       */
2289      public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) {
2290 <        ArrayList<ForkJoinTask<T>> forkJoinTasks =
2291 <            new ArrayList<ForkJoinTask<T>>(tasks.size());
2292 <        for (Callable<T> task : tasks)
2293 <            forkJoinTasks.add(ForkJoinTask.adapt(task));
2294 <        invoke(new InvokeAll<T>(forkJoinTasks));
2295 <
2290 >        // In previous versions of this class, this method constructed
2291 >        // a task to run ForkJoinTask.invokeAll, but now external
2292 >        // invocation of multiple tasks is at least as efficient.
2293 >        List<ForkJoinTask<T>> fs = new ArrayList<ForkJoinTask<T>>(tasks.size());
2294 >        // Workaround needed because method wasn't declared with
2295 >        // wildcards in return type but should have been.
2296          @SuppressWarnings({"unchecked", "rawtypes"})
2297 <            List<Future<T>> futures = (List<Future<T>>) (List) forkJoinTasks;
1418 <        return futures;
1419 <    }
2297 >            List<Future<T>> futures = (List<Future<T>>) (List) fs;
2298  
2299 <    static final class InvokeAll<T> extends RecursiveAction {
2300 <        final ArrayList<ForkJoinTask<T>> tasks;
2301 <        InvokeAll(ArrayList<ForkJoinTask<T>> tasks) { this.tasks = tasks; }
2302 <        public void compute() {
2303 <            try { invokeAll(tasks); }
2304 <            catch (Exception ignore) {}
2299 >        boolean done = false;
2300 >        try {
2301 >            for (Callable<T> t : tasks) {
2302 >                ForkJoinTask<T> f = new ForkJoinTask.AdaptedCallable<T>(t);
2303 >                doSubmit(f);
2304 >                fs.add(f);
2305 >            }
2306 >            for (ForkJoinTask<T> f : fs)
2307 >                f.quietlyJoin();
2308 >            done = true;
2309 >            return futures;
2310 >        } finally {
2311 >            if (!done)
2312 >                for (ForkJoinTask<T> f : fs)
2313 >                    f.cancel(false);
2314          }
1428        private static final long serialVersionUID = -7914297376763021607L;
2315      }
2316  
2317      /**
# Line 1465 | Line 2351 | public class ForkJoinPool extends Abstra
2351       * @return the number of worker threads
2352       */
2353      public int getPoolSize() {
2354 <        return workerCounts >>> TOTAL_COUNT_SHIFT;
2354 >        return parallelism + (short)(ctl >>> TC_SHIFT);
2355      }
2356  
2357      /**
# Line 1475 | Line 2361 | public class ForkJoinPool extends Abstra
2361       * @return {@code true} if this pool uses async mode
2362       */
2363      public boolean getAsyncMode() {
2364 <        return locallyFifo;
2364 >        return localMode != 0;
2365      }
2366  
2367      /**
# Line 1487 | Line 2373 | public class ForkJoinPool extends Abstra
2373       * @return the number of worker threads
2374       */
2375      public int getRunningThreadCount() {
2376 <        return workerCounts & RUNNING_COUNT_MASK;
2376 >        int rc = 0;
2377 >        WorkQueue[] ws; WorkQueue w;
2378 >        if ((ws = workQueues) != null) {
2379 >            for (int i = 1; i < ws.length; i += 2) {
2380 >                if ((w = ws[i]) != null && w.isApparentlyUnblocked())
2381 >                    ++rc;
2382 >            }
2383 >        }
2384 >        return rc;
2385      }
2386  
2387      /**
# Line 1498 | Line 2392 | public class ForkJoinPool extends Abstra
2392       * @return the number of active threads
2393       */
2394      public int getActiveThreadCount() {
2395 <        return runState & ACTIVE_COUNT_MASK;
2395 >        int r = parallelism + (int)(ctl >> AC_SHIFT);
2396 >        return (r <= 0) ? 0 : r; // suppress momentarily negative values
2397      }
2398  
2399      /**
# Line 1513 | Line 2408 | public class ForkJoinPool extends Abstra
2408       * @return {@code true} if all threads are currently idle
2409       */
2410      public boolean isQuiescent() {
2411 <        return (runState & ACTIVE_COUNT_MASK) == 0;
2411 >        return (int)(ctl >> AC_SHIFT) + parallelism == 0;
2412      }
2413  
2414      /**
# Line 1528 | Line 2423 | public class ForkJoinPool extends Abstra
2423       * @return the number of steals
2424       */
2425      public long getStealCount() {
2426 <        return stealCount;
2426 >        long count = stealCount.get();
2427 >        WorkQueue[] ws; WorkQueue w;
2428 >        if ((ws = workQueues) != null) {
2429 >            for (int i = 1; i < ws.length; i += 2) {
2430 >                if ((w = ws[i]) != null)
2431 >                    count += w.totalSteals;
2432 >            }
2433 >        }
2434 >        return count;
2435      }
2436  
2437      /**
# Line 1543 | Line 2446 | public class ForkJoinPool extends Abstra
2446       */
2447      public long getQueuedTaskCount() {
2448          long count = 0;
2449 <        for (ForkJoinWorkerThread w : workers)
2450 <            if (w != null)
2451 <                count += w.getQueueSize();
2449 >        WorkQueue[] ws; WorkQueue w;
2450 >        if ((ws = workQueues) != null) {
2451 >            for (int i = 1; i < ws.length; i += 2) {
2452 >                if ((w = ws[i]) != null)
2453 >                    count += w.queueSize();
2454 >            }
2455 >        }
2456          return count;
2457      }
2458  
2459      /**
2460       * Returns an estimate of the number of tasks submitted to this
2461 <     * pool that have not yet begun executing.  This method takes time
2462 <     * proportional to the number of submissions.
2461 >     * pool that have not yet begun executing.  This method may take
2462 >     * time proportional to the number of submissions.
2463       *
2464       * @return the number of queued submissions
2465       */
2466      public int getQueuedSubmissionCount() {
2467 <        return submissionQueue.size();
2467 >        int count = 0;
2468 >        WorkQueue[] ws; WorkQueue w;
2469 >        if ((ws = workQueues) != null) {
2470 >            for (int i = 0; i < ws.length; i += 2) {
2471 >                if ((w = ws[i]) != null)
2472 >                    count += w.queueSize();
2473 >            }
2474 >        }
2475 >        return count;
2476      }
2477  
2478      /**
# Line 1567 | Line 2482 | public class ForkJoinPool extends Abstra
2482       * @return {@code true} if there are any queued submissions
2483       */
2484      public boolean hasQueuedSubmissions() {
2485 <        return !submissionQueue.isEmpty();
2485 >        WorkQueue[] ws; WorkQueue w;
2486 >        if ((ws = workQueues) != null) {
2487 >            for (int i = 0; i < ws.length; i += 2) {
2488 >                if ((w = ws[i]) != null && !w.isEmpty())
2489 >                    return true;
2490 >            }
2491 >        }
2492 >        return false;
2493      }
2494  
2495      /**
# Line 1578 | Line 2500 | public class ForkJoinPool extends Abstra
2500       * @return the next submission, or {@code null} if none
2501       */
2502      protected ForkJoinTask<?> pollSubmission() {
2503 <        return submissionQueue.poll();
2503 >        WorkQueue[] ws; WorkQueue w; ForkJoinTask<?> t;
2504 >        if ((ws = workQueues) != null) {
2505 >            for (int i = 0; i < ws.length; i += 2) {
2506 >                if ((w = ws[i]) != null && (t = w.poll()) != null)
2507 >                    return t;
2508 >            }
2509 >        }
2510 >        return null;
2511      }
2512  
2513      /**
# Line 1599 | Line 2528 | public class ForkJoinPool extends Abstra
2528       * @return the number of elements transferred
2529       */
2530      protected int drainTasksTo(Collection<? super ForkJoinTask<?>> c) {
2531 <        int count = submissionQueue.drainTo(c);
2532 <        for (ForkJoinWorkerThread w : workers)
2533 <            if (w != null)
2534 <                count += w.drainTasksTo(c);
2531 >        int count = 0;
2532 >        WorkQueue[] ws; WorkQueue w; ForkJoinTask<?> t;
2533 >        if ((ws = workQueues) != null) {
2534 >            for (int i = 0; i < ws.length; ++i) {
2535 >                if ((w = ws[i]) != null) {
2536 >                    while ((t = w.poll()) != null) {
2537 >                        c.add(t);
2538 >                        ++count;
2539 >                    }
2540 >                }
2541 >            }
2542 >        }
2543          return count;
2544      }
2545  
# Line 1614 | Line 2551 | public class ForkJoinPool extends Abstra
2551       * @return a string identifying this pool, as well as its state
2552       */
2553      public String toString() {
2554 <        long st = getStealCount();
2555 <        long qt = getQueuedTaskCount();
2556 <        long qs = getQueuedSubmissionCount();
2557 <        int wc = workerCounts;
2558 <        int tc = wc >>> TOTAL_COUNT_SHIFT;
2559 <        int rc = wc & RUNNING_COUNT_MASK;
2554 >        // Use a single pass through workQueues to collect counts
2555 >        long qt = 0L, qs = 0L; int rc = 0;
2556 >        long st = stealCount.get();
2557 >        long c = ctl;
2558 >        WorkQueue[] ws; WorkQueue w;
2559 >        if ((ws = workQueues) != null) {
2560 >            for (int i = 0; i < ws.length; ++i) {
2561 >                if ((w = ws[i]) != null) {
2562 >                    int size = w.queueSize();
2563 >                    if ((i & 1) == 0)
2564 >                        qs += size;
2565 >                    else {
2566 >                        qt += size;
2567 >                        st += w.totalSteals;
2568 >                        if (w.isApparentlyUnblocked())
2569 >                            ++rc;
2570 >                    }
2571 >                }
2572 >            }
2573 >        }
2574          int pc = parallelism;
2575 <        int rs = runState;
2576 <        int ac = rs & ACTIVE_COUNT_MASK;
2575 >        int tc = pc + (short)(c >>> TC_SHIFT);
2576 >        int ac = pc + (int)(c >> AC_SHIFT);
2577 >        if (ac < 0) // ignore transient negative
2578 >            ac = 0;
2579 >        String level;
2580 >        if ((c & STOP_BIT) != 0)
2581 >            level = (tc == 0) ? "Terminated" : "Terminating";
2582 >        else
2583 >            level = runState < 0 ? "Shutting down" : "Running";
2584          return super.toString() +
2585 <            "[" + runLevelToString(rs) +
2585 >            "[" + level +
2586              ", parallelism = " + pc +
2587              ", size = " + tc +
2588              ", active = " + ac +
# Line 1635 | Line 2593 | public class ForkJoinPool extends Abstra
2593              "]";
2594      }
2595  
1638    private static String runLevelToString(int s) {
1639        return ((s & TERMINATED) != 0 ? "Terminated" :
1640                ((s & TERMINATING) != 0 ? "Terminating" :
1641                 ((s & SHUTDOWN) != 0 ? "Shutting down" :
1642                  "Running")));
1643    }
1644
2596      /**
2597       * Initiates an orderly shutdown in which previously submitted
2598       * tasks are executed, but no new tasks will be accepted.
# Line 1656 | Line 2607 | public class ForkJoinPool extends Abstra
2607       */
2608      public void shutdown() {
2609          checkPermission();
2610 <        advanceRunLevel(SHUTDOWN);
1660 <        tryTerminate(false);
2610 >        tryTerminate(false, true);
2611      }
2612  
2613      /**
# Line 1678 | Line 2628 | public class ForkJoinPool extends Abstra
2628       */
2629      public List<Runnable> shutdownNow() {
2630          checkPermission();
2631 <        tryTerminate(true);
2631 >        tryTerminate(true, true);
2632          return Collections.emptyList();
2633      }
2634  
# Line 1688 | Line 2638 | public class ForkJoinPool extends Abstra
2638       * @return {@code true} if all tasks have completed following shut down
2639       */
2640      public boolean isTerminated() {
2641 <        return runState >= TERMINATED;
2641 >        long c = ctl;
2642 >        return ((c & STOP_BIT) != 0L &&
2643 >                (short)(c >>> TC_SHIFT) == -parallelism);
2644      }
2645  
2646      /**
# Line 1696 | Line 2648 | public class ForkJoinPool extends Abstra
2648       * commenced but not yet completed.  This method may be useful for
2649       * debugging. A return of {@code true} reported a sufficient
2650       * period after shutdown may indicate that submitted tasks have
2651 <     * ignored or suppressed interruption, causing this executor not
2652 <     * to properly terminate.
2651 >     * ignored or suppressed interruption, or are waiting for IO,
2652 >     * causing this executor not to properly terminate. (See the
2653 >     * advisory notes for class {@link ForkJoinTask} stating that
2654 >     * tasks should not normally entail blocking operations.  But if
2655 >     * they do, they must abort them on interrupt.)
2656       *
2657       * @return {@code true} if terminating but not yet terminated
2658       */
2659      public boolean isTerminating() {
2660 <        return (runState & (TERMINATING|TERMINATED)) == TERMINATING;
2661 <    }
2662 <
1708 <    /**
1709 <     * Returns true if terminating or terminated. Used by ForkJoinWorkerThread.
1710 <     */
1711 <    final boolean isAtLeastTerminating() {
1712 <        return runState >= TERMINATING;
2660 >        long c = ctl;
2661 >        return ((c & STOP_BIT) != 0L &&
2662 >                (short)(c >>> TC_SHIFT) != -parallelism);
2663      }
2664  
2665      /**
# Line 1718 | Line 2668 | public class ForkJoinPool extends Abstra
2668       * @return {@code true} if this pool has been shut down
2669       */
2670      public boolean isShutdown() {
2671 <        return runState >= SHUTDOWN;
2671 >        return runState < 0;
2672      }
2673  
2674      /**
# Line 1734 | Line 2684 | public class ForkJoinPool extends Abstra
2684       */
2685      public boolean awaitTermination(long timeout, TimeUnit unit)
2686          throws InterruptedException {
2687 +        long nanos = unit.toNanos(timeout);
2688 +        final Mutex lock = this.lock;
2689 +        lock.lock();
2690          try {
2691 <            return termination.awaitAdvanceInterruptibly(0, timeout, unit) > 0;
2692 <        } catch (TimeoutException ex) {
2693 <            return false;
2691 >            for (;;) {
2692 >                if (isTerminated())
2693 >                    return true;
2694 >                if (nanos <= 0)
2695 >                    return false;
2696 >                nanos = termination.awaitNanos(nanos);
2697 >            }
2698 >        } finally {
2699 >            lock.unlock();
2700          }
2701      }
2702  
# Line 1749 | Line 2708 | public class ForkJoinPool extends Abstra
2708       * {@code isReleasable} must return {@code true} if blocking is
2709       * not necessary. Method {@code block} blocks the current thread
2710       * if necessary (perhaps internally invoking {@code isReleasable}
2711 <     * before actually blocking). The unusual methods in this API
2712 <     * accommodate synchronizers that may, but don't usually, block
2713 <     * for long periods. Similarly, they allow more efficient internal
2714 <     * handling of cases in which additional workers may be, but
2715 <     * usually are not, needed to ensure sufficient parallelism.
2716 <     * Toward this end, implementations of method {@code isReleasable}
2717 <     * must be amenable to repeated invocation.
2711 >     * before actually blocking). These actions are performed by any
2712 >     * thread invoking {@link ForkJoinPool#managedBlock}.  The
2713 >     * unusual methods in this API accommodate synchronizers that may,
2714 >     * but don't usually, block for long periods. Similarly, they
2715 >     * allow more efficient internal handling of cases in which
2716 >     * additional workers may be, but usually are not, needed to
2717 >     * ensure sufficient parallelism.  Toward this end,
2718 >     * implementations of method {@code isReleasable} must be amenable
2719 >     * to repeated invocation.
2720       *
2721       * <p>For example, here is a ManagedBlocker based on a
2722       * ReentrantLock:
# Line 1835 | Line 2796 | public class ForkJoinPool extends Abstra
2796      public static void managedBlock(ManagedBlocker blocker)
2797          throws InterruptedException {
2798          Thread t = Thread.currentThread();
2799 <        if (t instanceof ForkJoinWorkerThread) {
2800 <            ForkJoinWorkerThread w = (ForkJoinWorkerThread) t;
2801 <            w.pool.awaitBlocker(blocker);
2802 <        }
2803 <        else {
2804 <            do {} while (!blocker.isReleasable() && !blocker.block());
2799 >        ForkJoinPool p = ((t instanceof ForkJoinWorkerThread) ?
2800 >                          ((ForkJoinWorkerThread)t).pool : null);
2801 >        while (!blocker.isReleasable()) {
2802 >            if (p == null || p.tryCompensate(null, blocker)) {
2803 >                try {
2804 >                    do {} while (!blocker.isReleasable() && !blocker.block());
2805 >                } finally {
2806 >                    if (p != null)
2807 >                        p.incrementActiveCount();
2808 >                }
2809 >                break;
2810 >            }
2811          }
2812      }
2813  
# Line 1849 | Line 2816 | public class ForkJoinPool extends Abstra
2816      // implement RunnableFuture.
2817  
2818      protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
2819 <        return (RunnableFuture<T>) ForkJoinTask.adapt(runnable, value);
2819 >        return new ForkJoinTask.AdaptedRunnable<T>(runnable, value);
2820      }
2821  
2822      protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
2823 <        return (RunnableFuture<T>) ForkJoinTask.adapt(callable);
2823 >        return new ForkJoinTask.AdaptedCallable<T>(callable);
2824      }
2825  
2826      // Unsafe mechanics
2827 <
2828 <    private static final sun.misc.Unsafe UNSAFE = getUnsafe();
2829 <    private static final long workerCountsOffset =
2830 <        objectFieldOffset("workerCounts", ForkJoinPool.class);
2831 <    private static final long runStateOffset =
2832 <        objectFieldOffset("runState", ForkJoinPool.class);
2833 <    private static final long eventCountOffset =
2834 <        objectFieldOffset("eventCount", ForkJoinPool.class);
2835 <    private static final long eventWaitersOffset =
2836 <        objectFieldOffset("eventWaiters", ForkJoinPool.class);
2837 <    private static final long stealCountOffset =
2838 <        objectFieldOffset("stealCount", ForkJoinPool.class);
2839 <    private static final long spareWaitersOffset =
2840 <        objectFieldOffset("spareWaiters", ForkJoinPool.class);
1874 <
1875 <    private static long objectFieldOffset(String field, Class<?> klazz) {
2827 >    private static final sun.misc.Unsafe U;
2828 >    private static final long CTL;
2829 >    private static final long PARKBLOCKER;
2830 >    private static final int ABASE;
2831 >    private static final int ASHIFT;
2832 >
2833 >    static {
2834 >        poolNumberGenerator = new AtomicInteger();
2835 >        nextSubmitterSeed = new AtomicInteger(0x55555555);
2836 >        modifyThreadPermission = new RuntimePermission("modifyThread");
2837 >        defaultForkJoinWorkerThreadFactory =
2838 >            new DefaultForkJoinWorkerThreadFactory();
2839 >        submitters = new ThreadSubmitter();
2840 >        int s;
2841          try {
2842 <            return UNSAFE.objectFieldOffset(klazz.getDeclaredField(field));
2843 <        } catch (NoSuchFieldException e) {
2844 <            // Convert Exception to corresponding Error
2845 <            NoSuchFieldError error = new NoSuchFieldError(field);
2846 <            error.initCause(e);
2847 <            throw error;
2848 <        }
2842 >            U = getUnsafe();
2843 >            Class<?> k = ForkJoinPool.class;
2844 >            Class<?> ak = ForkJoinTask[].class;
2845 >            CTL = U.objectFieldOffset
2846 >                (k.getDeclaredField("ctl"));
2847 >            Class<?> tk = Thread.class;
2848 >            PARKBLOCKER = U.objectFieldOffset
2849 >                (tk.getDeclaredField("parkBlocker"));
2850 >            ABASE = U.arrayBaseOffset(ak);
2851 >            s = U.arrayIndexScale(ak);
2852 >        } catch (Exception e) {
2853 >            throw new Error(e);
2854 >        }
2855 >        if ((s & (s-1)) != 0)
2856 >            throw new Error("data type scale not a power of two");
2857 >        ASHIFT = 31 - Integer.numberOfLeadingZeros(s);
2858      }
2859  
2860      /**
# Line 1910 | Line 2884 | public class ForkJoinPool extends Abstra
2884              }
2885          }
2886      }
2887 +
2888   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines