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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines