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.40 by jsr166, Mon Aug 3 00:53:15 2009 UTC vs.
Revision 1.136 by dl, Mon Oct 29 17:23:34 2012 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines