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.27 by jsr166, Sun Jul 26 17:33:37 2009 UTC vs.
Revision 1.128 by dl, Mon Apr 9 13:11:44 2012 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines