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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines