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.47 by jsr166, Wed Aug 5 15:40:09 2009 UTC vs.
Revision 1.57 by dl, Wed Jul 7 19:52:31 2010 UTC

# Line 13 | Line 13 | import java.util.Arrays;
13   import java.util.Collection;
14   import java.util.Collections;
15   import java.util.List;
16 import java.util.concurrent.locks.Condition;
16   import java.util.concurrent.locks.LockSupport;
17   import java.util.concurrent.locks.ReentrantLock;
18   import java.util.concurrent.atomic.AtomicInteger;
19 < import java.util.concurrent.atomic.AtomicLong;
19 > import java.util.concurrent.CountDownLatch;
20  
21   /**
22   * An {@link ExecutorService} for running {@link ForkJoinTask}s.
23   * A {@code ForkJoinPool} provides the entry point for submissions
24 < * from non-{@code ForkJoinTask}s, as well as management and
25 < * monitoring operations.  
24 > * from non-{@code ForkJoinTask} clients, as well as management and
25 > * monitoring operations.
26   *
27   * <p>A {@code ForkJoinPool} differs from other kinds of {@link
28   * ExecutorService} mainly by virtue of employing
# Line 31 | Line 30 | import java.util.concurrent.atomic.Atomi
30   * execute subtasks created by other active tasks (eventually blocking
31   * waiting for work if none exist). This enables efficient processing
32   * when most tasks spawn other subtasks (as do most {@code
33 < * ForkJoinTask}s). A {@code ForkJoinPool} may also be used for mixed
34 < * execution of some plain {@code Runnable}- or {@code Callable}-
35 < * based activities along with {@code ForkJoinTask}s. When setting
37 < * {@linkplain #setAsyncMode async mode}, a {@code ForkJoinPool} may
38 < * also be appropriate for use with fine-grained tasks of any form
39 < * that are never joined. Otherwise, other {@code ExecutorService}
40 < * implementations are typically more appropriate choices.
33 > * ForkJoinTask}s). When setting <em>asyncMode</em> to true in
34 > * constructors, {@code ForkJoinPool}s may also be appropriate for use
35 > * with event-style tasks that are never joined.
36   *
37   * <p>A {@code ForkJoinPool} is constructed with a given target
38   * parallelism level; by default, equal to the number of available
39 < * processors. Unless configured otherwise via {@link
40 < * #setMaintainsParallelism}, the pool attempts to maintain this
41 < * number of active (or available) threads by dynamically adding,
42 < * suspending, or resuming internal worker threads, even if some tasks
43 < * are stalled waiting to join others. However, no such adjustments
44 < * are performed in the face of blocked IO or other unmanaged
45 < * synchronization. The nested {@link ManagedBlocker} interface
51 < * enables extension of the kinds of synchronization accommodated.
52 < * The target parallelism level may also be changed dynamically
53 < * ({@link #setParallelism}). The total number of threads may be
54 < * limited using method {@link #setMaximumPoolSize}, in which case it
55 < * may become possible for the activities of a pool to stall due to
56 < * the lack of available threads to process new tasks.
39 > * processors. The pool attempts to maintain enough active (or
40 > * available) threads by dynamically adding, suspending, or resuming
41 > * internal worker threads, even if some tasks are stalled waiting to
42 > * join others. However, no such adjustments are guaranteed in the
43 > * face of blocked IO or other unmanaged synchronization. The nested
44 > * {@link ManagedBlocker} interface enables extension of the kinds of
45 > * synchronization accommodated.
46   *
47   * <p>In addition to execution and lifecycle control methods, this
48   * class provides status check methods (for example
# Line 62 | Line 51 | import java.util.concurrent.atomic.Atomi
51   * {@link #toString} returns indications of pool state in a
52   * convenient form for informal monitoring.
53   *
54 + * <p> As is the case with other ExecutorServices, there are three
55 + * main task execution methods summarized in the follwoing
56 + * table. These are designed to be used by clients not already engaged
57 + * in fork/join computations in the current pool.  The main forms of
58 + * these methods accept instances of {@code ForkJoinTask}, but
59 + * overloaded forms also allow mixed execution of plain {@code
60 + * Runnable}- or {@code Callable}- based activities as well.  However,
61 + * tasks that are already executing in a pool should normally
62 + * <em>NOT</em> use these pool execution methods, but instead use the
63 + * within-computation forms listed in the table. To avoid inadvertant
64 + * cyclic task dependencies and to improve performance, task
65 + * submissions to the current pool by an ongoing fork/join
66 + * computations may be implicitly translated to the corresponding
67 + * ForkJoinTask forms.
68 + *
69 + * <table BORDER CELLPADDING=3 CELLSPACING=1>
70 + *  <tr>
71 + *    <td></td>
72 + *    <td ALIGN=CENTER> <b>Call from non-fork/join clients</b></td>
73 + *    <td ALIGN=CENTER> <b>Call from within fork/join computations</b></td>
74 + *  </tr>
75 + *  <tr>
76 + *    <td> <b>Arange async execution</td>
77 + *    <td> {@link #execute(ForkJoinTask)}</td>
78 + *    <td> {@link ForkJoinTask#fork}</td>
79 + *  </tr>
80 + *  <tr>
81 + *    <td> <b>Await and obtain result</td>
82 + *    <td> {@link #invoke(ForkJoinTask)}</td>
83 + *    <td> {@link ForkJoinTask#invoke}</td>
84 + *  </tr>
85 + *  <tr>
86 + *    <td> <b>Arrange exec and obtain Future</td>
87 + *    <td> {@link #submit(ForkJoinTask)}</td>
88 + *    <td> {@link ForkJoinTask#fork} (ForkJoinTasks <em>are</em> Futures)</td>
89 + *  </tr>
90 + * </table>
91 + *
92   * <p><b>Sample Usage.</b> Normally a single {@code ForkJoinPool} is
93   * used for all parallel task execution in a program or subsystem.
94   * Otherwise, use would not usually outweigh the construction and
# Line 82 | Line 109 | import java.util.concurrent.atomic.Atomi
109   *
110   * <p><b>Implementation notes</b>: This implementation restricts the
111   * maximum number of running threads to 32767. Attempts to create
112 < * pools with greater than the maximum result in
112 > * pools with greater than the maximum number result in
113   * {@code IllegalArgumentException}.
114   *
115 + * <p>This implementation rejects submitted tasks (that is, by throwing
116 + * {@link RejectedExecutionException}) only when the pool is shut down.
117 + *
118   * @since 1.7
119   * @author Doug Lea
120   */
121   public class ForkJoinPool extends AbstractExecutorService {
122  
123      /*
124 <     * See the extended comments interspersed below for design,
125 <     * rationale, and walkthroughs.
124 >     * Implementation Overview
125 >     *
126 >     * This class provides the central bookkeeping and control for a
127 >     * set of worker threads: Submissions from non-FJ threads enter
128 >     * into a submission queue. Workers take these tasks and typically
129 >     * split them into subtasks that may be stolen by other workers.
130 >     * The main work-stealing mechanics implemented in class
131 >     * ForkJoinWorkerThread give first priority to processing tasks
132 >     * from their own queues (LIFO or FIFO, depending on mode), then
133 >     * to randomized FIFO steals of tasks in other worker queues, and
134 >     * lastly to new submissions. These mechanics do not consider
135 >     * affinities, loads, cache localities, etc, so rarely provide the
136 >     * best possible performance on a given machine, but portably
137 >     * provide good throughput by averaging over these factors.
138 >     * (Further, even if we did try to use such information, we do not
139 >     * usually have a basis for exploiting it. For example, some sets
140 >     * of tasks profit from cache affinities, but others are harmed by
141 >     * cache pollution effects.)
142 >     *
143 >     * The main throughput advantages of work-stealing stem from
144 >     * decentralized control -- workers mostly steal tasks from each
145 >     * other. We do not want to negate this by creating bottlenecks
146 >     * implementing the management responsibilities of this class. So
147 >     * we use a collection of techniques that avoid, reduce, or cope
148 >     * well with contention. These entail several instances of
149 >     * bit-packing into CASable fields to maintain only the minimally
150 >     * required atomicity. To enable such packing, we restrict maximum
151 >     * parallelism to (1<<15)-1 (enabling twice this to fit into a 16
152 >     * bit field), which is far in excess of normal operating range.
153 >     * Even though updates to some of these bookkeeping fields do
154 >     * sometimes contend with each other, they don't normally
155 >     * cache-contend with updates to others enough to warrant memory
156 >     * padding or isolation. So they are all held as fields of
157 >     * ForkJoinPool objects.  The main capabilities are as follows:
158 >     *
159 >     * 1. Creating and removing workers. Workers are recorded in the
160 >     * "workers" array. This is an array as opposed to some other data
161 >     * structure to support index-based random steals by workers.
162 >     * Updates to the array recording new workers and unrecording
163 >     * terminated ones are protected from each other by a lock
164 >     * (workerLock) but the array is otherwise concurrently readable,
165 >     * and accessed directly by workers. To simplify index-based
166 >     * operations, the array size is always a power of two, and all
167 >     * readers must tolerate null slots. Currently, all worker thread
168 >     * creation is on-demand, triggered by task submissions,
169 >     * replacement of terminated workers, and/or compensation for
170 >     * blocked workers. However, all other support code is set up to
171 >     * work with other policies.
172 >     *
173 >     * 2. Bookkeeping for dynamically adding and removing workers. We
174 >     * aim to approximately maintain the given level of parallelism.
175 >     * When some workers are known to be blocked (on joins or via
176 >     * ManagedBlocker), we may create or resume others to take their
177 >     * place until they unblock (see below). Implementing this
178 >     * requires counts of the number of "running" threads (i.e., those
179 >     * that are neither blocked nor artifically suspended) as well as
180 >     * the total number.  These two values are packed into one field,
181 >     * "workerCounts" because we need accurate snapshots when deciding
182 >     * to create, resume or suspend.  To support these decisions,
183 >     * updates to spare counts must be prospective (not
184 >     * retrospective).  For example, the running count is decremented
185 >     * before blocking by a thread about to block as a spare, but
186 >     * incremented by the thread about to unblock it. Updates upon
187 >     * resumption ofr threads blocking in awaitJoin or awaitBlocker
188 >     * cannot usually be prospective, so the running count is in
189 >     * general an upper bound of the number of productively running
190 >     * threads Updates to the workerCounts field sometimes transiently
191 >     * encounter a fair amount of contention when join dependencies
192 >     * are such that many threads block or unblock at about the same
193 >     * time. We alleviate this by sometimes performing an alternative
194 >     * action on contention like releasing waiters or locating spares.
195 >     *
196 >     * 3. Maintaining global run state. The run state of the pool
197 >     * consists of a runLevel (SHUTDOWN, TERMINATING, etc) similar to
198 >     * those in other Executor implementations, as well as a count of
199 >     * "active" workers -- those that are, or soon will be, or
200 >     * recently were executing tasks. The runLevel and active count
201 >     * are packed together in order to correctly trigger shutdown and
202 >     * termination. Without care, active counts can be subject to very
203 >     * high contention.  We substantially reduce this contention by
204 >     * relaxing update rules.  A worker must claim active status
205 >     * prospectively, by activating if it sees that a submitted or
206 >     * stealable task exists (it may find after activating that the
207 >     * task no longer exists). It stays active while processing this
208 >     * task (if it exists) and any other local subtasks it produces,
209 >     * until it cannot find any other tasks. It then tries
210 >     * inactivating (see method preStep), but upon update contention
211 >     * instead scans for more tasks, later retrying inactivation if it
212 >     * doesn't find any.
213 >     *
214 >     * 4. Managing idle workers waiting for tasks. We cannot let
215 >     * workers spin indefinitely scanning for tasks when none are
216 >     * available. On the other hand, we must quickly prod them into
217 >     * action when new tasks are submitted or generated.  We
218 >     * park/unpark these idle workers using an event-count scheme.
219 >     * Field eventCount is incremented upon events that may enable
220 >     * workers that previously could not find a task to now find one:
221 >     * Submission of a new task to the pool, or another worker pushing
222 >     * a task onto a previously empty queue.  (We also use this
223 >     * mechanism for termination and reconfiguration actions that
224 >     * require wakeups of idle workers).  Each worker maintains its
225 >     * last known event count, and blocks when a scan for work did not
226 >     * find a task AND its lastEventCount matches the current
227 >     * eventCount. Waiting idle workers are recorded in a variant of
228 >     * Treiber stack headed by field eventWaiters which, when nonzero,
229 >     * encodes the thread index and count awaited for by the worker
230 >     * thread most recently calling eventSync. This thread in turn has
231 >     * a record (field nextEventWaiter) for the next waiting worker.
232 >     * In addition to allowing simpler decisions about need for
233 >     * wakeup, the event count bits in eventWaiters serve the role of
234 >     * tags to avoid ABA errors in Treiber stacks.  To reduce delays
235 >     * in task diffusion, workers not otherwise occupied may invoke
236 >     * method releaseWaiters, that removes and signals (unparks)
237 >     * workers not waiting on current count. To minimize task
238 >     * production stalls associate with signalling, any worker pushing
239 >     * a task on an empty queue invokes the weaker method signalWork,
240 >     * that only releases idle workers until it detects interference
241 >     * by other threads trying to release, and lets them take
242 >     * over. The net effect is a tree-like diffusion of signals, where
243 >     * released threads (and possibly others) help with unparks.  To
244 >     * further reduce contention effects a bit, failed CASes to
245 >     * increment field eventCount are tolerated without retries.
246 >     * Conceptually they are merged into the same event, which is OK
247 >     * when their only purpose is to enable workers to scan for work.
248 >     *
249 >     * 5. Managing suspension of extra workers. When a worker is about
250 >     * to block waiting for a join (or via ManagedBlockers), we may
251 >     * create a new thread to maintain parallelism level, or at least
252 >     * avoid starvation (see below). Usually, extra threads are needed
253 >     * for only very short periods, yet join dependencies are such
254 >     * that we sometimes need them in bursts. Rather than create new
255 >     * threads each time this happens, we suspend no-longer-needed
256 >     * extra ones as "spares". For most purposes, we don't distinguish
257 >     * "extra" spare threads from normal "core" threads: On each call
258 >     * to preStep (the only point at which we can do this) a worker
259 >     * checks to see if there are now too many running workers, and if
260 >     * so, suspends itself.  Methods awaitJoin and awaitBlocker look
261 >     * for suspended threads to resume before considering creating a
262 >     * new replacement. We don't need a special data structure to
263 >     * maintain spares; simply scanning the workers array looking for
264 >     * worker.isSuspended() is fine because the calling thread is
265 >     * otherwise not doing anything useful anyway; we are at least as
266 >     * happy if after locating a spare, the caller doesn't actually
267 >     * block because the join is ready before we try to adjust and
268 >     * compensate.  Note that this is intrinsically racy.  One thread
269 >     * may become a spare at about the same time as another is
270 >     * needlessly being created. We counteract this and related slop
271 >     * in part by requiring resumed spares to immediately recheck (in
272 >     * preStep) to see whether they they should re-suspend. The only
273 >     * effective difference between "extra" and "core" threads is that
274 >     * we allow the "extra" ones to time out and die if they are not
275 >     * resumed within a keep-alive interval of a few seconds. This is
276 >     * implemented mainly within ForkJoinWorkerThread, but requires
277 >     * some coordination (isTrimmed() -- meaning killed while
278 >     * suspended) to correctly maintain pool counts.
279 >     *
280 >     * 6. Deciding when to create new workers. The main dynamic
281 >     * control in this class is deciding when to create extra threads,
282 >     * in methods awaitJoin and awaitBlocker. We always need to create
283 >     * one when the number of running threads becomes zero. But
284 >     * because blocked joins are typically dependent, we don't
285 >     * necessarily need or want one-to-one replacement. Instead, we
286 >     * use a combination of heuristics that adds threads only when the
287 >     * pool appears to be approaching starvation.  These effectively
288 >     * reduce churn at the price of systematically undershooting
289 >     * target parallelism when many threads are blocked.  However,
290 >     * biasing toward undeshooting partially compensates for the above
291 >     * mechanics to suspend extra threads, that normally lead to
292 >     * overshoot because we can only suspend workers in-between
293 >     * top-level actions. It also better copes with the fact that some
294 >     * of the methods in this class tend to never become compiled (but
295 >     * are interpreted), so some components of the entire set of
296 >     * controls might execute many times faster than others. And
297 >     * similarly for cases where the apparent lack of work is just due
298 >     * to GC stalls and other transient system activity.
299 >     *
300 >     * Beware that there is a lot of representation-level coupling
301 >     * among classes ForkJoinPool, ForkJoinWorkerThread, and
302 >     * ForkJoinTask.  For example, direct access to "workers" array by
303 >     * workers, and direct access to ForkJoinTask.status by both
304 >     * ForkJoinPool and ForkJoinWorkerThread.  There is little point
305 >     * trying to reduce this, since any associated future changes in
306 >     * representations will need to be accompanied by algorithmic
307 >     * changes anyway.
308 >     *
309 >     * Style notes: There are lots of inline assignments (of form
310 >     * "while ((local = field) != 0)") which are usually the simplest
311 >     * way to ensure read orderings. Also several occurrences of the
312 >     * unusual "do {} while(!cas...)" which is the simplest way to
313 >     * force an update of a CAS'ed variable. There are also a few
314 >     * other coding oddities that help some methods perform reasonably
315 >     * even when interpreted (not compiled).
316 >     *
317 >     * The order of declarations in this file is: (1) statics (2)
318 >     * fields (along with constants used when unpacking some of them)
319 >     * (3) internal control methods (4) callbacks and other support
320 >     * for ForkJoinTask and ForkJoinWorkerThread classes, (5) exported
321 >     * methods (plus a few little helpers).
322       */
323  
98    /** Mask for packing and unpacking shorts */
99    private static final int  shortMask = 0xffff;
100
101    /** Max pool size -- must be a power of two minus 1 */
102    private static final int MAX_THREADS =  0x7FFF;
103
324      /**
325       * Factory for creating new {@link ForkJoinWorkerThread}s.
326       * A {@code ForkJoinWorkerThreadFactory} must be defined and used
# Line 112 | Line 332 | public class ForkJoinPool extends Abstra
332           * Returns a new worker thread operating in the given pool.
333           *
334           * @param pool the pool this thread works in
335 <         * @throws NullPointerException if pool is null
335 >         * @throws NullPointerException if the pool is null
336           */
337          public ForkJoinWorkerThread newThread(ForkJoinPool pool);
338      }
# Line 121 | Line 341 | public class ForkJoinPool extends Abstra
341       * Default ForkJoinWorkerThreadFactory implementation; creates a
342       * new ForkJoinWorkerThread.
343       */
344 <    static class  DefaultForkJoinWorkerThreadFactory
344 >    static class DefaultForkJoinWorkerThreadFactory
345          implements ForkJoinWorkerThreadFactory {
346          public ForkJoinWorkerThread newThread(ForkJoinPool pool) {
347 <            try {
128 <                return new ForkJoinWorkerThread(pool);
129 <            } catch (OutOfMemoryError oom)  {
130 <                return null;
131 <            }
347 >            return new ForkJoinWorkerThread(pool);
348          }
349      }
350  
# Line 164 | Line 380 | public class ForkJoinPool extends Abstra
380          new AtomicInteger();
381  
382      /**
383 <     * Array holding all worker threads in the pool. Initialized upon
384 <     * first use. Array size must be a power of two.  Updates and
385 <     * replacements are protected by workerLock, but it is always kept
386 <     * in a consistent enough state to be randomly accessed without
387 <     * locking by workers performing work-stealing.
383 >     * Absolute bound for parallelism level. Twice this number must
384 >     * fit into a 16bit field to enable word-packing for some counts.
385 >     */
386 >    private static final int MAX_THREADS = 0x7fff;
387 >
388 >    /**
389 >     * Array holding all worker threads in the pool.  Array size must
390 >     * be a power of two.  Updates and replacements are protected by
391 >     * workerLock, but the array is always kept in a consistent enough
392 >     * state to be randomly accessed without locking by workers
393 >     * performing work-stealing, as well as other traversal-based
394 >     * methods in this class. All readers must tolerate that some
395 >     * array slots may be null.
396       */
397      volatile ForkJoinWorkerThread[] workers;
398  
399      /**
400 <     * Lock protecting access to workers.
400 >     * Queue for external submissions.
401       */
402 <    private final ReentrantLock workerLock;
402 >    private final LinkedTransferQueue<ForkJoinTask<?>> submissionQueue;
403  
404      /**
405 <     * Condition for awaitTermination.
405 >     * Lock protecting updates to workers array.
406       */
407 <    private final Condition termination;
407 >    private final ReentrantLock workerLock;
408  
409      /**
410 <     * The uncaught exception handler used when any worker
187 <     * abruptly terminates
410 >     * Latch released upon termination.
411       */
412 <    private Thread.UncaughtExceptionHandler ueh;
412 >    private final Phaser termination;
413  
414      /**
415       * Creation factory for worker threads.
# Line 194 | Line 417 | public class ForkJoinPool extends Abstra
417      private final ForkJoinWorkerThreadFactory factory;
418  
419      /**
420 <     * Head of stack of threads that were created to maintain
421 <     * parallelism when other threads blocked, but have since
199 <     * suspended when the parallelism level rose.
420 >     * Sum of per-thread steal counts, updated only when threads are
421 >     * idle or terminating.
422       */
423 <    private volatile WaitQueueNode spareStack;
423 >    private volatile long stealCount;
424  
425      /**
426 <     * Sum of per-thread steal counts, updated only when threads are
427 <     * idle or terminating.
426 >     * Encoded record of top of treiber stack of threads waiting for
427 >     * events. The top 32 bits contain the count being waited for. The
428 >     * bottom word contains one plus the pool index of waiting worker
429 >     * thread.
430       */
431 <    private final AtomicLong stealCount;
431 >    private volatile long eventWaiters;
432 >
433 >    private static final int  EVENT_COUNT_SHIFT = 32;
434 >    private static final long WAITER_INDEX_MASK = (1L << EVENT_COUNT_SHIFT)-1L;
435  
436      /**
437 <     * Queue for external submissions.
437 >     * A counter for events that may wake up worker threads:
438 >     *   - Submission of a new task to the pool
439 >     *   - A worker pushing a task on an empty queue
440 >     *   - termination and reconfiguration
441       */
442 <    private final LinkedTransferQueue<ForkJoinTask<?>> submissionQueue;
442 >    private volatile int eventCount;
443 >
444 >    /**
445 >     * Lifecycle control. The low word contains the number of workers
446 >     * that are (probably) executing tasks. This value is atomically
447 >     * incremented before a worker gets a task to run, and decremented
448 >     * when worker has no tasks and cannot find any.  Bits 16-18
449 >     * contain runLevel value. When all are zero, the pool is
450 >     * running. Level transitions are monotonic (running -> shutdown
451 >     * -> terminating -> terminated) so each transition adds a bit.
452 >     * These are bundled together to ensure consistent read for
453 >     * termination checks (i.e., that runLevel is at least SHUTDOWN
454 >     * and active threads is zero).
455 >     */
456 >    private volatile int runState;
457 >
458 >    // Note: The order among run level values matters.
459 >    private static final int RUNLEVEL_SHIFT     = 16;
460 >    private static final int SHUTDOWN           = 1 << RUNLEVEL_SHIFT;
461 >    private static final int TERMINATING        = 1 << (RUNLEVEL_SHIFT + 1);
462 >    private static final int TERMINATED         = 1 << (RUNLEVEL_SHIFT + 2);
463 >    private static final int ACTIVE_COUNT_MASK  = (1 << RUNLEVEL_SHIFT) - 1;
464 >    private static final int ONE_ACTIVE         = 1; // active update delta
465 >
466 >    /**
467 >     * Holds number of total (i.e., created and not yet terminated)
468 >     * and running (i.e., not blocked on joins or other managed sync)
469 >     * threads, packed together to ensure consistent snapshot when
470 >     * making decisions about creating and suspending spare
471 >     * threads. Updated only by CAS. Note that adding a new worker
472 >     * requires incrementing both counts, since workers start off in
473 >     * running state.  This field is also used for memory-fencing
474 >     * configuration parameters.
475 >     */
476 >    private volatile int workerCounts;
477 >
478 >    private static final int TOTAL_COUNT_SHIFT  = 16;
479 >    private static final int RUNNING_COUNT_MASK = (1 << TOTAL_COUNT_SHIFT) - 1;
480 >    private static final int ONE_RUNNING        = 1;
481 >    private static final int ONE_TOTAL          = 1 << TOTAL_COUNT_SHIFT;
482 >
483 >    /**
484 >     * The target parallelism level.
485 >     * Accessed directly by ForkJoinWorkerThreads.
486 >     */
487 >    final int parallelism;
488  
489      /**
490 <     * Head of Treiber stack for barrier sync. See below for explanation.
490 >     * True if use local fifo, not default lifo, for local polling
491 >     * Read by, and replicated by ForkJoinWorkerThreads
492       */
493 <    private volatile WaitQueueNode syncStack;
493 >    final boolean locallyFifo;
494  
495      /**
496 <     * The count for event barrier
496 >     * The uncaught exception handler used when any worker abruptly
497 >     * terminates.
498       */
499 <    private volatile long eventCount;
499 >    private final Thread.UncaughtExceptionHandler ueh;
500  
501      /**
502       * Pool number, just for assigning useful names to worker threads
503       */
504      private final int poolNumber;
505  
506 +    // utilities for updating fields
507 +
508      /**
509 <     * The maximum allowed pool size
509 >     * Increments running count.  Also used by ForkJoinTask.
510       */
511 <    private volatile int maxPoolSize;
511 >    final void incrementRunningCount() {
512 >        int c;
513 >        do {} while (!UNSAFE.compareAndSwapInt(this, workerCountsOffset,
514 >                                               c = workerCounts,
515 >                                               c + ONE_RUNNING));
516 >    }
517 >    
518 >    /**
519 >     * Tries to decrement running count unless already zero
520 >     */
521 >    final boolean tryDecrementRunningCount() {
522 >        int wc = workerCounts;
523 >        if ((wc & RUNNING_COUNT_MASK) == 0)
524 >            return false;
525 >        return UNSAFE.compareAndSwapInt(this, workerCountsOffset,
526 >                                        wc, wc - ONE_RUNNING);
527 >    }
528  
529      /**
530 <     * The desired parallelism level, updated only under workerLock.
530 >     * Tries incrementing active count; fails on contention.
531 >     * Called by workers before executing tasks.
532 >     *
533 >     * @return true on success
534       */
535 <    private volatile int parallelism;
535 >    final boolean tryIncrementActiveCount() {
536 >        int c;
537 >        return UNSAFE.compareAndSwapInt(this, runStateOffset,
538 >                                        c = runState, c + ONE_ACTIVE);
539 >    }
540  
541      /**
542 <     * True if use local fifo, not default lifo, for local polling
542 >     * Tries decrementing active count; fails on contention.
543 >     * Called when workers cannot find tasks to run.
544       */
545 <    private volatile boolean locallyFifo;
545 >    final boolean tryDecrementActiveCount() {
546 >        int c;
547 >        return UNSAFE.compareAndSwapInt(this, runStateOffset,
548 >                                        c = runState, c - ONE_ACTIVE);
549 >    }
550  
551      /**
552 <     * Holds number of total (i.e., created and not yet terminated)
553 <     * and running (i.e., not blocked on joins or other managed sync)
247 <     * threads, packed into one int to ensure consistent snapshot when
248 <     * making decisions about creating and suspending spare
249 <     * threads. Updated only by CAS.  Note: CASes in
250 <     * updateRunningCount and preJoin assume that running active count
251 <     * is in low word, so need to be modified if this changes.
552 >     * Advances to at least the given level. Returns true if not
553 >     * already in at least the given level.
554       */
555 <    private volatile int workerCounts;
555 >    private boolean advanceRunLevel(int level) {
556 >        for (;;) {
557 >            int s = runState;
558 >            if ((s & level) != 0)
559 >                return false;
560 >            if (UNSAFE.compareAndSwapInt(this, runStateOffset, s, s | level))
561 >                return true;
562 >        }
563 >    }
564  
565 <    private static int totalCountOf(int s)           { return s >>> 16;  }
256 <    private static int runningCountOf(int s)         { return s & shortMask; }
257 <    private static int workerCountsFor(int t, int r) { return (t << 16) + r; }
565 >    // workers array maintenance
566  
567      /**
568 <     * Adds delta (which may be negative) to running count.  This must
569 <     * be called before (with negative arg) and after (with positive)
570 <     * any managed synchronization (i.e., mainly, joins).
568 >     * Records and returns a workers array index for new worker.
569 >     */
570 >    private int recordWorker(ForkJoinWorkerThread w) {
571 >        // Try using slot totalCount-1. If not available, scan and/or resize
572 >        int k = (workerCounts >>> TOTAL_COUNT_SHIFT) - 1;
573 >        final ReentrantLock lock = this.workerLock;
574 >        lock.lock();
575 >        try {
576 >            ForkJoinWorkerThread[] ws = workers;
577 >            int nws = ws.length;
578 >            if (k < 0 || k >= nws || ws[k] != null) {
579 >                for (k = 0; k < nws && ws[k] != null; ++k)
580 >                    ;
581 >                if (k == nws)
582 >                    ws = Arrays.copyOf(ws, nws << 1);
583 >            }
584 >            ws[k] = w;
585 >            workers = ws; // volatile array write ensures slot visibility
586 >        } finally {
587 >            lock.unlock();
588 >        }
589 >        return k;
590 >    }
591 >
592 >    /**
593 >     * Nulls out record of worker in workers array
594 >     */
595 >    private void forgetWorker(ForkJoinWorkerThread w) {
596 >        int idx = w.poolIndex;
597 >        // Locking helps method recordWorker avoid unecessary expansion
598 >        final ReentrantLock lock = this.workerLock;
599 >        lock.lock();
600 >        try {
601 >            ForkJoinWorkerThread[] ws = workers;
602 >            if (idx >= 0 && idx < ws.length && ws[idx] == w) // verify
603 >                ws[idx] = null;
604 >        } finally {
605 >            lock.unlock();
606 >        }
607 >    }
608 >
609 >    // adding and removing workers
610 >
611 >    /**
612 >     * Tries to create and add new worker. Assumes that worker counts
613 >     * are already updated to accommodate the worker, so adjusts on
614 >     * failure.
615       *
616 <     * @param delta the number to add
616 >     * @return new worker or null if creation failed
617 >     */
618 >    private ForkJoinWorkerThread addWorker() {
619 >        ForkJoinWorkerThread w = null;
620 >        try {
621 >            w = factory.newThread(this);
622 >        } finally { // Adjust on either null or exceptional factory return
623 >            if (w == null) {
624 >                onWorkerCreationFailure();
625 >                return null;
626 >            }
627 >        }
628 >        w.start(recordWorker(w), ueh);
629 >        return w;
630 >    }
631 >
632 >    /**
633 >     * Adjusts counts upon failure to create worker
634       */
635 <    final void updateRunningCount(int delta) {
636 <        int s;
637 <        do {} while (!casWorkerCounts(s = workerCounts, s + delta));
635 >    private void onWorkerCreationFailure() {
636 >        for (;;) {
637 >            int wc = workerCounts;
638 >            if ((wc >>> TOTAL_COUNT_SHIFT) > 0 &&
639 >                UNSAFE.compareAndSwapInt(this, workerCountsOffset,
640 >                                         wc, wc - (ONE_RUNNING|ONE_TOTAL)))
641 >                break;
642 >        }
643 >        tryTerminate(false); // in case of failure during shutdown
644      }
645  
646      /**
647 <     * Adds delta (which may be negative) to both total and running
648 <     * count.  This must be called upon creation and termination of
649 <     * worker threads.
647 >     * Create enough total workers to establish target parallelism,
648 >     * giving up if terminating or addWorker fails
649 >     */
650 >    private void ensureEnoughTotalWorkers() {
651 >        int wc;
652 >        while (((wc = workerCounts) >>> TOTAL_COUNT_SHIFT) < parallelism &&
653 >               runState < TERMINATING) {
654 >            if ((UNSAFE.compareAndSwapInt(this, workerCountsOffset,
655 >                                          wc, wc + (ONE_RUNNING|ONE_TOTAL)) &&
656 >                 addWorker() == null))
657 >                break;
658 >        }
659 >    }
660 >
661 >    /**
662 >     * Final callback from terminating worker.  Removes record of
663 >     * worker from array, and adjusts counts. If pool is shutting
664 >     * down, tries to complete terminatation, else possibly replaces
665 >     * the worker.
666       *
667 <     * @param delta the number to add
667 >     * @param w the worker
668       */
669 <    private void updateWorkerCount(int delta) {
670 <        int d = delta + (delta << 16); // add to both lo and hi parts
671 <        int s;
672 <        do {} while (!casWorkerCounts(s = workerCounts, s + d));
669 >    final void workerTerminated(ForkJoinWorkerThread w) {
670 >        if (w.active) { // force inactive
671 >            w.active = false;
672 >            do {} while (!tryDecrementActiveCount());
673 >        }
674 >        forgetWorker(w);
675 >
676 >        // Decrement total count, and if was running, running count
677 >        // Spin (waiting for other updates) if either would be negative
678 >        int nr = w.isTrimmed() ? 0 : ONE_RUNNING;
679 >        int unit = ONE_TOTAL + nr;
680 >        for (;;) {
681 >            int wc = workerCounts;
682 >            int rc = wc & RUNNING_COUNT_MASK;
683 >            if (rc - nr < 0 || (wc >>> TOTAL_COUNT_SHIFT) == 0)
684 >                Thread.yield(); // back off if waiting for other updates
685 >            else if (UNSAFE.compareAndSwapInt(this, workerCountsOffset,
686 >                                              wc, wc - unit))
687 >                break;
688 >        }
689 >
690 >        accumulateStealCount(w); // collect final count
691 >        if (!tryTerminate(false))
692 >            ensureEnoughTotalWorkers();
693      }
694  
695 +    // Waiting for and signalling events
696 +
697      /**
698 <     * Lifecycle control. High word contains runState, low word
286 <     * contains the number of workers that are (probably) executing
287 <     * tasks. This value is atomically incremented before a worker
288 <     * gets a task to run, and decremented when worker has no tasks
289 <     * and cannot find any. These two fields are bundled together to
290 <     * support correct termination triggering.  Note: activeCount
291 <     * CAS'es cheat by assuming active count is in low word, so need
292 <     * to be modified if this changes
698 >     * Releases workers blocked on a count not equal to current count.
699       */
700 <    private volatile int runControl;
700 >    private void releaseWaiters() {
701 >        long top;
702 >        int id;
703 >        while ((id = (int)((top = eventWaiters) & WAITER_INDEX_MASK)) > 0 &&
704 >               (int)(top >>> EVENT_COUNT_SHIFT) != eventCount) {
705 >            ForkJoinWorkerThread[] ws = workers;
706 >            ForkJoinWorkerThread w;
707 >            if (ws.length >= id && (w = ws[id - 1]) != null &&
708 >                UNSAFE.compareAndSwapLong(this, eventWaitersOffset,
709 >                                          top, w.nextWaiter))
710 >                LockSupport.unpark(w);
711 >        }
712 >    }
713  
714 <    // RunState values. Order among values matters
715 <    private static final int RUNNING     = 0;
716 <    private static final int SHUTDOWN    = 1;
717 <    private static final int TERMINATING = 2;
718 <    private static final int TERMINATED  = 3;
714 >    /**
715 >     * Ensures eventCount on exit is different (mod 2^32) than on
716 >     * entry and wakes up all waiters
717 >     */
718 >    private void signalEvent() {
719 >        int c;
720 >        do {} while (!UNSAFE.compareAndSwapInt(this, eventCountOffset,
721 >                                               c = eventCount, c+1));
722 >        releaseWaiters();
723 >    }
724  
725 <    private static int runStateOf(int c)             { return c >>> 16; }
726 <    private static int activeCountOf(int c)          { return c & shortMask; }
727 <    private static int runControlFor(int r, int a)   { return (r << 16) + a; }
725 >    /**
726 >     * Advances eventCount and releases waiters until interference by
727 >     * other releasing threads is detected.
728 >     */
729 >    final void signalWork() {
730 >        // EventCount CAS failures are OK -- any change in count suffices.
731 >        int ec;
732 >        UNSAFE.compareAndSwapInt(this, eventCountOffset, ec=eventCount, ec+1);
733 >        outer:for (;;) {
734 >            long top = eventWaiters;
735 >            ec = eventCount;
736 >            for (;;) {
737 >                ForkJoinWorkerThread[] ws; ForkJoinWorkerThread w;
738 >                int id = (int)(top & WAITER_INDEX_MASK);
739 >                if (id <= 0 || (int)(top >>> EVENT_COUNT_SHIFT) == ec)
740 >                    return;
741 >                if ((ws = workers).length < id || (w = ws[id - 1]) == null ||
742 >                    !UNSAFE.compareAndSwapLong(this, eventWaitersOffset,
743 >                                               top, top = w.nextWaiter))
744 >                    continue outer;      // possibly stale; reread
745 >                LockSupport.unpark(w);
746 >                if (top != eventWaiters) // let someone else take over
747 >                    return;
748 >            }
749 >        }
750 >    }
751  
752      /**
753 <     * Tries incrementing active count; fails on contention.
754 <     * Called by workers before/during executing tasks.
753 >     * If worker is inactive, blocks until terminating or event count
754 >     * advances from last value held by worker; in any case helps
755 >     * release others.
756       *
757 <     * @return true on success
757 >     * @param w the calling worker thread
758       */
759 <    final boolean tryIncrementActiveCount() {
760 <        int c = runControl;
761 <        return casRunControl(c, c+1);
759 >    private void eventSync(ForkJoinWorkerThread w) {
760 >        if (!w.active) {
761 >            int prev = w.lastEventCount;
762 >            long nextTop = (((long)prev << EVENT_COUNT_SHIFT) |
763 >                            ((long)(w.poolIndex + 1)));
764 >            long top;
765 >            while ((runState < SHUTDOWN || !tryTerminate(false)) &&
766 >                   (((int)(top = eventWaiters) & WAITER_INDEX_MASK) == 0 ||
767 >                    (int)(top >>> EVENT_COUNT_SHIFT) == prev) &&
768 >                   eventCount == prev) {
769 >                if (UNSAFE.compareAndSwapLong(this, eventWaitersOffset,
770 >                                              w.nextWaiter = top, nextTop)) {
771 >                    accumulateStealCount(w); // transfer steals while idle
772 >                    Thread.interrupted();    // clear/ignore interrupt
773 >                    while (eventCount == prev)
774 >                        w.doPark();
775 >                    break;
776 >                }
777 >            }
778 >            w.lastEventCount = eventCount;
779 >        }
780 >        releaseWaiters();
781      }
782  
783      /**
784 <     * Tries decrementing active count; fails on contention.
785 <     * Possibly triggers termination on success.
786 <     * Called by workers when they can't find tasks.
784 >     * Callback from workers invoked upon each top-level action (i.e.,
785 >     * stealing a task or taking a submission and running
786 >     * it). Performs one or both of the following:
787       *
788 <     * @return true on success
788 >     * * If the worker cannot find work, updates its active status to
789 >     * inactive and updates activeCount unless there is contention, in
790 >     * which case it may try again (either in this or a subsequent
791 >     * call).  Additionally, awaits the next task event and/or helps
792 >     * wake up other releasable waiters.
793 >     *
794 >     * * If there are too many running threads, suspends this worker
795 >     * (first forcing inactivation if necessary).  If it is not
796 >     * resumed before a keepAlive elapses, the worker may be "trimmed"
797 >     * -- killed while suspended within suspendAsSpare. Otherwise,
798 >     * upon resume it rechecks to make sure that it is still needed.
799 >     *
800 >     * @param w the worker
801 >     * @param worked false if the worker scanned for work but didn't
802 >     * find any (in which case it may block waiting for work).
803       */
804 <    final boolean tryDecrementActiveCount() {
805 <        int c = runControl;
806 <        int nextc = c - 1;
807 <        if (!casRunControl(c, nextc))
804 >    final void preStep(ForkJoinWorkerThread w, boolean worked) {
805 >        boolean active = w.active;
806 >        boolean inactivate = !worked & active;
807 >        for (;;) {
808 >            if (inactivate) {
809 >                int rs = runState;
810 >                if (UNSAFE.compareAndSwapInt(this, runStateOffset,
811 >                                             rs, rs - ONE_ACTIVE))
812 >                    inactivate = active = w.active = false;
813 >            }
814 >            int wc = workerCounts;
815 >            if ((wc & RUNNING_COUNT_MASK) <= parallelism) {
816 >                if (!worked)
817 >                    eventSync(w);
818 >                return;
819 >            }
820 >            if (!(inactivate |= active) &&  // must inactivate to suspend
821 >                UNSAFE.compareAndSwapInt(this, workerCountsOffset,
822 >                                         wc, wc - ONE_RUNNING) &&
823 >                !w.suspendAsSpare())        // false if trimmed
824 >                return;
825 >        }
826 >    }
827 >
828 >    /**
829 >     * Tries to decrement running count, and if so, possibly creates
830 >     * or resumes compensating threads before blocking on task joinMe.
831 >     * This code is sprawled out with manual inlining to evade some
832 >     * JIT oddities.
833 >     *
834 >     * @param joinMe the task to join
835 >     * @return task status on exit
836 >     */
837 >    final int tryAwaitJoin(ForkJoinTask<?> joinMe) {
838 >        int cw = workerCounts; // read now to spoil CAS if counts change as ...
839 >        releaseWaiters();      // ... a byproduct of releaseWaiters
840 >        int stat = joinMe.status;
841 >        if (stat >= 0 && // inline variant of tryDecrementRunningCount
842 >            (cw & RUNNING_COUNT_MASK) > 0 &&
843 >            UNSAFE.compareAndSwapInt(this, workerCountsOffset,
844 >                                     cw, cw - ONE_RUNNING)) {
845 >            int pc = parallelism;
846 >            int scans = 0;  // to require confirming passes to add threads
847 >            outer: while ((workerCounts & RUNNING_COUNT_MASK) < pc) {
848 >                if ((stat = joinMe.status) < 0)
849 >                    break;
850 >                ForkJoinWorkerThread spare = null;
851 >                ForkJoinWorkerThread[] ws = workers;
852 >                int nws = ws.length;
853 >                for (int i = 0; i < nws; ++i) {
854 >                    ForkJoinWorkerThread w = ws[i];
855 >                    if (w != null && w.isSuspended()) {
856 >                        spare = w;
857 >                        break;
858 >                    }
859 >                }
860 >                if ((stat = joinMe.status) < 0) // recheck to narrow race
861 >                    break;
862 >                int wc = workerCounts;
863 >                int rc = wc & RUNNING_COUNT_MASK;
864 >                if (rc >= pc)
865 >                    break;
866 >                if (spare != null) {
867 >                    if (spare.tryUnsuspend()) {
868 >                        int c; // inline incrementRunningCount
869 >                        do {} while (!UNSAFE.compareAndSwapInt
870 >                                     (this, workerCountsOffset,
871 >                                      c = workerCounts, c + ONE_RUNNING));
872 >                        LockSupport.unpark(spare);
873 >                        break;
874 >                    }
875 >                    continue;
876 >                }
877 >                int tc = wc >>> TOTAL_COUNT_SHIFT;
878 >                int sc = tc - pc;
879 >                if (rc > 0) {
880 >                    int p = pc;
881 >                    int s = sc;
882 >                    while (s-- >= 0) { // try keeping 3/4 live
883 >                        if (rc > (p -= (p >>> 2) + 1))
884 >                            break outer;
885 >                    }
886 >                }
887 >                if (scans++ > sc && tc < MAX_THREADS &&
888 >                    UNSAFE.compareAndSwapInt(this, workerCountsOffset, wc,
889 >                                             wc + (ONE_RUNNING|ONE_TOTAL))) {
890 >                    addWorker();
891 >                    break;
892 >                }
893 >            }
894 >            if (stat >= 0)
895 >                stat = joinMe.internalAwaitDone();
896 >            int c; // inline incrementRunningCount
897 >            do {} while (!UNSAFE.compareAndSwapInt
898 >                         (this, workerCountsOffset,
899 >                          c = workerCounts, c + ONE_RUNNING));
900 >        }
901 >        return stat;
902 >    }
903 >
904 >    /**
905 >     * Same idea as (and mostly pasted from) tryAwaitJoin, but
906 >     * self-contained
907 >     */
908 >    final void awaitBlocker(ManagedBlocker blocker)
909 >        throws InterruptedException {
910 >        for (;;) {
911 >            if (blocker.isReleasable())
912 >                return;
913 >            int cw = workerCounts;
914 >            releaseWaiters();
915 >            if ((cw & RUNNING_COUNT_MASK) > 0 &&
916 >                UNSAFE.compareAndSwapInt(this, workerCountsOffset,
917 >                                         cw, cw - ONE_RUNNING))
918 >                break;
919 >        }
920 >        boolean done = false;
921 >        int pc = parallelism;
922 >        int scans = 0;
923 >        outer: while ((workerCounts & RUNNING_COUNT_MASK) < pc) {
924 >            if (done = blocker.isReleasable())
925 >                break;
926 >            ForkJoinWorkerThread spare = null;
927 >            ForkJoinWorkerThread[] ws = workers;
928 >            int nws = ws.length;
929 >            for (int i = 0; i < nws; ++i) {
930 >                ForkJoinWorkerThread w = ws[i];
931 >                if (w != null && w.isSuspended()) {
932 >                    spare = w;
933 >                    break;
934 >                }
935 >            }
936 >            if (done = blocker.isReleasable())
937 >                break;
938 >            int wc = workerCounts;
939 >            int rc = wc & RUNNING_COUNT_MASK;
940 >            if (rc >= pc)
941 >                break;
942 >            if (spare != null) {
943 >                if (spare.tryUnsuspend()) {
944 >                    int c;
945 >                    do {} while (!UNSAFE.compareAndSwapInt
946 >                                 (this, workerCountsOffset,
947 >                                  c = workerCounts, c + ONE_RUNNING));
948 >                    LockSupport.unpark(spare);
949 >                    break;
950 >                }
951 >                continue;
952 >            }
953 >            int tc = wc >>> TOTAL_COUNT_SHIFT;
954 >            int sc = tc - pc;
955 >            if (rc > 0) {
956 >                int p = pc;
957 >                int s = sc;
958 >                while (s-- >= 0) {
959 >                    if (rc > (p -= (p >>> 2) + 1))
960 >                        break outer;
961 >                }
962 >            }
963 >            if (scans++ > sc && tc < MAX_THREADS &&
964 >                UNSAFE.compareAndSwapInt(this, workerCountsOffset, wc,
965 >                                         wc + (ONE_RUNNING|ONE_TOTAL))) {
966 >                addWorker();
967 >                break;
968 >            }
969 >        }
970 >        try {
971 >            if (!done)
972 >                do {} while (!blocker.isReleasable() &&
973 >                             !blocker.block());
974 >        } finally {
975 >            int c;
976 >            do {} while (!UNSAFE.compareAndSwapInt
977 >                         (this, workerCountsOffset,
978 >                          c = workerCounts, c + ONE_RUNNING));
979 >        }
980 >    }  
981 >
982 >    /**
983 >     * Possibly initiates and/or completes termination.
984 >     *
985 >     * @param now if true, unconditionally terminate, else only
986 >     * if shutdown and empty queue and no active workers
987 >     * @return true if now terminating or terminated
988 >     */
989 >    private boolean tryTerminate(boolean now) {
990 >        if (now)
991 >            advanceRunLevel(SHUTDOWN); // ensure at least SHUTDOWN
992 >        else if (runState < SHUTDOWN ||
993 >                 !submissionQueue.isEmpty() ||
994 >                 (runState & ACTIVE_COUNT_MASK) != 0)
995              return false;
996 <        if (canTerminateOnShutdown(nextc))
997 <            terminateOnShutdown();
996 >
997 >        if (advanceRunLevel(TERMINATING))
998 >            startTerminating();
999 >
1000 >        // Finish now if all threads terminated; else in some subsequent call
1001 >        if ((workerCounts >>> TOTAL_COUNT_SHIFT) == 0) {
1002 >            advanceRunLevel(TERMINATED);
1003 >            termination.arrive();
1004 >        }
1005          return true;
1006      }
1007  
1008      /**
1009 <     * Returns {@code true} if argument represents zero active count
336 <     * and nonzero runstate, which is the triggering condition for
337 <     * terminating on shutdown.
1009 >     * Actions on transition to TERMINATING
1010       */
1011 <    private static boolean canTerminateOnShutdown(int c) {
1012 <        // i.e. least bit is nonzero runState bit
1013 <        return ((c & -c) >>> 16) != 0;
1011 >    private void startTerminating() {
1012 >        for (int i = 0; i < 2; ++i) { // twice to mop up newly created workers
1013 >            cancelSubmissions();
1014 >            shutdownWorkers();
1015 >            cancelWorkerTasks();
1016 >            signalEvent();
1017 >            interruptWorkers();
1018 >        }
1019      }
1020  
1021      /**
1022 <     * Transition run state to at least the given state. Return true
346 <     * if not already at least given state.
1022 >     * Clear out and cancel submissions, ignoring exceptions
1023       */
1024 <    private boolean transitionRunStateTo(int state) {
1025 <        for (;;) {
1026 <            int c = runControl;
1027 <            if (runStateOf(c) >= state)
1028 <                return false;
1029 <            if (casRunControl(c, runControlFor(state, activeCountOf(c))))
1030 <                return true;
1024 >    private void cancelSubmissions() {
1025 >        ForkJoinTask<?> task;
1026 >        while ((task = submissionQueue.poll()) != null) {
1027 >            try {
1028 >                task.cancel(false);
1029 >            } catch (Throwable ignore) {
1030 >            }
1031 >        }
1032 >    }
1033 >
1034 >    /**
1035 >     * Sets all worker run states to at least shutdown,
1036 >     * also resuming suspended workers
1037 >     */
1038 >    private void shutdownWorkers() {
1039 >        ForkJoinWorkerThread[] ws = workers;
1040 >        int nws = ws.length;
1041 >        for (int i = 0; i < nws; ++i) {
1042 >            ForkJoinWorkerThread w = ws[i];
1043 >            if (w != null)
1044 >                w.shutdown();
1045 >        }
1046 >    }
1047 >
1048 >    /**
1049 >     * Clears out and cancels all locally queued tasks
1050 >     */
1051 >    private void cancelWorkerTasks() {
1052 >        ForkJoinWorkerThread[] ws = workers;
1053 >        int nws = ws.length;
1054 >        for (int i = 0; i < nws; ++i) {
1055 >            ForkJoinWorkerThread w = ws[i];
1056 >            if (w != null)
1057 >                w.cancelTasks();
1058          }
1059      }
1060  
1061      /**
1062 <     * Controls whether to add spares to maintain parallelism
1062 >     * Unsticks all workers blocked on joins etc
1063       */
1064 <    private volatile boolean maintainsParallelism;
1064 >    private void interruptWorkers() {
1065 >        ForkJoinWorkerThread[] ws = workers;
1066 >        int nws = ws.length;
1067 >        for (int i = 0; i < nws; ++i) {
1068 >            ForkJoinWorkerThread w = ws[i];
1069 >            if (w != null && !w.isTerminated()) {
1070 >                try {
1071 >                    w.interrupt();
1072 >                } catch (SecurityException ignore) {
1073 >                }
1074 >            }
1075 >        }
1076 >    }
1077 >
1078 >    // misc support for ForkJoinWorkerThread
1079 >
1080 >    /**
1081 >     * Returns pool number
1082 >     */
1083 >    final int getPoolNumber() {
1084 >        return poolNumber;
1085 >    }
1086 >
1087 >    /**
1088 >     * Accumulates steal count from a worker, clearing
1089 >     * the worker's value
1090 >     */
1091 >    final void accumulateStealCount(ForkJoinWorkerThread w) {
1092 >        int sc = w.stealCount;
1093 >        if (sc != 0) {
1094 >            long c;
1095 >            w.stealCount = 0;
1096 >            do {} while (!UNSAFE.compareAndSwapLong(this, stealCountOffset,
1097 >                                                    c = stealCount, c + sc));
1098 >        }
1099 >    }
1100 >
1101 >    /**
1102 >     * Returns the approximate (non-atomic) number of idle threads per
1103 >     * active thread.
1104 >     */
1105 >    final int idlePerActive() {
1106 >        int pc = parallelism; // use targeted parallelism, not rc
1107 >        int ac = runState;    // no mask -- artifically boosts during shutdown
1108 >        // Use exact results for small values, saturate past 4
1109 >        return pc <= ac? 0 : pc >>> 1 <= ac? 1 : pc >>> 2 <= ac? 3 : pc >>> 3;
1110 >    }
1111 >
1112 >    // Public and protected methods
1113  
1114      // Constructors
1115  
1116      /**
1117       * Creates a {@code ForkJoinPool} with parallelism equal to {@link
1118 <     * java.lang.Runtime#availableProcessors}, and using the {@linkplain
1119 <     * #defaultForkJoinWorkerThreadFactory default thread factory}.
1118 >     * java.lang.Runtime#availableProcessors}, using the {@linkplain
1119 >     * #defaultForkJoinWorkerThreadFactory default thread factory},
1120 >     * no UncaughtExceptionHandler, and non-async LIFO processing mode.
1121       *
1122       * @throws SecurityException if a security manager exists and
1123       *         the caller is not permitted to modify threads
# Line 374 | Line 1126 | public class ForkJoinPool extends Abstra
1126       */
1127      public ForkJoinPool() {
1128          this(Runtime.getRuntime().availableProcessors(),
1129 <             defaultForkJoinWorkerThreadFactory);
1129 >             defaultForkJoinWorkerThreadFactory, null, false);
1130      }
1131  
1132      /**
1133       * Creates a {@code ForkJoinPool} with the indicated parallelism
1134 <     * level and using the {@linkplain
1135 <     * #defaultForkJoinWorkerThreadFactory default thread factory}.
1134 >     * level, the {@linkplain
1135 >     * #defaultForkJoinWorkerThreadFactory default thread factory},
1136 >     * no UncaughtExceptionHandler, and non-async LIFO processing mode.
1137       *
1138       * @param parallelism the parallelism level
1139       * @throws IllegalArgumentException if parallelism less than or
# Line 391 | Line 1144 | public class ForkJoinPool extends Abstra
1144       *         java.lang.RuntimePermission}{@code ("modifyThread")}
1145       */
1146      public ForkJoinPool(int parallelism) {
1147 <        this(parallelism, defaultForkJoinWorkerThreadFactory);
1147 >        this(parallelism, defaultForkJoinWorkerThreadFactory, null, false);
1148      }
1149  
1150      /**
1151 <     * Creates a {@code ForkJoinPool} with parallelism equal to {@link
399 <     * java.lang.Runtime#availableProcessors}, and using the given
400 <     * thread factory.
1151 >     * Creates a {@code ForkJoinPool} with the given parameters.
1152       *
1153 <     * @param factory the factory for creating new threads
1154 <     * @throws NullPointerException if factory is null
1155 <     * @throws SecurityException if a security manager exists and
1156 <     *         the caller is not permitted to modify threads
1157 <     *         because it does not hold {@link
1158 <     *         java.lang.RuntimePermission}{@code ("modifyThread")}
1159 <     */
1160 <    public ForkJoinPool(ForkJoinWorkerThreadFactory factory) {
1161 <        this(Runtime.getRuntime().availableProcessors(), factory);
1162 <    }
1163 <
1164 <    /**
1165 <     * Creates a {@code ForkJoinPool} with the given parallelism and
415 <     * thread factory.
416 <     *
417 <     * @param parallelism the parallelism level
418 <     * @param factory the factory for creating new threads
1153 >     * @param parallelism the parallelism level. For default value,
1154 >     * use {@link java.lang.Runtime#availableProcessors}.
1155 >     * @param factory the factory for creating new threads. For default value,
1156 >     * use {@link #defaultForkJoinWorkerThreadFactory}.
1157 >     * @param handler the handler for internal worker threads that
1158 >     * terminate due to unrecoverable errors encountered while executing
1159 >     * tasks. For default value, use <code>null</code>.
1160 >     * @param asyncMode if true,
1161 >     * establishes local first-in-first-out scheduling mode for forked
1162 >     * tasks that are never joined. This mode may be more appropriate
1163 >     * than default locally stack-based mode in applications in which
1164 >     * worker threads only process event-style asynchronous tasks.
1165 >     * For default value, use <code>false</code>.
1166       * @throws IllegalArgumentException if parallelism less than or
1167       *         equal to zero, or greater than implementation limit
1168 <     * @throws NullPointerException if factory is null
1168 >     * @throws NullPointerException if the factory is null
1169       * @throws SecurityException if a security manager exists and
1170       *         the caller is not permitted to modify threads
1171       *         because it does not hold {@link
1172       *         java.lang.RuntimePermission}{@code ("modifyThread")}
1173       */
1174 <    public ForkJoinPool(int parallelism, ForkJoinWorkerThreadFactory factory) {
1175 <        if (parallelism <= 0 || parallelism > MAX_THREADS)
1176 <            throw new IllegalArgumentException();
1174 >    public ForkJoinPool(int parallelism,
1175 >                        ForkJoinWorkerThreadFactory factory,
1176 >                        Thread.UncaughtExceptionHandler handler,
1177 >                        boolean asyncMode) {
1178 >        checkPermission();
1179          if (factory == null)
1180              throw new NullPointerException();
1181 <        checkPermission();
1182 <        this.factory = factory;
1181 >        if (parallelism <= 0 || parallelism > MAX_THREADS)
1182 >            throw new IllegalArgumentException();
1183          this.parallelism = parallelism;
1184 <        this.maxPoolSize = MAX_THREADS;
1185 <        this.maintainsParallelism = true;
1186 <        this.poolNumber = poolNumberGenerator.incrementAndGet();
1187 <        this.workerLock = new ReentrantLock();
1188 <        this.termination = workerLock.newCondition();
440 <        this.stealCount = new AtomicLong();
1184 >        this.factory = factory;
1185 >        this.ueh = handler;
1186 >        this.locallyFifo = asyncMode;
1187 >        int arraySize = initialArraySizeFor(parallelism);
1188 >        this.workers = new ForkJoinWorkerThread[arraySize];
1189          this.submissionQueue = new LinkedTransferQueue<ForkJoinTask<?>>();
1190 <        // worker array and workers are lazily constructed
1191 <    }
1192 <
445 <    /**
446 <     * Creates a new worker thread using factory.
447 <     *
448 <     * @param index the index to assign worker
449 <     * @return new worker, or null if factory failed
450 <     */
451 <    private ForkJoinWorkerThread createWorker(int index) {
452 <        Thread.UncaughtExceptionHandler h = ueh;
453 <        ForkJoinWorkerThread w = factory.newThread(this);
454 <        if (w != null) {
455 <            w.poolIndex = index;
456 <            w.setDaemon(true);
457 <            w.setAsyncMode(locallyFifo);
458 <            w.setName("ForkJoinPool-" + poolNumber + "-worker-" + index);
459 <            if (h != null)
460 <                w.setUncaughtExceptionHandler(h);
461 <        }
462 <        return w;
463 <    }
464 <
465 <    /**
466 <     * Returns a good size for worker array given pool size.
467 <     * Currently requires size to be a power of two.
468 <     */
469 <    private static int arraySizeFor(int poolSize) {
470 <        if (poolSize <= 1)
471 <            return 1;
472 <        // See Hackers Delight, sec 3.2
473 <        int c = poolSize >= MAX_THREADS ? MAX_THREADS : (poolSize - 1);
474 <        c |= c >>>  1;
475 <        c |= c >>>  2;
476 <        c |= c >>>  4;
477 <        c |= c >>>  8;
478 <        c |= c >>> 16;
479 <        return c + 1;
480 <    }
481 <
482 <    /**
483 <     * Creates or resizes array if necessary to hold newLength.
484 <     * Call only under exclusion.
485 <     *
486 <     * @return the array
487 <     */
488 <    private ForkJoinWorkerThread[] ensureWorkerArrayCapacity(int newLength) {
489 <        ForkJoinWorkerThread[] ws = workers;
490 <        if (ws == null)
491 <            return workers = new ForkJoinWorkerThread[arraySizeFor(newLength)];
492 <        else if (newLength > ws.length)
493 <            return workers = Arrays.copyOf(ws, arraySizeFor(newLength));
494 <        else
495 <            return ws;
496 <    }
497 <
498 <    /**
499 <     * Tries to shrink workers into smaller array after one or more terminate.
500 <     */
501 <    private void tryShrinkWorkerArray() {
502 <        ForkJoinWorkerThread[] ws = workers;
503 <        if (ws != null) {
504 <            int len = ws.length;
505 <            int last = len - 1;
506 <            while (last >= 0 && ws[last] == null)
507 <                --last;
508 <            int newLength = arraySizeFor(last+1);
509 <            if (newLength < len)
510 <                workers = Arrays.copyOf(ws, newLength);
511 <        }
512 <    }
513 <
514 <    /**
515 <     * Initializes workers if necessary.
516 <     */
517 <    final void ensureWorkerInitialization() {
518 <        ForkJoinWorkerThread[] ws = workers;
519 <        if (ws == null) {
520 <            final ReentrantLock lock = this.workerLock;
521 <            lock.lock();
522 <            try {
523 <                ws = workers;
524 <                if (ws == null) {
525 <                    int ps = parallelism;
526 <                    ws = ensureWorkerArrayCapacity(ps);
527 <                    for (int i = 0; i < ps; ++i) {
528 <                        ForkJoinWorkerThread w = createWorker(i);
529 <                        if (w != null) {
530 <                            ws[i] = w;
531 <                            w.start();
532 <                            updateWorkerCount(1);
533 <                        }
534 <                    }
535 <                }
536 <            } finally {
537 <                lock.unlock();
538 <            }
539 <        }
1190 >        this.workerLock = new ReentrantLock();
1191 >        this.termination = new Phaser(1);
1192 >        this.poolNumber = poolNumberGenerator.incrementAndGet();
1193      }
1194  
1195      /**
1196 <     * Worker creation and startup for threads added via setParallelism.
1196 >     * Returns initial power of two size for workers array.
1197 >     * @param pc the initial parallelism level
1198       */
1199 <    private void createAndStartAddedWorkers() {
1200 <        resumeAllSpares();  // Allow spares to convert to nonspare
1201 <        int ps = parallelism;
1202 <        ForkJoinWorkerThread[] ws = ensureWorkerArrayCapacity(ps);
1203 <        int len = ws.length;
1204 <        // Sweep through slots, to keep lowest indices most populated
1205 <        int k = 0;
1206 <        while (k < len) {
553 <            if (ws[k] != null) {
554 <                ++k;
555 <                continue;
556 <            }
557 <            int s = workerCounts;
558 <            int tc = totalCountOf(s);
559 <            int rc = runningCountOf(s);
560 <            if (rc >= ps || tc >= ps)
561 <                break;
562 <            if (casWorkerCounts (s, workerCountsFor(tc+1, rc+1))) {
563 <                ForkJoinWorkerThread w = createWorker(k);
564 <                if (w != null) {
565 <                    ws[k++] = w;
566 <                    w.start();
567 <                }
568 <                else {
569 <                    updateWorkerCount(-1); // back out on failed creation
570 <                    break;
571 <                }
572 <            }
573 <        }
1199 >    private static int initialArraySizeFor(int pc) {
1200 >        // See Hackers Delight, sec 3.2. We know MAX_THREADS < (1 >>> 16)
1201 >        int size = pc < MAX_THREADS ? pc + 1 : MAX_THREADS;
1202 >        size |= size >>> 1;
1203 >        size |= size >>> 2;
1204 >        size |= size >>> 4;
1205 >        size |= size >>> 8;
1206 >        return size + 1;
1207      }
1208  
1209      // Execution methods
# Line 581 | Line 1214 | public class ForkJoinPool extends Abstra
1214      private <T> void doSubmit(ForkJoinTask<T> task) {
1215          if (task == null)
1216              throw new NullPointerException();
1217 <        if (isShutdown())
1217 >        if (runState >= SHUTDOWN)
1218              throw new RejectedExecutionException();
1219 <        if (workers == null)
1220 <            ensureWorkerInitialization();
1221 <        submissionQueue.offer(task);
1222 <        signalIdleWorkers();
1219 >        // Convert submissions to current pool into forks
1220 >        Thread t = Thread.currentThread();
1221 >        ForkJoinWorkerThread w;
1222 >        if ((t instanceof ForkJoinWorkerThread) &&
1223 >            (w = (ForkJoinWorkerThread) t).pool == this)
1224 >            w.pushTask(task);
1225 >        else {
1226 >            submissionQueue.offer(task);
1227 >            signalEvent();
1228 >            ensureEnoughTotalWorkers();
1229 >        }
1230      }
1231  
1232      /**
1233       * Performs the given task, returning its result upon completion.
1234 +     * If the caller is already engaged in a fork/join computation in
1235 +     * the current pool, this method is equivalent in effect to
1236 +     * {@link ForkJoinTask#invoke}.
1237       *
1238       * @param task the task
1239       * @return the task's result
1240 <     * @throws NullPointerException if task is null
1241 <     * @throws RejectedExecutionException if pool is shut down
1240 >     * @throws NullPointerException if the task is null
1241 >     * @throws RejectedExecutionException if the task cannot be
1242 >     *         scheduled for execution
1243       */
1244      public <T> T invoke(ForkJoinTask<T> task) {
1245          doSubmit(task);
# Line 604 | Line 1248 | public class ForkJoinPool extends Abstra
1248  
1249      /**
1250       * Arranges for (asynchronous) execution of the given task.
1251 +     * If the caller is already engaged in a fork/join computation in
1252 +     * the current pool, this method is equivalent in effect to
1253 +     * {@link ForkJoinTask#fork}.
1254       *
1255       * @param task the task
1256 <     * @throws NullPointerException if task is null
1257 <     * @throws RejectedExecutionException if pool is shut down
1256 >     * @throws NullPointerException if the task is null
1257 >     * @throws RejectedExecutionException if the task cannot be
1258 >     *         scheduled for execution
1259       */
1260      public void execute(ForkJoinTask<?> task) {
1261          doSubmit(task);
# Line 615 | Line 1263 | public class ForkJoinPool extends Abstra
1263  
1264      // AbstractExecutorService methods
1265  
1266 +    /**
1267 +     * @throws NullPointerException if the task is null
1268 +     * @throws RejectedExecutionException if the task cannot be
1269 +     *         scheduled for execution
1270 +     */
1271      public void execute(Runnable task) {
1272          ForkJoinTask<?> job;
1273          if (task instanceof ForkJoinTask<?>) // avoid re-wrap
# Line 624 | Line 1277 | public class ForkJoinPool extends Abstra
1277          doSubmit(job);
1278      }
1279  
1280 +    /**
1281 +     * Submits a ForkJoinTask for execution.
1282 +     * If the caller is already engaged in a fork/join computation in
1283 +     * the current pool, this method is equivalent in effect to
1284 +     * {@link ForkJoinTask#fork}.
1285 +     *
1286 +     * @param task the task to submit
1287 +     * @return the task
1288 +     * @throws NullPointerException if the task is null
1289 +     * @throws RejectedExecutionException if the task cannot be
1290 +     *         scheduled for execution
1291 +     */
1292 +    public <T> ForkJoinTask<T> submit(ForkJoinTask<T> task) {
1293 +        doSubmit(task);
1294 +        return task;
1295 +    }
1296 +
1297 +    /**
1298 +     * @throws NullPointerException if the task is null
1299 +     * @throws RejectedExecutionException if the task cannot be
1300 +     *         scheduled for execution
1301 +     */
1302      public <T> ForkJoinTask<T> submit(Callable<T> task) {
1303          ForkJoinTask<T> job = ForkJoinTask.adapt(task);
1304          doSubmit(job);
1305          return job;
1306      }
1307  
1308 +    /**
1309 +     * @throws NullPointerException if the task is null
1310 +     * @throws RejectedExecutionException if the task cannot be
1311 +     *         scheduled for execution
1312 +     */
1313      public <T> ForkJoinTask<T> submit(Runnable task, T result) {
1314          ForkJoinTask<T> job = ForkJoinTask.adapt(task, result);
1315          doSubmit(job);
1316          return job;
1317      }
1318  
1319 +    /**
1320 +     * @throws NullPointerException if the task is null
1321 +     * @throws RejectedExecutionException if the task cannot be
1322 +     *         scheduled for execution
1323 +     */
1324      public ForkJoinTask<?> submit(Runnable task) {
1325          ForkJoinTask<?> job;
1326          if (task instanceof ForkJoinTask<?>) // avoid re-wrap
# Line 647 | Line 1332 | public class ForkJoinPool extends Abstra
1332      }
1333  
1334      /**
1335 <     * Submits a ForkJoinTask for execution.
1336 <     *
652 <     * @param task the task to submit
653 <     * @return the task
654 <     * @throws RejectedExecutionException if the task cannot be
655 <     *         scheduled for execution
656 <     * @throws NullPointerException if the task is null
1335 >     * @throws NullPointerException       {@inheritDoc}
1336 >     * @throws RejectedExecutionException {@inheritDoc}
1337       */
658    public <T> ForkJoinTask<T> submit(ForkJoinTask<T> task) {
659        doSubmit(task);
660        return task;
661    }
662
663
1338      public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) {
1339          ArrayList<ForkJoinTask<T>> forkJoinTasks =
1340              new ArrayList<ForkJoinTask<T>>(tasks.size());
# Line 669 | Line 1343 | public class ForkJoinPool extends Abstra
1343          invoke(new InvokeAll<T>(forkJoinTasks));
1344  
1345          @SuppressWarnings({"unchecked", "rawtypes"})
1346 <        List<Future<T>> futures = (List<Future<T>>) (List) forkJoinTasks;
1346 >            List<Future<T>> futures = (List<Future<T>>) (List) forkJoinTasks;
1347          return futures;
1348      }
1349  
# Line 683 | Line 1357 | public class ForkJoinPool extends Abstra
1357          private static final long serialVersionUID = -7914297376763021607L;
1358      }
1359  
686    // Configuration and status settings and queries
687
1360      /**
1361       * Returns the factory used for constructing new workers.
1362       *
# Line 701 | Line 1373 | public class ForkJoinPool extends Abstra
1373       * @return the handler, or {@code null} if none
1374       */
1375      public Thread.UncaughtExceptionHandler getUncaughtExceptionHandler() {
1376 <        Thread.UncaughtExceptionHandler h;
705 <        final ReentrantLock lock = this.workerLock;
706 <        lock.lock();
707 <        try {
708 <            h = ueh;
709 <        } finally {
710 <            lock.unlock();
711 <        }
712 <        return h;
713 <    }
714 <
715 <    /**
716 <     * Sets the handler for internal worker threads that terminate due
717 <     * to unrecoverable errors encountered while executing tasks.
718 <     * Unless set, the current default or ThreadGroup handler is used
719 <     * as handler.
720 <     *
721 <     * @param h the new handler
722 <     * @return the old handler, or {@code null} if none
723 <     * @throws SecurityException if a security manager exists and
724 <     *         the caller is not permitted to modify threads
725 <     *         because it does not hold {@link
726 <     *         java.lang.RuntimePermission}{@code ("modifyThread")}
727 <     */
728 <    public Thread.UncaughtExceptionHandler
729 <        setUncaughtExceptionHandler(Thread.UncaughtExceptionHandler h) {
730 <        checkPermission();
731 <        Thread.UncaughtExceptionHandler old = null;
732 <        final ReentrantLock lock = this.workerLock;
733 <        lock.lock();
734 <        try {
735 <            old = ueh;
736 <            ueh = h;
737 <            ForkJoinWorkerThread[] ws = workers;
738 <            if (ws != null) {
739 <                for (int i = 0; i < ws.length; ++i) {
740 <                    ForkJoinWorkerThread w = ws[i];
741 <                    if (w != null)
742 <                        w.setUncaughtExceptionHandler(h);
743 <                }
744 <            }
745 <        } finally {
746 <            lock.unlock();
747 <        }
748 <        return old;
749 <    }
750 <
751 <
752 <    /**
753 <     * Sets the target parallelism level of this pool.
754 <     *
755 <     * @param parallelism the target parallelism
756 <     * @throws IllegalArgumentException if parallelism less than or
757 <     * equal to zero or greater than maximum size bounds
758 <     * @throws SecurityException if a security manager exists and
759 <     *         the caller is not permitted to modify threads
760 <     *         because it does not hold {@link
761 <     *         java.lang.RuntimePermission}{@code ("modifyThread")}
762 <     */
763 <    public void setParallelism(int parallelism) {
764 <        checkPermission();
765 <        if (parallelism <= 0 || parallelism > maxPoolSize)
766 <            throw new IllegalArgumentException();
767 <        final ReentrantLock lock = this.workerLock;
768 <        lock.lock();
769 <        try {
770 <            if (isProcessingTasks()) {
771 <                int p = this.parallelism;
772 <                this.parallelism = parallelism;
773 <                if (parallelism > p)
774 <                    createAndStartAddedWorkers();
775 <                else
776 <                    trimSpares();
777 <            }
778 <        } finally {
779 <            lock.unlock();
780 <        }
781 <        signalIdleWorkers();
1376 >        return ueh;
1377      }
1378  
1379      /**
# Line 799 | Line 1394 | public class ForkJoinPool extends Abstra
1394       * @return the number of worker threads
1395       */
1396      public int getPoolSize() {
1397 <        return totalCountOf(workerCounts);
803 <    }
804 <
805 <    /**
806 <     * Returns the maximum number of threads allowed to exist in the
807 <     * pool. Unless set using {@link #setMaximumPoolSize}, the
808 <     * maximum is an implementation-defined value designed only to
809 <     * prevent runaway growth.
810 <     *
811 <     * @return the maximum
812 <     */
813 <    public int getMaximumPoolSize() {
814 <        return maxPoolSize;
815 <    }
816 <
817 <    /**
818 <     * Sets the maximum number of threads allowed to exist in the
819 <     * pool. The given value should normally be greater than or equal
820 <     * to the {@link #getParallelism parallelism} level. Setting this
821 <     * value has no effect on current pool size. It controls
822 <     * construction of new threads.
823 <     *
824 <     * @throws IllegalArgumentException if negative or greater than
825 <     * internal implementation limit
826 <     */
827 <    public void setMaximumPoolSize(int newMax) {
828 <        if (newMax < 0 || newMax > MAX_THREADS)
829 <            throw new IllegalArgumentException();
830 <        maxPoolSize = newMax;
831 <    }
832 <
833 <
834 <    /**
835 <     * Returns {@code true} if this pool dynamically maintains its
836 <     * target parallelism level. If false, new threads are added only
837 <     * to avoid possible starvation.  This setting is by default true.
838 <     *
839 <     * @return {@code true} if maintains parallelism
840 <     */
841 <    public boolean getMaintainsParallelism() {
842 <        return maintainsParallelism;
843 <    }
844 <
845 <    /**
846 <     * Sets whether this pool dynamically maintains its target
847 <     * parallelism level. If false, new threads are added only to
848 <     * avoid possible starvation.
849 <     *
850 <     * @param enable {@code true} to maintain parallelism
851 <     */
852 <    public void setMaintainsParallelism(boolean enable) {
853 <        maintainsParallelism = enable;
854 <    }
855 <
856 <    /**
857 <     * Establishes local first-in-first-out scheduling mode for forked
858 <     * tasks that are never joined. This mode may be more appropriate
859 <     * than default locally stack-based mode in applications in which
860 <     * worker threads only process asynchronous tasks.  This method is
861 <     * designed to be invoked only when the pool is quiescent, and
862 <     * typically only before any tasks are submitted. The effects of
863 <     * invocations at other times may be unpredictable.
864 <     *
865 <     * @param async if {@code true}, use locally FIFO scheduling
866 <     * @return the previous mode
867 <     * @see #getAsyncMode
868 <     */
869 <    public boolean setAsyncMode(boolean async) {
870 <        boolean oldMode = locallyFifo;
871 <        locallyFifo = async;
872 <        ForkJoinWorkerThread[] ws = workers;
873 <        if (ws != null) {
874 <            for (int i = 0; i < ws.length; ++i) {
875 <                ForkJoinWorkerThread t = ws[i];
876 <                if (t != null)
877 <                    t.setAsyncMode(async);
878 <            }
879 <        }
880 <        return oldMode;
1397 >        return workerCounts >>> TOTAL_COUNT_SHIFT;
1398      }
1399  
1400      /**
# Line 885 | Line 1402 | public class ForkJoinPool extends Abstra
1402       * scheduling mode for forked tasks that are never joined.
1403       *
1404       * @return {@code true} if this pool uses async mode
888     * @see #setAsyncMode
1405       */
1406      public boolean getAsyncMode() {
1407          return locallyFifo;
# Line 894 | Line 1410 | public class ForkJoinPool extends Abstra
1410      /**
1411       * Returns an estimate of the number of worker threads that are
1412       * not blocked waiting to join tasks or for other managed
1413 <     * synchronization.
1413 >     * synchronization. This method may overestimate the
1414 >     * number of running threads.
1415       *
1416       * @return the number of worker threads
1417       */
1418      public int getRunningThreadCount() {
1419 <        return runningCountOf(workerCounts);
1419 >        return workerCounts & RUNNING_COUNT_MASK;
1420      }
1421  
1422      /**
# Line 910 | Line 1427 | public class ForkJoinPool extends Abstra
1427       * @return the number of active threads
1428       */
1429      public int getActiveThreadCount() {
1430 <        return activeCountOf(runControl);
914 <    }
915 <
916 <    /**
917 <     * Returns an estimate of the number of threads that are currently
918 <     * idle waiting for tasks. This method may underestimate the
919 <     * number of idle threads.
920 <     *
921 <     * @return the number of idle threads
922 <     */
923 <    final int getIdleThreadCount() {
924 <        int c = runningCountOf(workerCounts) - activeCountOf(runControl);
925 <        return (c <= 0) ? 0 : c;
1430 >        return runState & ACTIVE_COUNT_MASK;
1431      }
1432  
1433      /**
# Line 937 | Line 1442 | public class ForkJoinPool extends Abstra
1442       * @return {@code true} if all threads are currently idle
1443       */
1444      public boolean isQuiescent() {
1445 <        return activeCountOf(runControl) == 0;
1445 >        return (runState & ACTIVE_COUNT_MASK) == 0;
1446      }
1447  
1448      /**
# Line 952 | Line 1457 | public class ForkJoinPool extends Abstra
1457       * @return the number of steals
1458       */
1459      public long getStealCount() {
1460 <        return stealCount.get();
956 <    }
957 <
958 <    /**
959 <     * Accumulates steal count from a worker.
960 <     * Call only when worker known to be idle.
961 <     */
962 <    private void updateStealCount(ForkJoinWorkerThread w) {
963 <        int sc = w.getAndClearStealCount();
964 <        if (sc != 0)
965 <            stealCount.addAndGet(sc);
1460 >        return stealCount;
1461      }
1462  
1463      /**
# Line 978 | Line 1473 | public class ForkJoinPool extends Abstra
1473      public long getQueuedTaskCount() {
1474          long count = 0;
1475          ForkJoinWorkerThread[] ws = workers;
1476 <        if (ws != null) {
1477 <            for (int i = 0; i < ws.length; ++i) {
1478 <                ForkJoinWorkerThread t = ws[i];
1479 <                if (t != null)
1480 <                    count += t.getQueueSize();
986 <            }
1476 >        int nws = ws.length;
1477 >        for (int i = 0; i < nws; ++i) {
1478 >            ForkJoinWorkerThread w = ws[i];
1479 >            if (w != null)
1480 >                count += w.getQueueSize();
1481          }
1482          return count;
1483      }
# Line 1040 | Line 1534 | public class ForkJoinPool extends Abstra
1534      protected int drainTasksTo(Collection<? super ForkJoinTask<?>> c) {
1535          int n = submissionQueue.drainTo(c);
1536          ForkJoinWorkerThread[] ws = workers;
1537 <        if (ws != null) {
1538 <            for (int i = 0; i < ws.length; ++i) {
1539 <                ForkJoinWorkerThread w = ws[i];
1540 <                if (w != null)
1541 <                    n += w.drainTasksTo(c);
1048 <            }
1537 >        int nws = ws.length;
1538 >        for (int i = 0; i < nws; ++i) {
1539 >            ForkJoinWorkerThread w = ws[i];
1540 >            if (w != null)
1541 >                n += w.drainTasksTo(c);
1542          }
1543          return n;
1544      }
1545  
1546      /**
1547 +     * Returns count of total parks by existing workers.
1548 +     * Used during development only since not meaningful to users.
1549 +     */
1550 +    private int collectParkCount() {
1551 +        int count = 0;
1552 +        ForkJoinWorkerThread[] ws = workers;
1553 +        int nws = ws.length;
1554 +        for (int i = 0; i < nws; ++i) {
1555 +            ForkJoinWorkerThread w = ws[i];
1556 +            if (w != null)
1557 +                count += w.parkCount;
1558 +        }
1559 +        return count;
1560 +    }
1561 +
1562 +    /**
1563       * Returns a string identifying this pool, as well as its state,
1564       * including indications of run state, parallelism level, and
1565       * worker and task counts.
# Line 1058 | Line 1567 | public class ForkJoinPool extends Abstra
1567       * @return a string identifying this pool, as well as its state
1568       */
1569      public String toString() {
1061        int ps = parallelism;
1062        int wc = workerCounts;
1063        int rc = runControl;
1570          long st = getStealCount();
1571          long qt = getQueuedTaskCount();
1572          long qs = getQueuedSubmissionCount();
1573 +        int wc = workerCounts;
1574 +        int tc = wc >>> TOTAL_COUNT_SHIFT;
1575 +        int rc = wc & RUNNING_COUNT_MASK;
1576 +        int pc = parallelism;
1577 +        int rs = runState;
1578 +        int ac = rs & ACTIVE_COUNT_MASK;
1579 +        //        int pk = collectParkCount();
1580          return super.toString() +
1581 <            "[" + runStateToString(runStateOf(rc)) +
1582 <            ", parallelism = " + ps +
1583 <            ", size = " + totalCountOf(wc) +
1584 <            ", active = " + activeCountOf(rc) +
1585 <            ", running = " + runningCountOf(wc) +
1581 >            "[" + runLevelToString(rs) +
1582 >            ", parallelism = " + pc +
1583 >            ", size = " + tc +
1584 >            ", active = " + ac +
1585 >            ", running = " + rc +
1586              ", steals = " + st +
1587              ", tasks = " + qt +
1588              ", submissions = " + qs +
1589 +            //            ", parks = " + pk +
1590              "]";
1591      }
1592  
1593 <    private static String runStateToString(int rs) {
1594 <        switch(rs) {
1595 <        case RUNNING: return "Running";
1596 <        case SHUTDOWN: return "Shutting down";
1597 <        case TERMINATING: return "Terminating";
1084 <        case TERMINATED: return "Terminated";
1085 <        default: throw new Error("Unknown run state");
1086 <        }
1593 >    private static String runLevelToString(int s) {
1594 >        return ((s & TERMINATED) != 0 ? "Terminated" :
1595 >                ((s & TERMINATING) != 0 ? "Terminating" :
1596 >                 ((s & SHUTDOWN) != 0 ? "Shutting down" :
1597 >                  "Running")));
1598      }
1599  
1089    // lifecycle control
1090
1600      /**
1601       * Initiates an orderly shutdown in which previously submitted
1602       * tasks are executed, but no new tasks will be accepted.
# Line 1102 | Line 1611 | public class ForkJoinPool extends Abstra
1611       */
1612      public void shutdown() {
1613          checkPermission();
1614 <        transitionRunStateTo(SHUTDOWN);
1615 <        if (canTerminateOnShutdown(runControl)) {
1107 <            if (workers == null) { // shutting down before workers created
1108 <                final ReentrantLock lock = this.workerLock;
1109 <                lock.lock();
1110 <                try {
1111 <                    if (workers == null) {
1112 <                        terminate();
1113 <                        transitionRunStateTo(TERMINATED);
1114 <                        termination.signalAll();
1115 <                    }
1116 <                } finally {
1117 <                    lock.unlock();
1118 <                }
1119 <            }
1120 <            terminateOnShutdown();
1121 <        }
1614 >        advanceRunLevel(SHUTDOWN);
1615 >        tryTerminate(false);
1616      }
1617  
1618      /**
# Line 1139 | Line 1633 | public class ForkJoinPool extends Abstra
1633       */
1634      public List<Runnable> shutdownNow() {
1635          checkPermission();
1636 <        terminate();
1636 >        tryTerminate(true);
1637          return Collections.emptyList();
1638      }
1639  
# Line 1149 | Line 1643 | public class ForkJoinPool extends Abstra
1643       * @return {@code true} if all tasks have completed following shut down
1644       */
1645      public boolean isTerminated() {
1646 <        return runStateOf(runControl) == TERMINATED;
1646 >        return runState >= TERMINATED;
1647      }
1648  
1649      /**
# Line 1163 | Line 1657 | public class ForkJoinPool extends Abstra
1657       * @return {@code true} if terminating but not yet terminated
1658       */
1659      public boolean isTerminating() {
1660 <        return runStateOf(runControl) == TERMINATING;
1660 >        return (runState & (TERMINATING|TERMINATED)) == TERMINATING;
1661      }
1662  
1663      /**
# Line 1172 | Line 1666 | public class ForkJoinPool extends Abstra
1666       * @return {@code true} if this pool has been shut down
1667       */
1668      public boolean isShutdown() {
1669 <        return runStateOf(runControl) >= SHUTDOWN;
1176 <    }
1177 <
1178 <    /**
1179 <     * Returns true if pool is not terminating or terminated.
1180 <     * Used internally to suppress execution when terminating.
1181 <     */
1182 <    final boolean isProcessingTasks() {
1183 <        return runStateOf(runControl) < TERMINATING;
1669 >        return runState >= SHUTDOWN;
1670      }
1671  
1672      /**
# Line 1196 | Line 1682 | public class ForkJoinPool extends Abstra
1682       */
1683      public boolean awaitTermination(long timeout, TimeUnit unit)
1684          throws InterruptedException {
1199        long nanos = unit.toNanos(timeout);
1200        final ReentrantLock lock = this.workerLock;
1201        lock.lock();
1202        try {
1203            for (;;) {
1204                if (isTerminated())
1205                    return true;
1206                if (nanos <= 0)
1207                    return false;
1208                nanos = termination.awaitNanos(nanos);
1209            }
1210        } finally {
1211            lock.unlock();
1212        }
1213    }
1214
1215    // Shutdown and termination support
1216
1217    /**
1218     * Callback from terminating worker. Nulls out the corresponding
1219     * workers slot, and if terminating, tries to terminate; else
1220     * tries to shrink workers array.
1221     *
1222     * @param w the worker
1223     */
1224    final void workerTerminated(ForkJoinWorkerThread w) {
1225        updateStealCount(w);
1226        updateWorkerCount(-1);
1227        final ReentrantLock lock = this.workerLock;
1228        lock.lock();
1685          try {
1686 <            ForkJoinWorkerThread[] ws = workers;
1687 <            if (ws != null) {
1232 <                int idx = w.poolIndex;
1233 <                if (idx >= 0 && idx < ws.length && ws[idx] == w)
1234 <                    ws[idx] = null;
1235 <                if (totalCountOf(workerCounts) == 0) {
1236 <                    terminate(); // no-op if already terminating
1237 <                    transitionRunStateTo(TERMINATED);
1238 <                    termination.signalAll();
1239 <                }
1240 <                else if (isProcessingTasks()) {
1241 <                    tryShrinkWorkerArray();
1242 <                    tryResumeSpare(true); // allow replacement
1243 <                }
1244 <            }
1245 <        } finally {
1246 <            lock.unlock();
1247 <        }
1248 <        signalIdleWorkers();
1249 <    }
1250 <
1251 <    /**
1252 <     * Initiates termination.
1253 <     */
1254 <    private void terminate() {
1255 <        if (transitionRunStateTo(TERMINATING)) {
1256 <            stopAllWorkers();
1257 <            resumeAllSpares();
1258 <            signalIdleWorkers();
1259 <            cancelQueuedSubmissions();
1260 <            cancelQueuedWorkerTasks();
1261 <            interruptUnterminatedWorkers();
1262 <            signalIdleWorkers(); // resignal after interrupt
1263 <        }
1264 <    }
1265 <
1266 <    /**
1267 <     * Possibly terminates when on shutdown state.
1268 <     */
1269 <    private void terminateOnShutdown() {
1270 <        if (!hasQueuedSubmissions() && canTerminateOnShutdown(runControl))
1271 <            terminate();
1272 <    }
1273 <
1274 <    /**
1275 <     * Clears out and cancels submissions.
1276 <     */
1277 <    private void cancelQueuedSubmissions() {
1278 <        ForkJoinTask<?> task;
1279 <        while ((task = pollSubmission()) != null)
1280 <            task.cancel(false);
1281 <    }
1282 <
1283 <    /**
1284 <     * Cleans out worker queues.
1285 <     */
1286 <    private void cancelQueuedWorkerTasks() {
1287 <        final ReentrantLock lock = this.workerLock;
1288 <        lock.lock();
1289 <        try {
1290 <            ForkJoinWorkerThread[] ws = workers;
1291 <            if (ws != null) {
1292 <                for (int i = 0; i < ws.length; ++i) {
1293 <                    ForkJoinWorkerThread t = ws[i];
1294 <                    if (t != null)
1295 <                        t.cancelTasks();
1296 <                }
1297 <            }
1298 <        } finally {
1299 <            lock.unlock();
1300 <        }
1301 <    }
1302 <
1303 <    /**
1304 <     * Sets each worker's status to terminating. Requires lock to avoid
1305 <     * conflicts with add/remove.
1306 <     */
1307 <    private void stopAllWorkers() {
1308 <        final ReentrantLock lock = this.workerLock;
1309 <        lock.lock();
1310 <        try {
1311 <            ForkJoinWorkerThread[] ws = workers;
1312 <            if (ws != null) {
1313 <                for (int i = 0; i < ws.length; ++i) {
1314 <                    ForkJoinWorkerThread t = ws[i];
1315 <                    if (t != null)
1316 <                        t.shutdownNow();
1317 <                }
1318 <            }
1319 <        } finally {
1320 <            lock.unlock();
1321 <        }
1322 <    }
1323 <
1324 <    /**
1325 <     * Interrupts all unterminated workers.  This is not required for
1326 <     * sake of internal control, but may help unstick user code during
1327 <     * shutdown.
1328 <     */
1329 <    private void interruptUnterminatedWorkers() {
1330 <        final ReentrantLock lock = this.workerLock;
1331 <        lock.lock();
1332 <        try {
1333 <            ForkJoinWorkerThread[] ws = workers;
1334 <            if (ws != null) {
1335 <                for (int i = 0; i < ws.length; ++i) {
1336 <                    ForkJoinWorkerThread t = ws[i];
1337 <                    if (t != null && !t.isTerminated()) {
1338 <                        try {
1339 <                            t.interrupt();
1340 <                        } catch (SecurityException ignore) {
1341 <                        }
1342 <                    }
1343 <                }
1344 <            }
1345 <        } finally {
1346 <            lock.unlock();
1347 <        }
1348 <    }
1349 <
1350 <
1351 <    /*
1352 <     * Nodes for event barrier to manage idle threads.  Queue nodes
1353 <     * are basic Treiber stack nodes, also used for spare stack.
1354 <     *
1355 <     * The event barrier has an event count and a wait queue (actually
1356 <     * a Treiber stack).  Workers are enabled to look for work when
1357 <     * the eventCount is incremented. If they fail to find work, they
1358 <     * may wait for next count. Upon release, threads help others wake
1359 <     * up.
1360 <     *
1361 <     * Synchronization events occur only in enough contexts to
1362 <     * maintain overall liveness:
1363 <     *
1364 <     *   - Submission of a new task to the pool
1365 <     *   - Resizes or other changes to the workers array
1366 <     *   - pool termination
1367 <     *   - A worker pushing a task on an empty queue
1368 <     *
1369 <     * The case of pushing a task occurs often enough, and is heavy
1370 <     * enough compared to simple stack pushes, to require special
1371 <     * handling: Method signalWork returns without advancing count if
1372 <     * the queue appears to be empty.  This would ordinarily result in
1373 <     * races causing some queued waiters not to be woken up. To avoid
1374 <     * this, the first worker enqueued in method sync (see
1375 <     * syncIsReleasable) rescans for tasks after being enqueued, and
1376 <     * helps signal if any are found. This works well because the
1377 <     * worker has nothing better to do, and so might as well help
1378 <     * alleviate the overhead and contention on the threads actually
1379 <     * doing work.  Also, since event counts increments on task
1380 <     * availability exist to maintain liveness (rather than to force
1381 <     * refreshes etc), it is OK for callers to exit early if
1382 <     * contending with another signaller.
1383 <     */
1384 <    static final class WaitQueueNode {
1385 <        WaitQueueNode next; // only written before enqueued
1386 <        volatile ForkJoinWorkerThread thread; // nulled to cancel wait
1387 <        final long count; // unused for spare stack
1388 <
1389 <        WaitQueueNode(long c, ForkJoinWorkerThread w) {
1390 <            count = c;
1391 <            thread = w;
1392 <        }
1393 <
1394 <        /**
1395 <         * Wakes up waiter, returning false if known to already
1396 <         */
1397 <        boolean signal() {
1398 <            ForkJoinWorkerThread t = thread;
1399 <            if (t == null)
1400 <                return false;
1401 <            thread = null;
1402 <            LockSupport.unpark(t);
1403 <            return true;
1404 <        }
1405 <
1406 <        /**
1407 <         * Awaits release on sync.
1408 <         */
1409 <        void awaitSyncRelease(ForkJoinPool p) {
1410 <            while (thread != null && !p.syncIsReleasable(this))
1411 <                LockSupport.park(this);
1412 <        }
1413 <
1414 <        /**
1415 <         * Awaits resumption as spare.
1416 <         */
1417 <        void awaitSpareRelease() {
1418 <            while (thread != null) {
1419 <                if (!Thread.interrupted())
1420 <                    LockSupport.park(this);
1421 <            }
1422 <        }
1423 <    }
1424 <
1425 <    /**
1426 <     * Ensures that no thread is waiting for count to advance from the
1427 <     * current value of eventCount read on entry to this method, by
1428 <     * releasing waiting threads if necessary.
1429 <     *
1430 <     * @return the count
1431 <     */
1432 <    final long ensureSync() {
1433 <        long c = eventCount;
1434 <        WaitQueueNode q;
1435 <        while ((q = syncStack) != null && q.count < c) {
1436 <            if (casBarrierStack(q, null)) {
1437 <                do {
1438 <                    q.signal();
1439 <                } while ((q = q.next) != null);
1440 <                break;
1441 <            }
1442 <        }
1443 <        return c;
1444 <    }
1445 <
1446 <    /**
1447 <     * Increments event count and releases waiting threads.
1448 <     */
1449 <    private void signalIdleWorkers() {
1450 <        long c;
1451 <        do {} while (!casEventCount(c = eventCount, c+1));
1452 <        ensureSync();
1453 <    }
1454 <
1455 <    /**
1456 <     * Signals threads waiting to poll a task. Because method sync
1457 <     * rechecks availability, it is OK to only proceed if queue
1458 <     * appears to be non-empty, and OK to skip under contention to
1459 <     * increment count (since some other thread succeeded).
1460 <     */
1461 <    final void signalWork() {
1462 <        long c;
1463 <        WaitQueueNode q;
1464 <        if (syncStack != null &&
1465 <            casEventCount(c = eventCount, c+1) &&
1466 <            (((q = syncStack) != null && q.count <= c) &&
1467 <             (!casBarrierStack(q, q.next) || !q.signal())))
1468 <            ensureSync();
1469 <    }
1470 <
1471 <    /**
1472 <     * Waits until event count advances from last value held by
1473 <     * caller, or if excess threads, caller is resumed as spare, or
1474 <     * caller or pool is terminating. Updates caller's event on exit.
1475 <     *
1476 <     * @param w the calling worker thread
1477 <     */
1478 <    final void sync(ForkJoinWorkerThread w) {
1479 <        updateStealCount(w); // Transfer w's count while it is idle
1480 <
1481 <        while (!w.isShutdown() && isProcessingTasks() && !suspendIfSpare(w)) {
1482 <            long prev = w.lastEventCount;
1483 <            WaitQueueNode node = null;
1484 <            WaitQueueNode h;
1485 <            while (eventCount == prev &&
1486 <                   ((h = syncStack) == null || h.count == prev)) {
1487 <                if (node == null)
1488 <                    node = new WaitQueueNode(prev, w);
1489 <                if (casBarrierStack(node.next = h, node)) {
1490 <                    node.awaitSyncRelease(this);
1491 <                    break;
1492 <                }
1493 <            }
1494 <            long ec = ensureSync();
1495 <            if (ec != prev) {
1496 <                w.lastEventCount = ec;
1497 <                break;
1498 <            }
1499 <        }
1500 <    }
1501 <
1502 <    /**
1503 <     * Returns {@code true} if worker waiting on sync can proceed:
1504 <     *  - on signal (thread == null)
1505 <     *  - on event count advance (winning race to notify vs signaller)
1506 <     *  - on interrupt
1507 <     *  - if the first queued node, we find work available
1508 <     * If node was not signalled and event count not advanced on exit,
1509 <     * then we also help advance event count.
1510 <     *
1511 <     * @return {@code true} if node can be released
1512 <     */
1513 <    final boolean syncIsReleasable(WaitQueueNode node) {
1514 <        long prev = node.count;
1515 <        if (!Thread.interrupted() && node.thread != null &&
1516 <            (node.next != null ||
1517 <             !ForkJoinWorkerThread.hasQueuedTasks(workers)) &&
1518 <            eventCount == prev)
1519 <            return false;
1520 <        if (node.thread != null) {
1521 <            node.thread = null;
1522 <            long ec = eventCount;
1523 <            if (prev <= ec) // help signal
1524 <                casEventCount(ec, ec+1);
1525 <        }
1526 <        return true;
1527 <    }
1528 <
1529 <    /**
1530 <     * Returns {@code true} if a new sync event occurred since last
1531 <     * call to sync or this method, if so, updating caller's count.
1532 <     */
1533 <    final boolean hasNewSyncEvent(ForkJoinWorkerThread w) {
1534 <        long lc = w.lastEventCount;
1535 <        long ec = ensureSync();
1536 <        if (ec == lc)
1686 >            return termination.awaitAdvanceInterruptibly(0, timeout, unit) > 0;
1687 >        } catch(TimeoutException ex) {
1688              return false;
1538        w.lastEventCount = ec;
1539        return true;
1540    }
1541
1542    //  Parallelism maintenance
1543
1544    /**
1545     * Decrements running count; if too low, adds spare.
1546     *
1547     * Conceptually, all we need to do here is add or resume a
1548     * spare thread when one is about to block (and remove or
1549     * suspend it later when unblocked -- see suspendIfSpare).
1550     * However, implementing this idea requires coping with
1551     * several problems: we have imperfect information about the
1552     * states of threads. Some count updates can and usually do
1553     * lag run state changes, despite arrangements to keep them
1554     * accurate (for example, when possible, updating counts
1555     * before signalling or resuming), especially when running on
1556     * dynamic JVMs that don't optimize the infrequent paths that
1557     * update counts. Generating too many threads can make these
1558     * problems become worse, because excess threads are more
1559     * likely to be context-switched with others, slowing them all
1560     * down, especially if there is no work available, so all are
1561     * busy scanning or idling.  Also, excess spare threads can
1562     * only be suspended or removed when they are idle, not
1563     * immediately when they aren't needed. So adding threads will
1564     * raise parallelism level for longer than necessary.  Also,
1565     * FJ applications often encounter highly transient peaks when
1566     * many threads are blocked joining, but for less time than it
1567     * takes to create or resume spares.
1568     *
1569     * @param joinMe if non-null, return early if done
1570     * @param maintainParallelism if true, try to stay within
1571     * target counts, else create only to avoid starvation
1572     * @return true if joinMe known to be done
1573     */
1574    final boolean preJoin(ForkJoinTask<?> joinMe,
1575                          boolean maintainParallelism) {
1576        maintainParallelism &= maintainsParallelism; // overrride
1577        boolean dec = false;  // true when running count decremented
1578        while (spareStack == null || !tryResumeSpare(dec)) {
1579            int counts = workerCounts;
1580            if (dec || (dec = casWorkerCounts(counts, --counts))) {
1581                if (!needSpare(counts, maintainParallelism))
1582                    break;
1583                if (joinMe.status < 0)
1584                    return true;
1585                if (tryAddSpare(counts))
1586                    break;
1587            }
1588        }
1589        return false;
1590    }
1591
1592    /**
1593     * Same idea as preJoin
1594     */
1595    final boolean preBlock(ManagedBlocker blocker,
1596                           boolean maintainParallelism) {
1597        maintainParallelism &= maintainsParallelism;
1598        boolean dec = false;
1599        while (spareStack == null || !tryResumeSpare(dec)) {
1600            int counts = workerCounts;
1601            if (dec || (dec = casWorkerCounts(counts, --counts))) {
1602                if (!needSpare(counts, maintainParallelism))
1603                    break;
1604                if (blocker.isReleasable())
1605                    return true;
1606                if (tryAddSpare(counts))
1607                    break;
1608            }
1609        }
1610        return false;
1611    }
1612
1613    /**
1614     * Returns {@code true} if a spare thread appears to be needed.
1615     * If maintaining parallelism, returns true when the deficit in
1616     * running threads is more than the surplus of total threads, and
1617     * there is apparently some work to do.  This self-limiting rule
1618     * means that the more threads that have already been added, the
1619     * less parallelism we will tolerate before adding another.
1620     *
1621     * @param counts current worker counts
1622     * @param maintainParallelism try to maintain parallelism
1623     */
1624    private boolean needSpare(int counts, boolean maintainParallelism) {
1625        int ps = parallelism;
1626        int rc = runningCountOf(counts);
1627        int tc = totalCountOf(counts);
1628        int runningDeficit = ps - rc;
1629        int totalSurplus = tc - ps;
1630        return (tc < maxPoolSize &&
1631                (rc == 0 || totalSurplus < 0 ||
1632                 (maintainParallelism &&
1633                  runningDeficit > totalSurplus &&
1634                  ForkJoinWorkerThread.hasQueuedTasks(workers))));
1635    }
1636
1637    /**
1638     * Adds a spare worker if lock available and no more than the
1639     * expected numbers of threads exist.
1640     *
1641     * @return true if successful
1642     */
1643    private boolean tryAddSpare(int expectedCounts) {
1644        final ReentrantLock lock = this.workerLock;
1645        int expectedRunning = runningCountOf(expectedCounts);
1646        int expectedTotal = totalCountOf(expectedCounts);
1647        boolean success = false;
1648        boolean locked = false;
1649        // confirm counts while locking; CAS after obtaining lock
1650        try {
1651            for (;;) {
1652                int s = workerCounts;
1653                int tc = totalCountOf(s);
1654                int rc = runningCountOf(s);
1655                if (rc > expectedRunning || tc > expectedTotal)
1656                    break;
1657                if (!locked && !(locked = lock.tryLock()))
1658                    break;
1659                if (casWorkerCounts(s, workerCountsFor(tc+1, rc+1))) {
1660                    createAndStartSpare(tc);
1661                    success = true;
1662                    break;
1663                }
1664            }
1665        } finally {
1666            if (locked)
1667                lock.unlock();
1668        }
1669        return success;
1670    }
1671
1672    /**
1673     * Adds the kth spare worker. On entry, pool counts are already
1674     * adjusted to reflect addition.
1675     */
1676    private void createAndStartSpare(int k) {
1677        ForkJoinWorkerThread w = null;
1678        ForkJoinWorkerThread[] ws = ensureWorkerArrayCapacity(k + 1);
1679        int len = ws.length;
1680        // Probably, we can place at slot k. If not, find empty slot
1681        if (k < len && ws[k] != null) {
1682            for (k = 0; k < len && ws[k] != null; ++k)
1683                ;
1684        }
1685        if (k < len && isProcessingTasks() && (w = createWorker(k)) != null) {
1686            ws[k] = w;
1687            w.start();
1688        }
1689        else
1690            updateWorkerCount(-1); // adjust on failure
1691        signalIdleWorkers();
1692    }
1693
1694    /**
1695     * Suspends calling thread w if there are excess threads.  Called
1696     * only from sync.  Spares are enqueued in a Treiber stack using
1697     * the same WaitQueueNodes as barriers.  They are resumed mainly
1698     * in preJoin, but are also woken on pool events that require all
1699     * threads to check run state.
1700     *
1701     * @param w the caller
1702     */
1703    private boolean suspendIfSpare(ForkJoinWorkerThread w) {
1704        WaitQueueNode node = null;
1705        int s;
1706        while (parallelism < runningCountOf(s = workerCounts)) {
1707            if (node == null)
1708                node = new WaitQueueNode(0, w);
1709            if (casWorkerCounts(s, s-1)) { // representation-dependent
1710                // push onto stack
1711                do {} while (!casSpareStack(node.next = spareStack, node));
1712                // block until released by resumeSpare
1713                node.awaitSpareRelease();
1714                return true;
1715            }
1716        }
1717        return false;
1718    }
1719
1720    /**
1721     * Tries to pop and resume a spare thread.
1722     *
1723     * @param updateCount if true, increment running count on success
1724     * @return true if successful
1725     */
1726    private boolean tryResumeSpare(boolean updateCount) {
1727        WaitQueueNode q;
1728        while ((q = spareStack) != null) {
1729            if (casSpareStack(q, q.next)) {
1730                if (updateCount)
1731                    updateRunningCount(1);
1732                q.signal();
1733                return true;
1734            }
1735        }
1736        return false;
1737    }
1738
1739    /**
1740     * Pops and resumes all spare threads. Same idea as ensureSync.
1741     *
1742     * @return true if any spares released
1743     */
1744    private boolean resumeAllSpares() {
1745        WaitQueueNode q;
1746        while ( (q = spareStack) != null) {
1747            if (casSpareStack(q, null)) {
1748                do {
1749                    updateRunningCount(1);
1750                    q.signal();
1751                } while ((q = q.next) != null);
1752                return true;
1753            }
1754        }
1755        return false;
1756    }
1757
1758    /**
1759     * Pops and shuts down excessive spare threads. Call only while
1760     * holding lock. This is not guaranteed to eliminate all excess
1761     * threads, only those suspended as spares, which are the ones
1762     * unlikely to be needed in the future.
1763     */
1764    private void trimSpares() {
1765        int surplus = totalCountOf(workerCounts) - parallelism;
1766        WaitQueueNode q;
1767        while (surplus > 0 && (q = spareStack) != null) {
1768            if (casSpareStack(q, null)) {
1769                do {
1770                    updateRunningCount(1);
1771                    ForkJoinWorkerThread w = q.thread;
1772                    if (w != null && surplus > 0 &&
1773                        runningCountOf(workerCounts) > 0 && w.shutdown())
1774                        --surplus;
1775                    q.signal();
1776                } while ((q = q.next) != null);
1777            }
1689          }
1690      }
1691  
# Line 1827 | Line 1738 | public class ForkJoinPool extends Abstra
1738       * Blocks in accord with the given blocker.  If the current thread
1739       * is a {@link ForkJoinWorkerThread}, this method possibly
1740       * arranges for a spare thread to be activated if necessary to
1741 <     * ensure parallelism while the current thread is blocked.
1831 <     *
1832 <     * <p>If {@code maintainParallelism} is {@code true} and the pool
1833 <     * supports it ({@link #getMaintainsParallelism}), this method
1834 <     * attempts to maintain the pool's nominal parallelism. Otherwise
1835 <     * it activates a thread only if necessary to avoid complete
1836 <     * starvation. This option may be preferable when blockages use
1837 <     * timeouts, or are almost always brief.
1741 >     * ensure sufficient parallelism while the current thread is blocked.
1742       *
1743       * <p>If the caller is not a {@link ForkJoinTask}, this method is
1744       * behaviorally equivalent to
# Line 1848 | Line 1752 | public class ForkJoinPool extends Abstra
1752       * first be expanded to ensure parallelism, and later adjusted.
1753       *
1754       * @param blocker the blocker
1851     * @param maintainParallelism if {@code true} and supported by
1852     * this pool, attempt to maintain the pool's nominal parallelism;
1853     * otherwise activate a thread only if necessary to avoid
1854     * complete starvation.
1755       * @throws InterruptedException if blocker.block did so
1756       */
1757 <    public static void managedBlock(ManagedBlocker blocker,
1858 <                                    boolean maintainParallelism)
1757 >    public static void managedBlock(ManagedBlocker blocker)
1758          throws InterruptedException {
1759          Thread t = Thread.currentThread();
1760 <        ForkJoinPool pool = ((t instanceof ForkJoinWorkerThread) ?
1761 <                             ((ForkJoinWorkerThread) t).pool : null);
1762 <        if (!blocker.isReleasable()) {
1763 <            try {
1865 <                if (pool == null ||
1866 <                    !pool.preBlock(blocker, maintainParallelism))
1867 <                    awaitBlocker(blocker);
1868 <            } finally {
1869 <                if (pool != null)
1870 <                    pool.updateRunningCount(1);
1871 <            }
1760 >        if (t instanceof ForkJoinWorkerThread)
1761 >            ((ForkJoinWorkerThread) t).pool.awaitBlocker(blocker);
1762 >        else {
1763 >            do {} while (!blocker.isReleasable() && !blocker.block());
1764          }
1765      }
1766  
1875    private static void awaitBlocker(ManagedBlocker blocker)
1876        throws InterruptedException {
1877        do {} while (!blocker.isReleasable() && !blocker.block());
1878    }
1879
1767      // AbstractExecutorService overrides.  These rely on undocumented
1768      // fact that ForkJoinTask.adapt returns ForkJoinTasks that also
1769      // implement RunnableFuture.
# Line 1892 | Line 1779 | public class ForkJoinPool extends Abstra
1779      // Unsafe mechanics
1780  
1781      private static final sun.misc.Unsafe UNSAFE = getUnsafe();
1895    private static final long eventCountOffset =
1896        objectFieldOffset("eventCount", ForkJoinPool.class);
1782      private static final long workerCountsOffset =
1783          objectFieldOffset("workerCounts", ForkJoinPool.class);
1784 <    private static final long runControlOffset =
1785 <        objectFieldOffset("runControl", ForkJoinPool.class);
1786 <    private static final long syncStackOffset =
1787 <        objectFieldOffset("syncStack",ForkJoinPool.class);
1788 <    private static final long spareStackOffset =
1789 <        objectFieldOffset("spareStack", ForkJoinPool.class);
1790 <
1791 <    private boolean casEventCount(long cmp, long val) {
1907 <        return UNSAFE.compareAndSwapLong(this, eventCountOffset, cmp, val);
1908 <    }
1909 <    private boolean casWorkerCounts(int cmp, int val) {
1910 <        return UNSAFE.compareAndSwapInt(this, workerCountsOffset, cmp, val);
1911 <    }
1912 <    private boolean casRunControl(int cmp, int val) {
1913 <        return UNSAFE.compareAndSwapInt(this, runControlOffset, cmp, val);
1914 <    }
1915 <    private boolean casSpareStack(WaitQueueNode cmp, WaitQueueNode val) {
1916 <        return UNSAFE.compareAndSwapObject(this, spareStackOffset, cmp, val);
1917 <    }
1918 <    private boolean casBarrierStack(WaitQueueNode cmp, WaitQueueNode val) {
1919 <        return UNSAFE.compareAndSwapObject(this, syncStackOffset, cmp, val);
1920 <    }
1784 >    private static final long runStateOffset =
1785 >        objectFieldOffset("runState", ForkJoinPool.class);
1786 >    private static final long eventCountOffset =
1787 >        objectFieldOffset("eventCount", ForkJoinPool.class);
1788 >    private static final long eventWaitersOffset =
1789 >        objectFieldOffset("eventWaiters",ForkJoinPool.class);
1790 >    private static final long stealCountOffset =
1791 >        objectFieldOffset("stealCount",ForkJoinPool.class);
1792  
1793      private static long objectFieldOffset(String field, Class<?> klazz) {
1794          try {

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines