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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines