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.46 by dl, Tue Aug 4 14:19:00 2009 UTC vs.
Revision 1.56 by dl, Thu May 27 16:46:48 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.  
25 > * monitoring operations.
26   *
27   * <p>A {@code ForkJoinPool} differs from other kinds of {@link
28   * ExecutorService} mainly by virtue of employing
# Line 53 | Line 52 | import java.util.concurrent.atomic.Atomi
52   * ({@link #setParallelism}). The total number of threads may be
53   * limited using method {@link #setMaximumPoolSize}, in which case it
54   * may become possible for the activities of a pool to stall due to
55 < * the lack of available threads to process new tasks.
55 > * the lack of available threads to process new tasks. When the pool
56 > * is executing tasks, these and other configuration setting methods
57 > * may only gradually affect actual pool sizes. It is normally best
58 > * practice to invoke these methods only when the pool is known to be
59 > * quiescent.
60   *
61   * <p>In addition to execution and lifecycle control methods, this
62   * class provides status check methods (for example
# Line 82 | Line 85 | import java.util.concurrent.atomic.Atomi
85   *
86   * <p><b>Implementation notes</b>: This implementation restricts the
87   * maximum number of running threads to 32767. Attempts to create
88 < * pools with greater than the maximum result in
88 > * pools with greater than the maximum number result in
89   * {@code IllegalArgumentException}.
90   *
91 + * <p>This implementation rejects submitted tasks (that is, by throwing
92 + * {@link RejectedExecutionException}) only when the pool is shut down.
93 + *
94   * @since 1.7
95   * @author Doug Lea
96   */
97   public class ForkJoinPool extends AbstractExecutorService {
98  
99      /*
100 <     * See the extended comments interspersed below for design,
101 <     * rationale, and walkthroughs.
100 >     * Implementation Overview
101 >     *
102 >     * This class provides the central bookkeeping and control for a
103 >     * set of worker threads: Submissions from non-FJ threads enter
104 >     * into a submission queue. Workers take these tasks and typically
105 >     * split them into subtasks that may be stolen by other workers.
106 >     * The main work-stealing mechanics implemented in class
107 >     * ForkJoinWorkerThread give first priority to processing tasks
108 >     * from their own queues (LIFO or FIFO, depending on mode), then
109 >     * to randomized FIFO steals of tasks in other worker queues, and
110 >     * lastly to new submissions. These mechanics do not consider
111 >     * affinities, loads, cache localities, etc, so rarely provide the
112 >     * best possible performance on a given machine, but portably
113 >     * provide good throughput by averaging over these factors.
114 >     * (Further, even if we did try to use such information, we do not
115 >     * usually have a basis for exploiting it. For example, some sets
116 >     * of tasks profit from cache affinities, but others are harmed by
117 >     * cache pollution effects.)
118 >     *
119 >     * The main throughput advantages of work-stealing stem from
120 >     * decentralized control -- workers mostly steal tasks from each
121 >     * other. We do not want to negate this by creating bottlenecks
122 >     * implementing the management responsibilities of this class. So
123 >     * we use a collection of techniques that avoid, reduce, or cope
124 >     * well with contention. These entail several instances of
125 >     * bit-packing into CASable fields to maintain only the minimally
126 >     * required atomicity. To enable such packing, we restrict maximum
127 >     * parallelism to (1<<15)-1 (enabling twice this to fit into a 16
128 >     * bit field), which is far in excess of normal operating range.
129 >     * Even though updates to some of these bookkeeping fields do
130 >     * sometimes contend with each other, they don't normally
131 >     * cache-contend with updates to others enough to warrant memory
132 >     * padding or isolation. So they are all held as fields of
133 >     * ForkJoinPool objects.  The main capabilities are as follows:
134 >     *
135 >     * 1. Creating and removing workers. Workers are recorded in the
136 >     * "workers" array. This is an array as opposed to some other data
137 >     * structure to support index-based random steals by workers.
138 >     * Updates to the array recording new workers and unrecording
139 >     * terminated ones are protected from each other by a lock
140 >     * (workerLock) but the array is otherwise concurrently readable,
141 >     * and accessed directly by workers. To simplify index-based
142 >     * operations, the array size is always a power of two, and all
143 >     * readers must tolerate null slots. Currently, all worker thread
144 >     * creation is on-demand, triggered by task submissions,
145 >     * replacement of terminated workers, and/or compensation for
146 >     * blocked workers. However, all other support code is set up to
147 >     * work with other policies.
148 >     *
149 >     * 2. Bookkeeping for dynamically adding and removing workers. We
150 >     * maintain a given level of parallelism (or, if
151 >     * maintainsParallelism is false, at least avoid starvation). When
152 >     * some workers are known to be blocked (on joins or via
153 >     * ManagedBlocker), we may create or resume others to take their
154 >     * place until they unblock (see below). Implementing this
155 >     * requires counts of the number of "running" threads (i.e., those
156 >     * that are neither blocked nor artifically suspended) as well as
157 >     * the total number.  These two values are packed into one field,
158 >     * "workerCounts" because we need accurate snapshots when deciding
159 >     * to create, resume or suspend.  To support these decisions,
160 >     * updates to spare counts must be prospective (not
161 >     * retrospective).  For example, the running count is decremented
162 >     * before blocking by a thread about to block as a spare, but
163 >     * incremented by the thread about to unblock it. Updates upon
164 >     * resumption ofr threads blocking in awaitJoin or awaitBlocker
165 >     * cannot usually be prospective, so the running count is in
166 >     * general an upper bound of the number of productively running
167 >     * threads Updates to the workerCounts field sometimes transiently
168 >     * encounter a fair amount of contention when join dependencies
169 >     * are such that many threads block or unblock at about the same
170 >     * time. We alleviate this by sometimes bundling updates (for
171 >     * example blocking one thread on join and resuming a spare cancel
172 >     * each other out), and in most other cases performing an
173 >     * alternative action like releasing waiters or locating spares.
174 >     *
175 >     * 3. Maintaining global run state. The run state of the pool
176 >     * consists of a runLevel (SHUTDOWN, TERMINATING, etc) similar to
177 >     * those in other Executor implementations, as well as a count of
178 >     * "active" workers -- those that are, or soon will be, or
179 >     * recently were executing tasks. The runLevel and active count
180 >     * are packed together in order to correctly trigger shutdown and
181 >     * termination. Without care, active counts can be subject to very
182 >     * high contention.  We substantially reduce this contention by
183 >     * relaxing update rules.  A worker must claim active status
184 >     * prospectively, by activating if it sees that a submitted or
185 >     * stealable task exists (it may find after activating that the
186 >     * task no longer exists). It stays active while processing this
187 >     * task (if it exists) and any other local subtasks it produces,
188 >     * until it cannot find any other tasks. It then tries
189 >     * inactivating (see method preStep), but upon update contention
190 >     * instead scans for more tasks, later retrying inactivation if it
191 >     * doesn't find any.
192 >     *
193 >     * 4. Managing idle workers waiting for tasks. We cannot let
194 >     * workers spin indefinitely scanning for tasks when none are
195 >     * available. On the other hand, we must quickly prod them into
196 >     * action when new tasks are submitted or generated.  We
197 >     * park/unpark these idle workers using an event-count scheme.
198 >     * Field eventCount is incremented upon events that may enable
199 >     * workers that previously could not find a task to now find one:
200 >     * Submission of a new task to the pool, or another worker pushing
201 >     * a task onto a previously empty queue.  (We also use this
202 >     * mechanism for termination and reconfiguration actions that
203 >     * require wakeups of idle workers).  Each worker maintains its
204 >     * last known event count, and blocks when a scan for work did not
205 >     * find a task AND its lastEventCount matches the current
206 >     * eventCount. Waiting idle workers are recorded in a variant of
207 >     * Treiber stack headed by field eventWaiters which, when nonzero,
208 >     * encodes the thread index and count awaited for by the worker
209 >     * thread most recently calling eventSync. This thread in turn has
210 >     * a record (field nextEventWaiter) for the next waiting worker.
211 >     * In addition to allowing simpler decisions about need for
212 >     * wakeup, the event count bits in eventWaiters serve the role of
213 >     * tags to avoid ABA errors in Treiber stacks.  To reduce delays
214 >     * in task diffusion, workers not otherwise occupied may invoke
215 >     * method releaseWaiters, that removes and signals (unparks)
216 >     * workers not waiting on current count. To minimize task
217 >     * production stalls associate with signalling, any worker pushing
218 >     * a task on an empty queue invokes the weaker method signalWork,
219 >     * that only releases idle workers until it detects interference
220 >     * by other threads trying to release, and lets them take
221 >     * over. The net effect is a tree-like diffusion of signals, where
222 >     * released threads (and possibly others) help with unparks.  To
223 >     * further reduce contention effects a bit, failed CASes to
224 >     * increment field eventCount are tolerated without retries.
225 >     * Conceptually they are merged into the same event, which is OK
226 >     * when their only purpose is to enable workers to scan for work.
227 >     *
228 >     * 5. Managing suspension of extra workers. When a worker is about
229 >     * to block waiting for a join (or via ManagedBlockers), we may
230 >     * create a new thread to maintain parallelism level, or at least
231 >     * avoid starvation (see below). Usually, extra threads are needed
232 >     * for only very short periods, yet join dependencies are such
233 >     * that we sometimes need them in bursts. Rather than create new
234 >     * threads each time this happens, we suspend no-longer-needed
235 >     * extra ones as "spares". For most purposes, we don't distinguish
236 >     * "extra" spare threads from normal "core" threads: On each call
237 >     * to preStep (the only point at which we can do this) a worker
238 >     * checks to see if there are now too many running workers, and if
239 >     * so, suspends itself.  Methods awaitJoin and awaitBlocker look
240 >     * for suspended threads to resume before considering creating a
241 >     * new replacement. We don't need a special data structure to
242 >     * maintain spares; simply scanning the workers array looking for
243 >     * worker.isSuspended() is fine because the calling thread is
244 >     * otherwise not doing anything useful anyway; we are at least as
245 >     * happy if after locating a spare, the caller doesn't actually
246 >     * block because the join is ready before we try to adjust and
247 >     * compensate.  Note that this is intrinsically racy.  One thread
248 >     * may become a spare at about the same time as another is
249 >     * needlessly being created. We counteract this and related slop
250 >     * in part by requiring resumed spares to immediately recheck (in
251 >     * preStep) to see whether they they should re-suspend. The only
252 >     * effective difference between "extra" and "core" threads is that
253 >     * we allow the "extra" ones to time out and die if they are not
254 >     * resumed within a keep-alive interval of a few seconds. This is
255 >     * implemented mainly within ForkJoinWorkerThread, but requires
256 >     * some coordination (isTrimmed() -- meaning killed while
257 >     * suspended) to correctly maintain pool counts.
258 >     *
259 >     * 6. Deciding when to create new workers. The main dynamic
260 >     * control in this class is deciding when to create extra threads,
261 >     * in methods awaitJoin and awaitBlocker. We always
262 >     * need to create one when the number of running threads becomes
263 >     * zero. But because blocked joins are typically dependent, we
264 >     * don't necessarily need or want one-to-one replacement. Using a
265 >     * one-to-one compensation rule often leads to enough useless
266 >     * overhead creating, suspending, resuming, and/or killing threads
267 >     * to signficantly degrade throughput.  We use a rule reflecting
268 >     * the idea that, the more spare threads you already have, the
269 >     * more evidence you need to create another one. The "evidence"
270 >     * here takes two forms: (1) Using a creation threshold expressed
271 >     * in terms of the current deficit -- target minus running
272 >     * threads. To reduce flickering and drift around target values,
273 >     * the relation is quadratic: adding a spare if (dc*dc)>=(sc*pc)
274 >     * (where dc is deficit, sc is number of spare threads and pc is
275 >     * target parallelism.)  (2) Using a form of adaptive
276 >     * spionning. requiring a number of threshold checks proportional
277 >     * to the number of spare threads.  This effectively reduces churn
278 >     * at the price of systematically undershooting target parallelism
279 >     * when many threads are blocked.  However, biasing toward
280 >     * undeshooting partially compensates for the above mechanics to
281 >     * suspend extra threads, that normally lead to overshoot because
282 >     * we can only suspend workers in-between top-level actions. It
283 >     * also better copes with the fact that some of the methods in
284 >     * this class tend to never become compiled (but are interpreted),
285 >     * so some components of the entire set of controls might execute
286 >     * many times faster than others. And similarly for cases where
287 >     * the apparent lack of work is just due to GC stalls and other
288 >     * transient system activity.
289 >     *
290 >     * 7. Maintaining other configuration parameters and monitoring
291 >     * statistics. Updates to fields controlling parallelism level,
292 >     * max size, etc can only meaningfully take effect for individual
293 >     * threads upon their next top-level actions; i.e., between
294 >     * stealing/running tasks/submission, which are separated by calls
295 >     * to preStep.  Memory ordering for these (assumed infrequent)
296 >     * reconfiguration calls is ensured by using reads and writes to
297 >     * volatile field workerCounts (that must be read in preStep anyway)
298 >     * as "fences" -- user-level reads are preceded by reads of
299 >     * workCounts, and writes are followed by no-op CAS to
300 >     * workerCounts. The values reported by other management and
301 >     * monitoring methods are either computed on demand, or are kept
302 >     * in fields that are only updated when threads are otherwise
303 >     * idle.
304 >     *
305 >     * Beware that there is a lot of representation-level coupling
306 >     * among classes ForkJoinPool, ForkJoinWorkerThread, and
307 >     * ForkJoinTask.  For example, direct access to "workers" array by
308 >     * workers, and direct access to ForkJoinTask.status by both
309 >     * ForkJoinPool and ForkJoinWorkerThread.  There is little point
310 >     * trying to reduce this, since any associated future changes in
311 >     * representations will need to be accompanied by algorithmic
312 >     * changes anyway.
313 >     *
314 >     * Style notes: There are lots of inline assignments (of form
315 >     * "while ((local = field) != 0)") which are usually the simplest
316 >     * way to ensure read orderings. Also several occurrences of the
317 >     * unusual "do {} while(!cas...)" which is the simplest way to
318 >     * force an update of a CAS'ed variable. There are also a few
319 >     * other coding oddities that help some methods perform reasonably
320 >     * even when interpreted (not compiled).
321 >     *
322 >     * The order of declarations in this file is: (1) statics (2)
323 >     * fields (along with constants used when unpacking some of them)
324 >     * (3) internal control methods (4) callbacks and other support
325 >     * for ForkJoinTask and ForkJoinWorkerThread classes, (5) exported
326 >     * methods (plus a few little helpers).
327       */
328  
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
329      /**
330       * Factory for creating new {@link ForkJoinWorkerThread}s.
331       * A {@code ForkJoinWorkerThreadFactory} must be defined and used
# Line 112 | Line 337 | public class ForkJoinPool extends Abstra
337           * Returns a new worker thread operating in the given pool.
338           *
339           * @param pool the pool this thread works in
340 <         * @throws NullPointerException if pool is null
340 >         * @throws NullPointerException if the pool is null
341           */
342          public ForkJoinWorkerThread newThread(ForkJoinPool pool);
343      }
# Line 124 | Line 349 | public class ForkJoinPool extends Abstra
349      static class  DefaultForkJoinWorkerThreadFactory
350          implements ForkJoinWorkerThreadFactory {
351          public ForkJoinWorkerThread newThread(ForkJoinPool pool) {
352 <            try {
128 <                return new ForkJoinWorkerThread(pool);
129 <            } catch (OutOfMemoryError oom)  {
130 <                return null;
131 <            }
352 >            return new ForkJoinWorkerThread(pool);
353          }
354      }
355  
# Line 164 | Line 385 | public class ForkJoinPool extends Abstra
385          new AtomicInteger();
386  
387      /**
388 <     * Array holding all worker threads in the pool. Initialized upon
389 <     * first use. Array size must be a power of two.  Updates and
169 <     * replacements are protected by workerLock, but it is always kept
170 <     * in a consistent enough state to be randomly accessed without
171 <     * locking by workers performing work-stealing.
388 >     * Absolute bound for parallelism level. Twice this number must
389 >     * fit into a 16bit field to enable word-packing for some counts.
390       */
391 <    volatile ForkJoinWorkerThread[] workers;
391 >    private static final int MAX_THREADS = 0x7fff;
392  
393      /**
394 <     * Lock protecting access to workers.
394 >     * Array holding all worker threads in the pool.  Array size must
395 >     * be a power of two.  Updates and replacements are protected by
396 >     * workerLock, but the array is always kept in a consistent enough
397 >     * state to be randomly accessed without locking by workers
398 >     * performing work-stealing, as well as other traversal-based
399 >     * methods in this class. All readers must tolerate that some
400 >     * array slots may be null.
401       */
402 <    private final ReentrantLock workerLock;
402 >    volatile ForkJoinWorkerThread[] workers;
403  
404      /**
405 <     * Condition for awaitTermination.
405 >     * Queue for external submissions.
406       */
407 <    private final Condition termination;
407 >    private final LinkedTransferQueue<ForkJoinTask<?>> submissionQueue;
408  
409      /**
410 <     * The uncaught exception handler used when any worker
187 <     * abruptly terminates
410 >     * Lock protecting updates to workers array.
411       */
412 <    private Thread.UncaughtExceptionHandler ueh;
412 >    private final ReentrantLock workerLock;
413  
414      /**
415 <     * Creation factory for worker threads.
415 >     * Latch released upon termination.
416       */
417 <    private final ForkJoinWorkerThreadFactory factory;
417 >    private final CountDownLatch terminationLatch;
418  
419      /**
420 <     * Head of stack of threads that were created to maintain
198 <     * parallelism when other threads blocked, but have since
199 <     * suspended when the parallelism level rose.
420 >     * Creation factory for worker threads.
421       */
422 <    private volatile WaitQueueNode spareStack;
422 >    private final ForkJoinWorkerThreadFactory factory;
423  
424      /**
425       * Sum of per-thread steal counts, updated only when threads are
426       * idle or terminating.
427       */
428 <    private final AtomicLong stealCount;
428 >    private volatile long stealCount;
429  
430      /**
431 <     * Queue for external submissions.
431 >     * Encoded record of top of treiber stack of threads waiting for
432 >     * events. The top 32 bits contain the count being waited for. The
433 >     * bottom word contains one plus the pool index of waiting worker
434 >     * thread.
435       */
436 <    private final LinkedTransferQueue<ForkJoinTask<?>> submissionQueue;
436 >    private volatile long eventWaiters;
437 >
438 >    private static final int  EVENT_COUNT_SHIFT = 32;
439 >    private static final long WAITER_INDEX_MASK = (1L << EVENT_COUNT_SHIFT)-1L;
440  
441      /**
442 <     * Head of Treiber stack for barrier sync. See below for explanation.
442 >     * A counter for events that may wake up worker threads:
443 >     *   - Submission of a new task to the pool
444 >     *   - A worker pushing a task on an empty queue
445 >     *   - termination and reconfiguration
446       */
447 <    private volatile WaitQueueNode syncStack;
447 >    private volatile int eventCount;
448  
449      /**
450 <     * The count for event barrier
451 <     */
452 <    private volatile long eventCount;
450 >     * Lifecycle control. The low word contains the number of workers
451 >     * that are (probably) executing tasks. This value is atomically
452 >     * incremented before a worker gets a task to run, and decremented
453 >     * when worker has no tasks and cannot find any.  Bits 16-18
454 >     * contain runLevel value. When all are zero, the pool is
455 >     * running. Level transitions are monotonic (running -> shutdown
456 >     * -> terminating -> terminated) so each transition adds a bit.
457 >     * These are bundled together to ensure consistent read for
458 >     * termination checks (i.e., that runLevel is at least SHUTDOWN
459 >     * and active threads is zero).
460 >     */
461 >    private volatile int runState;
462 >
463 >    // Note: The order among run level values matters.
464 >    private static final int RUNLEVEL_SHIFT     = 16;
465 >    private static final int SHUTDOWN           = 1 << RUNLEVEL_SHIFT;
466 >    private static final int TERMINATING        = 1 << (RUNLEVEL_SHIFT + 1);
467 >    private static final int TERMINATED         = 1 << (RUNLEVEL_SHIFT + 2);
468 >    private static final int ACTIVE_COUNT_MASK  = (1 << RUNLEVEL_SHIFT) - 1;
469 >    private static final int ONE_ACTIVE         = 1; // active update delta
470  
471      /**
472 <     * Pool number, just for assigning useful names to worker threads
472 >     * Holds number of total (i.e., created and not yet terminated)
473 >     * and running (i.e., not blocked on joins or other managed sync)
474 >     * threads, packed together to ensure consistent snapshot when
475 >     * making decisions about creating and suspending spare
476 >     * threads. Updated only by CAS. Note that adding a new worker
477 >     * requires incrementing both counts, since workers start off in
478 >     * running state.  This field is also used for memory-fencing
479 >     * configuration parameters.
480 >     */
481 >    private volatile int workerCounts;
482 >
483 >    private static final int TOTAL_COUNT_SHIFT  = 16;
484 >    private static final int RUNNING_COUNT_MASK = (1 << TOTAL_COUNT_SHIFT) - 1;
485 >    private static final int ONE_RUNNING        = 1;
486 >    private static final int ONE_TOTAL          = 1 << TOTAL_COUNT_SHIFT;
487 >
488 >    /*
489 >     * Fields parallelism. maxPoolSize, and maintainsParallelism are
490 >     * non-volatile, but external reads/writes use workerCount fences
491 >     * to ensure visability.
492       */
227    private final int poolNumber;
493  
494      /**
495 <     * The maximum allowed pool size
495 >     * The target parallelism level.
496       */
497 <    private volatile int maxPoolSize;
497 >    private int parallelism;
498  
499      /**
500 <     * The desired parallelism level, updated only under workerLock.
500 >     * The maximum allowed pool size.
501       */
502 <    private volatile int parallelism;
502 >    private int maxPoolSize;
503  
504      /**
505       * True if use local fifo, not default lifo, for local polling
506 +     * Replicated by ForkJoinWorkerThreads
507       */
508      private volatile boolean locallyFifo;
509  
510      /**
511 <     * Holds number of total (i.e., created and not yet terminated)
246 <     * 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.
511 >     * Controls whether to add spares to maintain parallelism
512       */
513 <    private volatile int workerCounts;
513 >    private boolean maintainsParallelism;
514 >
515 >    /**
516 >     * The uncaught exception handler used when any worker
517 >     * abruptly terminates
518 >     */
519 >    private volatile Thread.UncaughtExceptionHandler ueh;
520  
521 <    private static int totalCountOf(int s)           { return s >>> 16;  }
522 <    private static int runningCountOf(int s)         { return s & shortMask; }
523 <    private static int workerCountsFor(int t, int r) { return (t << 16) + r; }
521 >    /**
522 >     * Pool number, just for assigning useful names to worker threads
523 >     */
524 >    private final int poolNumber;
525 >
526 >    // utilities for updating fields
527  
528      /**
529 <     * Adds delta (which may be negative) to running count.  This must
261 <     * be called before (with negative arg) and after (with positive)
262 <     * any managed synchronization (i.e., mainly, joins).
263 <     *
264 <     * @param delta the number to add
529 >     * Adds delta to running count.  Used mainly by ForkJoinTask.
530       */
531      final void updateRunningCount(int delta) {
532 <        int s;
533 <        do {} while (!casWorkerCounts(s = workerCounts, s + delta));
532 >        int wc;
533 >        do {} while (!UNSAFE.compareAndSwapInt(this, workerCountsOffset,
534 >                                               wc = workerCounts,
535 >                                               wc + delta));
536      }
537  
538      /**
539 <     * Adds delta (which may be negative) to both total and running
273 <     * count.  This must be called upon creation and termination of
274 <     * worker threads.
275 <     *
276 <     * @param delta the number to add
539 >     * Decrements running count unless already zero
540       */
541 <    private void updateWorkerCount(int delta) {
542 <        int d = delta + (delta << 16); // add to both lo and hi parts
543 <        int s;
544 <        do {} while (!casWorkerCounts(s = workerCounts, s + d));
541 >    final boolean tryDecrementRunningCount() {
542 >        int wc = workerCounts;
543 >        if ((wc & RUNNING_COUNT_MASK) == 0)
544 >            return false;
545 >        return UNSAFE.compareAndSwapInt(this, workerCountsOffset,
546 >                                        wc, wc - ONE_RUNNING);
547      }
548  
549      /**
550 <     * Lifecycle control. High word contains runState, low word
551 <     * 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
550 >     * Write fence for user modifications of pool parameters
551 >     * (parallelism. etc).  Note that it doesn't matter if CAS fails.
552       */
553 <    private volatile int runControl;
554 <
555 <    // RunState values. Order among values matters
556 <    private static final int RUNNING     = 0;
557 <    private static final int SHUTDOWN    = 1;
299 <    private static final int TERMINATING = 2;
300 <    private static final int TERMINATED  = 3;
553 >    private void workerCountWriteFence() {
554 >        int wc;
555 >        UNSAFE.compareAndSwapInt(this, workerCountsOffset,
556 >                                 wc = workerCounts, wc);
557 >    }
558  
559 <    private static int runStateOf(int c)             { return c >>> 16; }
560 <    private static int activeCountOf(int c)          { return c & shortMask; }
561 <    private static int runControlFor(int r, int a)   { return (r << 16) + a; }
559 >    /**
560 >     * Read fence for external reads of pool parameters
561 >     * (parallelism. maxPoolSize, etc).
562 >     */
563 >    private void workerCountReadFence() {
564 >        int ignore = workerCounts;
565 >    }
566  
567      /**
568       * Tries incrementing active count; fails on contention.
569 <     * Called by workers before/during executing tasks.
569 >     * Called by workers before executing tasks.
570       *
571       * @return true on success
572       */
573      final boolean tryIncrementActiveCount() {
574 <        int c = runControl;
575 <        return casRunControl(c, c+1);
574 >        int c;
575 >        return UNSAFE.compareAndSwapInt(this, runStateOffset,
576 >                                        c = runState, c + ONE_ACTIVE);
577      }
578  
579      /**
580       * Tries decrementing active count; fails on contention.
581 <     * Possibly triggers termination on success.
320 <     * Called by workers when they can't find tasks.
321 <     *
322 <     * @return true on success
581 >     * Called when workers cannot find tasks to run.
582       */
583      final boolean tryDecrementActiveCount() {
584 <        int c = runControl;
585 <        int nextc = c - 1;
586 <        if (!casRunControl(c, nextc))
587 <            return false;
588 <        if (canTerminateOnShutdown(nextc))
589 <            terminateOnShutdown();
590 <        return true;
584 >        int c;
585 >        return UNSAFE.compareAndSwapInt(this, runStateOffset,
586 >                                        c = runState, c - ONE_ACTIVE);
587 >    }
588 >
589 >    /**
590 >     * Advances to at least the given level. Returns true if not
591 >     * already in at least the given level.
592 >     */
593 >    private boolean advanceRunLevel(int level) {
594 >        for (;;) {
595 >            int s = runState;
596 >            if ((s & level) != 0)
597 >                return false;
598 >            if (UNSAFE.compareAndSwapInt(this, runStateOffset, s, s | level))
599 >                return true;
600 >        }
601      }
602  
603 +    // workers array maintenance
604 +
605      /**
606 <     * Returns {@code true} if argument represents zero active count
336 <     * and nonzero runstate, which is the triggering condition for
337 <     * terminating on shutdown.
606 >     * Records and returns a workers array index for new worker.
607       */
608 <    private static boolean canTerminateOnShutdown(int c) {
609 <        // i.e. least bit is nonzero runState bit
610 <        return ((c & -c) >>> 16) != 0;
608 >    private int recordWorker(ForkJoinWorkerThread w) {
609 >        // Try using slot totalCount-1. If not available, scan and/or resize
610 >        int k = (workerCounts >>> TOTAL_COUNT_SHIFT) - 1;
611 >        final ReentrantLock lock = this.workerLock;
612 >        lock.lock();
613 >        try {
614 >            ForkJoinWorkerThread[] ws = workers;
615 >            int nws = ws.length;
616 >            if (k < 0 || k >= nws || ws[k] != null) {
617 >                for (k = 0; k < nws && ws[k] != null; ++k)
618 >                    ;
619 >                if (k == nws)
620 >                    ws = Arrays.copyOf(ws, nws << 1);
621 >            }
622 >            ws[k] = w;
623 >            workers = ws; // volatile array write ensures slot visibility
624 >        } finally {
625 >            lock.unlock();
626 >        }
627 >        return k;
628      }
629  
630      /**
631 <     * Transition run state to at least the given state. Return true
346 <     * if not already at least given state.
631 >     * Nulls out record of worker in workers array
632       */
633 <    private boolean transitionRunStateTo(int state) {
633 >    private void forgetWorker(ForkJoinWorkerThread w) {
634 >        int idx = w.poolIndex;
635 >        // Locking helps method recordWorker avoid unecessary expansion
636 >        final ReentrantLock lock = this.workerLock;
637 >        lock.lock();
638 >        try {
639 >            ForkJoinWorkerThread[] ws = workers;
640 >            if (idx >= 0 && idx < ws.length && ws[idx] == w) // verify
641 >                ws[idx] = null;
642 >        } finally {
643 >            lock.unlock();
644 >        }
645 >    }
646 >
647 >    // adding and removing workers
648 >
649 >    /**
650 >     * Tries to create and add new worker. Assumes that worker counts
651 >     * are already updated to accommodate the worker, so adjusts on
652 >     * failure.
653 >     *
654 >     * @return new worker or null if creation failed
655 >     */
656 >    private ForkJoinWorkerThread addWorker() {
657 >        ForkJoinWorkerThread w = null;
658 >        try {
659 >            w = factory.newThread(this);
660 >        } finally { // Adjust on either null or exceptional factory return
661 >            if (w == null) {
662 >                onWorkerCreationFailure();
663 >                return null;
664 >            }
665 >        }
666 >        w.start(recordWorker(w), locallyFifo, ueh);
667 >        return w;
668 >    }
669 >
670 >    /**
671 >     * Adjusts counts upon failure to create worker
672 >     */
673 >    private void onWorkerCreationFailure() {
674          for (;;) {
675 <            int c = runControl;
676 <            if (runStateOf(c) >= state)
677 <                return false;
678 <            if (casRunControl(c, runControlFor(state, activeCountOf(c))))
675 >            int wc = workerCounts;
676 >            if ((wc >>> TOTAL_COUNT_SHIFT) > 0 &&
677 >                UNSAFE.compareAndSwapInt(this, workerCountsOffset,
678 >                                         wc, wc - (ONE_RUNNING|ONE_TOTAL)))
679 >                break;
680 >        }
681 >        tryTerminate(false); // in case of failure during shutdown
682 >    }
683 >
684 >    /**
685 >     * Create enough total workers to establish target parallelism,
686 >     * giving up if terminating or addWorker fails
687 >     */
688 >    private void ensureEnoughTotalWorkers() {
689 >        int wc;
690 >        while (((wc = workerCounts) >>> TOTAL_COUNT_SHIFT) < parallelism &&
691 >               runState < TERMINATING) {
692 >            if ((UNSAFE.compareAndSwapInt(this, workerCountsOffset,
693 >                                          wc, wc + (ONE_RUNNING|ONE_TOTAL)) &&
694 >                 addWorker() == null))
695 >                break;
696 >        }
697 >    }
698 >
699 >    /**
700 >     * Final callback from terminating worker.  Removes record of
701 >     * worker from array, and adjusts counts. If pool is shutting
702 >     * down, tries to complete terminatation, else possibly replaces
703 >     * the worker.
704 >     *
705 >     * @param w the worker
706 >     */
707 >    final void workerTerminated(ForkJoinWorkerThread w) {
708 >        if (w.active) { // force inactive
709 >            w.active = false;
710 >            do {} while (!tryDecrementActiveCount());
711 >        }
712 >        forgetWorker(w);
713 >
714 >        // Decrement total count, and if was running, running count
715 >        // Spin (waiting for other updates) if either would be negative
716 >        int nr = w.isTrimmed() ? 0 : ONE_RUNNING;
717 >        int unit = ONE_TOTAL + nr;
718 >        for (;;) {
719 >            int wc = workerCounts;
720 >            int rc = wc & RUNNING_COUNT_MASK;
721 >            if (rc - nr < 0 || (wc >>> TOTAL_COUNT_SHIFT) == 0)
722 >                Thread.yield(); // back off if waiting for other updates
723 >            else if (UNSAFE.compareAndSwapInt(this, workerCountsOffset,
724 >                                              wc, wc - unit))
725 >                break;
726 >        }
727 >
728 >        accumulateStealCount(w); // collect final count
729 >        if (!tryTerminate(false))
730 >            ensureEnoughTotalWorkers();
731 >    }
732 >
733 >    // Waiting for and signalling events
734 >
735 >    /**
736 >     * Ensures eventCount on exit is different (mod 2^32) than on
737 >     * entry.  CAS failures are OK -- any change in count suffices.
738 >     */
739 >    private void advanceEventCount() {
740 >        int c;
741 >        UNSAFE.compareAndSwapInt(this, eventCountOffset, c = eventCount, c+1);
742 >    }
743 >
744 >    /**
745 >     * Releases workers blocked on a count not equal to current count.
746 >     */
747 >    final void releaseWaiters() {
748 >        long top;
749 >        int id;
750 >        while ((id = (int)((top = eventWaiters) & WAITER_INDEX_MASK)) > 0 &&
751 >               (int)(top >>> EVENT_COUNT_SHIFT) != eventCount) {
752 >            ForkJoinWorkerThread[] ws = workers;
753 >            ForkJoinWorkerThread w;
754 >            if (ws.length >= id && (w = ws[id - 1]) != null &&
755 >                UNSAFE.compareAndSwapLong(this, eventWaitersOffset,
756 >                                          top, w.nextWaiter))
757 >                LockSupport.unpark(w);
758 >        }
759 >    }
760 >
761 >    /**
762 >     * Advances eventCount and releases waiters until interference by
763 >     * other releasing threads is detected.
764 >     */
765 >    final void signalWork() {
766 >        int ec;
767 >        UNSAFE.compareAndSwapInt(this, eventCountOffset, ec=eventCount, ec+1);
768 >        outer:for (;;) {
769 >            long top = eventWaiters;
770 >            ec = eventCount;
771 >            for (;;) {
772 >                ForkJoinWorkerThread[] ws; ForkJoinWorkerThread w;
773 >                int id = (int)(top & WAITER_INDEX_MASK);
774 >                if (id <= 0 || (int)(top >>> EVENT_COUNT_SHIFT) == ec)
775 >                    return;
776 >                if ((ws = workers).length < id || (w = ws[id - 1]) == null ||
777 >                    !UNSAFE.compareAndSwapLong(this, eventWaitersOffset,
778 >                                               top, top = w.nextWaiter))
779 >                    continue outer;      // possibly stale; reread
780 >                LockSupport.unpark(w);
781 >                if (top != eventWaiters) // let someone else take over
782 >                    return;
783 >            }
784 >        }
785 >    }
786 >
787 >    /**
788 >     * If worker is inactive, blocks until terminating or event count
789 >     * advances from last value held by worker; in any case helps
790 >     * release others.
791 >     *
792 >     * @param w the calling worker thread
793 >     */
794 >    private void eventSync(ForkJoinWorkerThread w) {
795 >        if (!w.active) {
796 >            int prev = w.lastEventCount;
797 >            long nextTop = (((long)prev << EVENT_COUNT_SHIFT) |
798 >                            ((long)(w.poolIndex + 1)));
799 >            long top;
800 >            while ((runState < SHUTDOWN || !tryTerminate(false)) &&
801 >                   (((int)(top = eventWaiters) & WAITER_INDEX_MASK) == 0 ||
802 >                    (int)(top >>> EVENT_COUNT_SHIFT) == prev) &&
803 >                   eventCount == prev) {
804 >                if (UNSAFE.compareAndSwapLong(this, eventWaitersOffset,
805 >                                              w.nextWaiter = top, nextTop)) {
806 >                    accumulateStealCount(w); // transfer steals while idle
807 >                    Thread.interrupted();    // clear/ignore interrupt
808 >                    while (eventCount == prev)
809 >                        w.doPark();
810 >                    break;
811 >                }
812 >            }
813 >            w.lastEventCount = eventCount;
814 >        }
815 >        releaseWaiters();
816 >    }
817 >
818 >    /**
819 >     * Callback from workers invoked upon each top-level action (i.e.,
820 >     * stealing a task or taking a submission and running
821 >     * it). Performs one or both of the following:
822 >     *
823 >     * * If the worker cannot find work, updates its active status to
824 >     * inactive and updates activeCount unless there is contention, in
825 >     * which case it may try again (either in this or a subsequent
826 >     * call).  Additionally, awaits the next task event and/or helps
827 >     * wake up other releasable waiters.
828 >     *
829 >     * * If there are too many running threads, suspends this worker
830 >     * (first forcing inactivation if necessary).  If it is not
831 >     * resumed before a keepAlive elapses, the worker may be "trimmed"
832 >     * -- killed while suspended within suspendAsSpare. Otherwise,
833 >     * upon resume it rechecks to make sure that it is still needed.
834 >     *
835 >     * @param w the worker
836 >     * @param worked false if the worker scanned for work but didn't
837 >     * find any (in which case it may block waiting for work).
838 >     */
839 >    final void preStep(ForkJoinWorkerThread w, boolean worked) {
840 >        boolean active = w.active;
841 >        boolean inactivate = !worked & active;
842 >        for (;;) {
843 >            if (inactivate) {
844 >                int c = runState;
845 >                if (UNSAFE.compareAndSwapInt(this, runStateOffset,
846 >                                             c, c - ONE_ACTIVE))
847 >                    inactivate = active = w.active = false;
848 >            }
849 >            int wc = workerCounts;
850 >            if ((wc & RUNNING_COUNT_MASK) <= parallelism) {
851 >                if (!worked)
852 >                    eventSync(w);
853 >                return;
854 >            }
855 >            if (!(inactivate |= active) &&  // must inactivate to suspend
856 >                UNSAFE.compareAndSwapInt(this, workerCountsOffset,
857 >                                         wc, wc - ONE_RUNNING) &&
858 >                !w.suspendAsSpare())        // false if trimmed
859 >                return;
860 >        }
861 >    }
862 >
863 >    /**
864 >     * Adjusts counts and creates or resumes compensating threads for
865 >     * a worker blocking on task joinMe.  First tries resuming an
866 >     * existing spare (which usually also avoids any count
867 >     * adjustment), but must then decrement running count to determine
868 >     * whether a new thread is needed. See above for fuller
869 >     * explanation. This code is sprawled out non-modularly mainly
870 >     * because adaptive spinning works best if the entire method is
871 >     * either interpreted or compiled vs having only some pieces of it
872 >     * compiled.
873 >     *
874 >     * @param joinMe the task to join
875 >     * @return task status on exit (to simplify usage by callers)
876 >     */
877 >    final int awaitJoin(ForkJoinTask<?> joinMe) {
878 >        int pc = parallelism;
879 >        boolean adj = false;        // true when running count adjusted
880 >        int scans = 0;
881 >
882 >        while (joinMe.status >= 0) {
883 >            ForkJoinWorkerThread spare = null;
884 >            if ((workerCounts & RUNNING_COUNT_MASK) < pc) {
885 >                ForkJoinWorkerThread[] ws = workers;
886 >                int nws = ws.length;
887 >                for (int i = 0; i < nws; ++i) {
888 >                    ForkJoinWorkerThread w = ws[i];
889 >                    if (w != null && w.isSuspended()) {
890 >                        spare = w;
891 >                        break;
892 >                    }
893 >                }
894 >                if (joinMe.status < 0)
895 >                    break;
896 >            }
897 >            int wc = workerCounts;
898 >            int rc = wc & RUNNING_COUNT_MASK;
899 >            int dc = pc - rc;
900 >            if (dc > 0 && spare != null && spare.tryUnsuspend()) {
901 >                if (adj) {
902 >                    int c;
903 >                    do {} while (!UNSAFE.compareAndSwapInt
904 >                                 (this, workerCountsOffset,
905 >                                  c = workerCounts, c + ONE_RUNNING));
906 >                }
907 >                adj = true;
908 >                LockSupport.unpark(spare);
909 >            }
910 >            else if (adj) {
911 >                if (dc <= 0)
912 >                    break;
913 >                int tc = wc >>> TOTAL_COUNT_SHIFT;
914 >                if (scans > tc) {
915 >                    int ts = (tc - pc) * pc;
916 >                    if (rc != 0 &&  (dc * dc < ts || !maintainsParallelism))
917 >                        break;
918 >                    if (scans > ts && tc < maxPoolSize &&
919 >                        UNSAFE.compareAndSwapInt(this, workerCountsOffset, wc,
920 >                                                 wc+(ONE_RUNNING|ONE_TOTAL))){
921 >                        addWorker();
922 >                        break;
923 >                    }
924 >                }
925 >            }
926 >            else if (rc != 0)
927 >                adj = UNSAFE.compareAndSwapInt (this, workerCountsOffset,
928 >                                                wc, wc - ONE_RUNNING);
929 >            if ((scans++ & 1) == 0)
930 >                releaseWaiters();   // help others progress
931 >            else
932 >                Thread.yield();     // avoid starving productive threads
933 >        }
934 >
935 >        if (adj) {
936 >            joinMe.internalAwaitDone();
937 >            int c;
938 >            do {} while (!UNSAFE.compareAndSwapInt
939 >                         (this, workerCountsOffset,
940 >                          c = workerCounts, c + ONE_RUNNING));
941 >        }
942 >        return joinMe.status;
943 >    }
944 >
945 >    /**
946 >     * Same idea as awaitJoin
947 >     */
948 >    final void awaitBlocker(ManagedBlocker blocker, boolean maintainPar)
949 >        throws InterruptedException {
950 >        maintainPar &= maintainsParallelism;
951 >        int pc = parallelism;
952 >        boolean adj = false;        // true when running count adjusted
953 >        int scans = 0;
954 >        boolean done;
955 >
956 >        for (;;) {
957 >            if (done = blocker.isReleasable())
958 >                break;
959 >            ForkJoinWorkerThread spare = null;
960 >            if ((workerCounts & RUNNING_COUNT_MASK) < pc) {
961 >                ForkJoinWorkerThread[] ws = workers;
962 >                int nws = ws.length;
963 >                for (int i = 0; i < nws; ++i) {
964 >                    ForkJoinWorkerThread w = ws[i];
965 >                    if (w != null && w.isSuspended()) {
966 >                        spare = w;
967 >                        break;
968 >                    }
969 >                }
970 >                if (done = blocker.isReleasable())
971 >                    break;
972 >            }
973 >            int wc = workerCounts;
974 >            int rc = wc & RUNNING_COUNT_MASK;
975 >            int dc = pc - rc;
976 >            if (dc > 0 && spare != null && spare.tryUnsuspend()) {
977 >                if (adj) {
978 >                    int c;
979 >                    do {} while (!UNSAFE.compareAndSwapInt
980 >                                 (this, workerCountsOffset,
981 >                                  c = workerCounts, c + ONE_RUNNING));
982 >                }
983 >                adj = true;
984 >                LockSupport.unpark(spare);
985 >            }
986 >            else if (adj) {
987 >                if (dc <= 0)
988 >                    break;
989 >                int tc = wc >>> TOTAL_COUNT_SHIFT;
990 >                if (scans > tc) {
991 >                    int ts = (tc - pc) * pc;
992 >                    if (rc != 0 &&  (dc * dc < ts || !maintainPar))
993 >                        break;
994 >                    if (scans > ts && tc < maxPoolSize &&
995 >                        UNSAFE.compareAndSwapInt(this, workerCountsOffset, wc,
996 >                                                 wc+(ONE_RUNNING|ONE_TOTAL))){
997 >                        addWorker();
998 >                        break;
999 >                    }
1000 >                }
1001 >            }
1002 >            else if (rc != 0)
1003 >                adj = UNSAFE.compareAndSwapInt (this, workerCountsOffset,
1004 >                                                wc, wc - ONE_RUNNING);
1005 >            if ((++scans & 1) == 0)
1006 >                releaseWaiters();   // help others progress
1007 >            else
1008 >                Thread.yield();     // avoid starving productive threads
1009 >        }
1010 >
1011 >        try {
1012 >            if (!done)
1013 >                do {} while (!blocker.isReleasable() && !blocker.block());
1014 >        } finally {
1015 >            if (adj) {
1016 >                int c;
1017 >                do {} while (!UNSAFE.compareAndSwapInt
1018 >                             (this, workerCountsOffset,
1019 >                              c = workerCounts, c + ONE_RUNNING));
1020 >            }
1021 >        }
1022 >    }
1023 >
1024 >    /**
1025 >     * Unless there are not enough other running threads, adjusts
1026 >     * counts and blocks a worker performing helpJoin that cannot find
1027 >     * any work.
1028 >     *
1029 >     * @return true if joinMe now done
1030 >     */
1031 >    final boolean tryAwaitBusyJoin(ForkJoinTask<?> joinMe) {
1032 >        int pc = parallelism;
1033 >        outer:for (;;) {
1034 >            releaseWaiters();
1035 >            if ((workerCounts & RUNNING_COUNT_MASK) < pc) {
1036 >                ForkJoinWorkerThread[] ws = workers;
1037 >                int nws = ws.length;
1038 >                for (int i = 0; i < nws; ++i) {
1039 >                    ForkJoinWorkerThread w = ws[i];
1040 >                    if (w != null && w.isSuspended()) {
1041 >                        if (joinMe.status < 0)
1042 >                            return true;
1043 >                        if ((workerCounts & RUNNING_COUNT_MASK) > pc)
1044 >                            break;
1045 >                        if (w.tryUnsuspend()) {
1046 >                            LockSupport.unpark(w);
1047 >                            break outer;
1048 >                        }
1049 >                        continue outer;
1050 >                    }
1051 >                }
1052 >            }
1053 >            if (joinMe.status < 0)
1054                  return true;
1055 +            int wc = workerCounts;
1056 +            if ((wc & RUNNING_COUNT_MASK) <= 2 ||
1057 +                (wc >>> TOTAL_COUNT_SHIFT) < pc)
1058 +                return false;  // keep this thread alive
1059 +            if (UNSAFE.compareAndSwapInt(this, workerCountsOffset,
1060 +                                         wc, wc - ONE_RUNNING))
1061 +                break;
1062          }
1063 +
1064 +        joinMe.internalAwaitDone();
1065 +        int c;
1066 +        do {} while (!UNSAFE.compareAndSwapInt
1067 +                     (this, workerCountsOffset,
1068 +                      c = workerCounts, c + ONE_RUNNING));
1069 +        return true;
1070      }
1071  
1072      /**
1073 <     * Controls whether to add spares to maintain parallelism
1073 >     * Possibly initiates and/or completes termination.
1074 >     *
1075 >     * @param now if true, unconditionally terminate, else only
1076 >     * if shutdown and empty queue and no active workers
1077 >     * @return true if now terminating or terminated
1078 >     */
1079 >    private boolean tryTerminate(boolean now) {
1080 >        if (now)
1081 >            advanceRunLevel(SHUTDOWN); // ensure at least SHUTDOWN
1082 >        else if (runState < SHUTDOWN ||
1083 >                 !submissionQueue.isEmpty() ||
1084 >                 (runState & ACTIVE_COUNT_MASK) != 0)
1085 >            return false;
1086 >
1087 >        if (advanceRunLevel(TERMINATING))
1088 >            startTerminating();
1089 >
1090 >        // Finish now if all threads terminated; else in some subsequent call
1091 >        if ((workerCounts >>> TOTAL_COUNT_SHIFT) == 0) {
1092 >            advanceRunLevel(TERMINATED);
1093 >            terminationLatch.countDown();
1094 >        }
1095 >        return true;
1096 >    }
1097 >
1098 >    /**
1099 >     * Actions on transition to TERMINATING
1100 >     */
1101 >    private void startTerminating() {
1102 >        for (int i = 0; i < 2; ++i) { // twice to mop up newly created workers
1103 >            cancelSubmissions();
1104 >            shutdownWorkers();
1105 >            cancelWorkerTasks();
1106 >            advanceEventCount();
1107 >            releaseWaiters();
1108 >            interruptWorkers();
1109 >        }
1110 >    }
1111 >
1112 >    /**
1113 >     * Clear out and cancel submissions, ignoring exceptions
1114 >     */
1115 >    private void cancelSubmissions() {
1116 >        ForkJoinTask<?> task;
1117 >        while ((task = submissionQueue.poll()) != null) {
1118 >            try {
1119 >                task.cancel(false);
1120 >            } catch (Throwable ignore) {
1121 >            }
1122 >        }
1123 >    }
1124 >
1125 >    /**
1126 >     * Sets all worker run states to at least shutdown,
1127 >     * also resuming suspended workers
1128       */
1129 <    private volatile boolean maintainsParallelism;
1129 >    private void shutdownWorkers() {
1130 >        ForkJoinWorkerThread[] ws = workers;
1131 >        int nws = ws.length;
1132 >        for (int i = 0; i < nws; ++i) {
1133 >            ForkJoinWorkerThread w = ws[i];
1134 >            if (w != null)
1135 >                w.shutdown();
1136 >        }
1137 >    }
1138 >
1139 >    /**
1140 >     * Clears out and cancels all locally queued tasks
1141 >     */
1142 >    private void cancelWorkerTasks() {
1143 >        ForkJoinWorkerThread[] ws = workers;
1144 >        int nws = ws.length;
1145 >        for (int i = 0; i < nws; ++i) {
1146 >            ForkJoinWorkerThread w = ws[i];
1147 >            if (w != null)
1148 >                w.cancelTasks();
1149 >        }
1150 >    }
1151 >
1152 >    /**
1153 >     * Unsticks all workers blocked on joins etc
1154 >     */
1155 >    private void interruptWorkers() {
1156 >        ForkJoinWorkerThread[] ws = workers;
1157 >        int nws = ws.length;
1158 >        for (int i = 0; i < nws; ++i) {
1159 >            ForkJoinWorkerThread w = ws[i];
1160 >            if (w != null && !w.isTerminated()) {
1161 >                try {
1162 >                    w.interrupt();
1163 >                } catch (SecurityException ignore) {
1164 >                }
1165 >            }
1166 >        }
1167 >    }
1168 >
1169 >    // misc support for ForkJoinWorkerThread
1170 >
1171 >    /**
1172 >     * Returns pool number
1173 >     */
1174 >    final int getPoolNumber() {
1175 >        return poolNumber;
1176 >    }
1177 >
1178 >    /**
1179 >     * Accumulates steal count from a worker, clearing
1180 >     * the worker's value
1181 >     */
1182 >    final void accumulateStealCount(ForkJoinWorkerThread w) {
1183 >        int sc = w.stealCount;
1184 >        if (sc != 0) {
1185 >            long c;
1186 >            w.stealCount = 0;
1187 >            do {} while (!UNSAFE.compareAndSwapLong(this, stealCountOffset,
1188 >                                                    c = stealCount, c + sc));
1189 >        }
1190 >    }
1191 >
1192 >    /**
1193 >     * Returns the approximate (non-atomic) number of idle threads per
1194 >     * active thread.
1195 >     */
1196 >    final int idlePerActive() {
1197 >        int ac = runState;    // no mask -- artifically boosts during shutdown
1198 >        int pc = parallelism; // use targeted parallelism, not rc
1199 >        // Use exact results for small values, saturate past 4
1200 >        return pc <= ac? 0 : pc >>> 1 <= ac? 1 : pc >>> 2 <= ac? 3 : pc >>> 3;
1201 >    }
1202 >
1203 >    // Public and protected methods
1204  
1205      // Constructors
1206  
# Line 384 | Line 1226 | public class ForkJoinPool extends Abstra
1226       *
1227       * @param parallelism the parallelism level
1228       * @throws IllegalArgumentException if parallelism less than or
1229 <     * equal to zero
1229 >     *         equal to zero, or greater than implementation limit
1230       * @throws SecurityException if a security manager exists and
1231       *         the caller is not permitted to modify threads
1232       *         because it does not hold {@link
# Line 400 | Line 1242 | public class ForkJoinPool extends Abstra
1242       * thread factory.
1243       *
1244       * @param factory the factory for creating new threads
1245 <     * @throws NullPointerException if factory is null
1245 >     * @throws NullPointerException if the factory is null
1246       * @throws SecurityException if a security manager exists and
1247       *         the caller is not permitted to modify threads
1248       *         because it does not hold {@link
# Line 417 | Line 1259 | public class ForkJoinPool extends Abstra
1259       * @param parallelism the parallelism level
1260       * @param factory the factory for creating new threads
1261       * @throws IllegalArgumentException if parallelism less than or
1262 <     * equal to zero, or greater than implementation limit
1263 <     * @throws NullPointerException if factory is null
1262 >     *         equal to zero, or greater than implementation limit
1263 >     * @throws NullPointerException if the factory is null
1264       * @throws SecurityException if a security manager exists and
1265       *         the caller is not permitted to modify threads
1266       *         because it does not hold {@link
1267       *         java.lang.RuntimePermission}{@code ("modifyThread")}
1268       */
1269      public ForkJoinPool(int parallelism, ForkJoinWorkerThreadFactory factory) {
1270 <        if (parallelism <= 0 || parallelism > MAX_THREADS)
429 <            throw new IllegalArgumentException();
1270 >        checkPermission();
1271          if (factory == null)
1272              throw new NullPointerException();
1273 <        checkPermission();
1274 <        this.factory = factory;
1273 >        if (parallelism <= 0 || parallelism > MAX_THREADS)
1274 >            throw new IllegalArgumentException();
1275 >        this.poolNumber = poolNumberGenerator.incrementAndGet();
1276 >        int arraySize = initialArraySizeFor(parallelism);
1277          this.parallelism = parallelism;
1278 +        this.factory = factory;
1279          this.maxPoolSize = MAX_THREADS;
1280          this.maintainsParallelism = true;
1281 <        this.poolNumber = poolNumberGenerator.incrementAndGet();
438 <        this.workerLock = new ReentrantLock();
439 <        this.termination = workerLock.newCondition();
440 <        this.stealCount = new AtomicLong();
1281 >        this.workers = new ForkJoinWorkerThread[arraySize];
1282          this.submissionQueue = new LinkedTransferQueue<ForkJoinTask<?>>();
1283 <        // worker array and workers are lazily constructed
1284 <    }
444 <
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 <        }
1283 >        this.workerLock = new ReentrantLock();
1284 >        this.terminationLatch = new CountDownLatch(1);
1285      }
1286  
1287      /**
1288 <     * Worker creation and startup for threads added via setParallelism.
1288 >     * Returns initial power of two size for workers array.
1289 >     * @param pc the initial parallelism level
1290       */
1291 <    private void createAndStartAddedWorkers() {
1292 <        resumeAllSpares();  // Allow spares to convert to nonspare
1293 <        int ps = parallelism;
1294 <        ForkJoinWorkerThread[] ws = ensureWorkerArrayCapacity(ps);
1295 <        int len = ws.length;
1296 <        // Sweep through slots, to keep lowest indices most populated
1297 <        int k = 0;
1298 <        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 <        }
1291 >    private static int initialArraySizeFor(int pc) {
1292 >        // See Hackers Delight, sec 3.2. We know MAX_THREADS < (1 >>> 16)
1293 >        int size = pc < MAX_THREADS ? pc + 1 : MAX_THREADS;
1294 >        size |= size >>> 1;
1295 >        size |= size >>> 2;
1296 >        size |= size >>> 4;
1297 >        size |= size >>> 8;
1298 >        return size + 1;
1299      }
1300  
1301      // Execution methods
# Line 581 | Line 1306 | public class ForkJoinPool extends Abstra
1306      private <T> void doSubmit(ForkJoinTask<T> task) {
1307          if (task == null)
1308              throw new NullPointerException();
1309 <        if (isShutdown())
1309 >        if (runState >= SHUTDOWN)
1310              throw new RejectedExecutionException();
586        if (workers == null)
587            ensureWorkerInitialization();
1311          submissionQueue.offer(task);
1312 <        signalIdleWorkers();
1312 >        advanceEventCount();
1313 >        releaseWaiters();
1314 >        ensureEnoughTotalWorkers();
1315      }
1316  
1317      /**
# Line 594 | Line 1319 | public class ForkJoinPool extends Abstra
1319       *
1320       * @param task the task
1321       * @return the task's result
1322 <     * @throws NullPointerException if task is null
1323 <     * @throws RejectedExecutionException if pool is shut down
1322 >     * @throws NullPointerException if the task is null
1323 >     * @throws RejectedExecutionException if the task cannot be
1324 >     *         scheduled for execution
1325       */
1326      public <T> T invoke(ForkJoinTask<T> task) {
1327          doSubmit(task);
# Line 606 | Line 1332 | public class ForkJoinPool extends Abstra
1332       * Arranges for (asynchronous) execution of the given task.
1333       *
1334       * @param task the task
1335 <     * @throws NullPointerException if task is null
1336 <     * @throws RejectedExecutionException if pool is shut down
1335 >     * @throws NullPointerException if the task is null
1336 >     * @throws RejectedExecutionException if the task cannot be
1337 >     *         scheduled for execution
1338       */
1339      public void execute(ForkJoinTask<?> task) {
1340          doSubmit(task);
# Line 615 | Line 1342 | public class ForkJoinPool extends Abstra
1342  
1343      // AbstractExecutorService methods
1344  
1345 +    /**
1346 +     * @throws NullPointerException if the task is null
1347 +     * @throws RejectedExecutionException if the task cannot be
1348 +     *         scheduled for execution
1349 +     */
1350      public void execute(Runnable task) {
1351          ForkJoinTask<?> job;
1352          if (task instanceof ForkJoinTask<?>) // avoid re-wrap
# Line 624 | Line 1356 | public class ForkJoinPool extends Abstra
1356          doSubmit(job);
1357      }
1358  
1359 +    /**
1360 +     * @throws NullPointerException if the task is null
1361 +     * @throws RejectedExecutionException if the task cannot be
1362 +     *         scheduled for execution
1363 +     */
1364      public <T> ForkJoinTask<T> submit(Callable<T> task) {
1365          ForkJoinTask<T> job = ForkJoinTask.adapt(task);
1366          doSubmit(job);
1367          return job;
1368      }
1369  
1370 +    /**
1371 +     * @throws NullPointerException if the task is null
1372 +     * @throws RejectedExecutionException if the task cannot be
1373 +     *         scheduled for execution
1374 +     */
1375      public <T> ForkJoinTask<T> submit(Runnable task, T result) {
1376          ForkJoinTask<T> job = ForkJoinTask.adapt(task, result);
1377          doSubmit(job);
1378          return job;
1379      }
1380  
1381 +    /**
1382 +     * @throws NullPointerException if the task is null
1383 +     * @throws RejectedExecutionException if the task cannot be
1384 +     *         scheduled for execution
1385 +     */
1386      public ForkJoinTask<?> submit(Runnable task) {
1387          ForkJoinTask<?> job;
1388          if (task instanceof ForkJoinTask<?>) // avoid re-wrap
# Line 651 | Line 1398 | public class ForkJoinPool extends Abstra
1398       *
1399       * @param task the task to submit
1400       * @return the task
1401 +     * @throws NullPointerException if the task is null
1402       * @throws RejectedExecutionException if the task cannot be
1403       *         scheduled for execution
656     * @throws NullPointerException if the task is null
1404       */
1405      public <T> ForkJoinTask<T> submit(ForkJoinTask<T> task) {
1406          doSubmit(task);
1407          return task;
1408      }
1409  
1410 <
1410 >    /**
1411 >     * @throws NullPointerException       {@inheritDoc}
1412 >     * @throws RejectedExecutionException {@inheritDoc}
1413 >     */
1414      public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) {
1415          ArrayList<ForkJoinTask<T>> forkJoinTasks =
1416              new ArrayList<ForkJoinTask<T>>(tasks.size());
# Line 669 | Line 1419 | public class ForkJoinPool extends Abstra
1419          invoke(new InvokeAll<T>(forkJoinTasks));
1420  
1421          @SuppressWarnings({"unchecked", "rawtypes"})
1422 <        List<Future<T>> futures = (List<Future<T>>) (List) forkJoinTasks;
1422 >            List<Future<T>> futures = (List<Future<T>>) (List) forkJoinTasks;
1423          return futures;
1424      }
1425  
# Line 683 | Line 1433 | public class ForkJoinPool extends Abstra
1433          private static final long serialVersionUID = -7914297376763021607L;
1434      }
1435  
686    // Configuration and status settings and queries
687
1436      /**
1437       * Returns the factory used for constructing new workers.
1438       *
# Line 701 | Line 1449 | public class ForkJoinPool extends Abstra
1449       * @return the handler, or {@code null} if none
1450       */
1451      public Thread.UncaughtExceptionHandler getUncaughtExceptionHandler() {
1452 <        Thread.UncaughtExceptionHandler h;
1453 <        final ReentrantLock lock = this.workerLock;
706 <        lock.lock();
707 <        try {
708 <            h = ueh;
709 <        } finally {
710 <            lock.unlock();
711 <        }
712 <        return h;
1452 >        workerCountReadFence();
1453 >        return ueh;
1454      }
1455  
1456      /**
# Line 728 | Line 1469 | public class ForkJoinPool extends Abstra
1469      public Thread.UncaughtExceptionHandler
1470          setUncaughtExceptionHandler(Thread.UncaughtExceptionHandler h) {
1471          checkPermission();
1472 <        Thread.UncaughtExceptionHandler old = null;
1473 <        final ReentrantLock lock = this.workerLock;
733 <        lock.lock();
734 <        try {
735 <            old = ueh;
1472 >        Thread.UncaughtExceptionHandler old = ueh;
1473 >        if (h != old) {
1474              ueh = h;
1475              ForkJoinWorkerThread[] ws = workers;
1476 <            if (ws != null) {
1477 <                for (int i = 0; i < ws.length; ++i) {
1478 <                    ForkJoinWorkerThread w = ws[i];
1479 <                    if (w != null)
1480 <                        w.setUncaughtExceptionHandler(h);
743 <                }
1476 >            int nws = ws.length;
1477 >            for (int i = 0; i < nws; ++i) {
1478 >                ForkJoinWorkerThread w = ws[i];
1479 >                if (w != null)
1480 >                    w.setUncaughtExceptionHandler(h);
1481              }
745        } finally {
746            lock.unlock();
1482          }
1483          return old;
1484      }
1485  
751
1486      /**
1487       * Sets the target parallelism level of this pool.
1488       *
# Line 764 | Line 1498 | public class ForkJoinPool extends Abstra
1498          checkPermission();
1499          if (parallelism <= 0 || parallelism > maxPoolSize)
1500              throw new IllegalArgumentException();
1501 <        final ReentrantLock lock = this.workerLock;
1502 <        lock.lock();
1503 <        try {
1504 <            if (isProcessingTasks()) {
1505 <                int p = this.parallelism;
1506 <                this.parallelism = parallelism;
1507 <                if (parallelism > p)
1508 <                    createAndStartAddedWorkers();
1509 <                else
1510 <                    trimSpares();
1501 >        workerCountReadFence();
1502 >        int pc = this.parallelism;
1503 >        if (pc != parallelism) {
1504 >            this.parallelism = parallelism;
1505 >            workerCountWriteFence();
1506 >            // Release spares. If too many, some will die after re-suspend
1507 >            ForkJoinWorkerThread[] ws = workers;
1508 >            int nws = ws.length;
1509 >            for (int i = 0; i < nws; ++i) {
1510 >                ForkJoinWorkerThread w = ws[i];
1511 >                if (w != null && w.tryUnsuspend()) {
1512 >                    int c;
1513 >                    do {} while (!UNSAFE.compareAndSwapInt
1514 >                                 (this, workerCountsOffset,
1515 >                                  c = workerCounts, c + ONE_RUNNING));
1516 >                    LockSupport.unpark(w);
1517 >                }
1518              }
1519 <        } finally {
1520 <            lock.unlock();
1519 >            ensureEnoughTotalWorkers();
1520 >            advanceEventCount();
1521 >            releaseWaiters(); // force config recheck by existing workers
1522          }
781        signalIdleWorkers();
1523      }
1524  
1525      /**
# Line 787 | Line 1528 | public class ForkJoinPool extends Abstra
1528       * @return the targeted parallelism level of this pool
1529       */
1530      public int getParallelism() {
1531 +        //        workerCountReadFence(); // inlined below
1532 +        int ignore = workerCounts;
1533          return parallelism;
1534      }
1535  
# Line 799 | Line 1542 | public class ForkJoinPool extends Abstra
1542       * @return the number of worker threads
1543       */
1544      public int getPoolSize() {
1545 <        return totalCountOf(workerCounts);
1545 >        return workerCounts >>> TOTAL_COUNT_SHIFT;
1546      }
1547  
1548      /**
# Line 811 | Line 1554 | public class ForkJoinPool extends Abstra
1554       * @return the maximum
1555       */
1556      public int getMaximumPoolSize() {
1557 +        workerCountReadFence();
1558          return maxPoolSize;
1559      }
1560  
# Line 819 | Line 1563 | public class ForkJoinPool extends Abstra
1563       * pool. The given value should normally be greater than or equal
1564       * to the {@link #getParallelism parallelism} level. Setting this
1565       * value has no effect on current pool size. It controls
1566 <     * construction of new threads.
1566 >     * construction of new threads. The use of this method may cause
1567 >     * tasks that intrinsically require extra threads for dependent
1568 >     * computations to indefinitely stall. If you are instead trying
1569 >     * to minimize internal thread creation, consider setting {@link
1570 >     * #setMaintainsParallelism} as false.
1571       *
1572       * @throws IllegalArgumentException if negative or greater than
1573       * internal implementation limit
# Line 828 | Line 1576 | public class ForkJoinPool extends Abstra
1576          if (newMax < 0 || newMax > MAX_THREADS)
1577              throw new IllegalArgumentException();
1578          maxPoolSize = newMax;
1579 +        workerCountWriteFence();
1580      }
1581  
833
1582      /**
1583       * Returns {@code true} if this pool dynamically maintains its
1584       * target parallelism level. If false, new threads are added only
# Line 839 | Line 1587 | public class ForkJoinPool extends Abstra
1587       * @return {@code true} if maintains parallelism
1588       */
1589      public boolean getMaintainsParallelism() {
1590 +        workerCountReadFence();
1591          return maintainsParallelism;
1592      }
1593  
# Line 851 | Line 1600 | public class ForkJoinPool extends Abstra
1600       */
1601      public void setMaintainsParallelism(boolean enable) {
1602          maintainsParallelism = enable;
1603 +        workerCountWriteFence();
1604      }
1605  
1606      /**
# Line 867 | Line 1617 | public class ForkJoinPool extends Abstra
1617       * @see #getAsyncMode
1618       */
1619      public boolean setAsyncMode(boolean async) {
1620 +        workerCountReadFence();
1621          boolean oldMode = locallyFifo;
1622 <        locallyFifo = async;
1623 <        ForkJoinWorkerThread[] ws = workers;
1624 <        if (ws != null) {
1625 <            for (int i = 0; i < ws.length; ++i) {
1626 <                ForkJoinWorkerThread t = ws[i];
1627 <                if (t != null)
1628 <                    t.setAsyncMode(async);
1622 >        if (oldMode != async) {
1623 >            locallyFifo = async;
1624 >            workerCountWriteFence();
1625 >            ForkJoinWorkerThread[] ws = workers;
1626 >            int nws = ws.length;
1627 >            for (int i = 0; i < nws; ++i) {
1628 >                ForkJoinWorkerThread w = ws[i];
1629 >                if (w != null)
1630 >                    w.setAsyncMode(async);
1631              }
1632          }
1633          return oldMode;
# Line 888 | Line 1641 | public class ForkJoinPool extends Abstra
1641       * @see #setAsyncMode
1642       */
1643      public boolean getAsyncMode() {
1644 +        workerCountReadFence();
1645          return locallyFifo;
1646      }
1647  
1648      /**
1649       * Returns an estimate of the number of worker threads that are
1650       * not blocked waiting to join tasks or for other managed
1651 <     * synchronization.
1651 >     * synchronization. This method may overestimate the
1652 >     * number of running threads.
1653       *
1654       * @return the number of worker threads
1655       */
1656      public int getRunningThreadCount() {
1657 <        return runningCountOf(workerCounts);
1657 >        return workerCounts & RUNNING_COUNT_MASK;
1658      }
1659  
1660      /**
# Line 910 | Line 1665 | public class ForkJoinPool extends Abstra
1665       * @return the number of active threads
1666       */
1667      public int getActiveThreadCount() {
1668 <        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;
1668 >        return runState & ACTIVE_COUNT_MASK;
1669      }
1670  
1671      /**
# Line 937 | Line 1680 | public class ForkJoinPool extends Abstra
1680       * @return {@code true} if all threads are currently idle
1681       */
1682      public boolean isQuiescent() {
1683 <        return activeCountOf(runControl) == 0;
1683 >        return (runState & ACTIVE_COUNT_MASK) == 0;
1684      }
1685  
1686      /**
# Line 952 | Line 1695 | public class ForkJoinPool extends Abstra
1695       * @return the number of steals
1696       */
1697      public long getStealCount() {
1698 <        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);
1698 >        return stealCount;
1699      }
1700  
1701      /**
# Line 978 | Line 1711 | public class ForkJoinPool extends Abstra
1711      public long getQueuedTaskCount() {
1712          long count = 0;
1713          ForkJoinWorkerThread[] ws = workers;
1714 <        if (ws != null) {
1715 <            for (int i = 0; i < ws.length; ++i) {
1716 <                ForkJoinWorkerThread t = ws[i];
1717 <                if (t != null)
1718 <                    count += t.getQueueSize();
986 <            }
1714 >        int nws = ws.length;
1715 >        for (int i = 0; i < nws; ++i) {
1716 >            ForkJoinWorkerThread w = ws[i];
1717 >            if (w != null)
1718 >                count += w.getQueueSize();
1719          }
1720          return count;
1721      }
# Line 1040 | Line 1772 | public class ForkJoinPool extends Abstra
1772      protected int drainTasksTo(Collection<? super ForkJoinTask<?>> c) {
1773          int n = submissionQueue.drainTo(c);
1774          ForkJoinWorkerThread[] ws = workers;
1775 <        if (ws != null) {
1776 <            for (int i = 0; i < ws.length; ++i) {
1777 <                ForkJoinWorkerThread w = ws[i];
1778 <                if (w != null)
1779 <                    n += w.drainTasksTo(c);
1048 <            }
1775 >        int nws = ws.length;
1776 >        for (int i = 0; i < nws; ++i) {
1777 >            ForkJoinWorkerThread w = ws[i];
1778 >            if (w != null)
1779 >                n += w.drainTasksTo(c);
1780          }
1781          return n;
1782      }
# Line 1058 | Line 1789 | public class ForkJoinPool extends Abstra
1789       * @return a string identifying this pool, as well as its state
1790       */
1791      public String toString() {
1061        int ps = parallelism;
1062        int wc = workerCounts;
1063        int rc = runControl;
1792          long st = getStealCount();
1793          long qt = getQueuedTaskCount();
1794          long qs = getQueuedSubmissionCount();
1795 +        int wc = workerCounts;
1796 +        int tc = wc >>> TOTAL_COUNT_SHIFT;
1797 +        int rc = wc & RUNNING_COUNT_MASK;
1798 +        int pc = parallelism;
1799 +        int rs = runState;
1800 +        int ac = rs & ACTIVE_COUNT_MASK;
1801          return super.toString() +
1802 <            "[" + runStateToString(runStateOf(rc)) +
1803 <            ", parallelism = " + ps +
1804 <            ", size = " + totalCountOf(wc) +
1805 <            ", active = " + activeCountOf(rc) +
1806 <            ", running = " + runningCountOf(wc) +
1802 >            "[" + runLevelToString(rs) +
1803 >            ", parallelism = " + pc +
1804 >            ", size = " + tc +
1805 >            ", active = " + ac +
1806 >            ", running = " + rc +
1807              ", steals = " + st +
1808              ", tasks = " + qt +
1809              ", submissions = " + qs +
1810              "]";
1811      }
1812  
1813 <    private static String runStateToString(int rs) {
1814 <        switch(rs) {
1815 <        case RUNNING: return "Running";
1816 <        case SHUTDOWN: return "Shutting down";
1817 <        case TERMINATING: return "Terminating";
1084 <        case TERMINATED: return "Terminated";
1085 <        default: throw new Error("Unknown run state");
1086 <        }
1813 >    private static String runLevelToString(int s) {
1814 >        return ((s & TERMINATED) != 0 ? "Terminated" :
1815 >                ((s & TERMINATING) != 0 ? "Terminating" :
1816 >                 ((s & SHUTDOWN) != 0 ? "Shutting down" :
1817 >                  "Running")));
1818      }
1819  
1089    // lifecycle control
1090
1820      /**
1821       * Initiates an orderly shutdown in which previously submitted
1822       * tasks are executed, but no new tasks will be accepted.
# Line 1102 | Line 1831 | public class ForkJoinPool extends Abstra
1831       */
1832      public void shutdown() {
1833          checkPermission();
1834 <        transitionRunStateTo(SHUTDOWN);
1835 <        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 <        }
1834 >        advanceRunLevel(SHUTDOWN);
1835 >        tryTerminate(false);
1836      }
1837  
1838      /**
# Line 1139 | Line 1853 | public class ForkJoinPool extends Abstra
1853       */
1854      public List<Runnable> shutdownNow() {
1855          checkPermission();
1856 <        terminate();
1856 >        tryTerminate(true);
1857          return Collections.emptyList();
1858      }
1859  
# Line 1149 | Line 1863 | public class ForkJoinPool extends Abstra
1863       * @return {@code true} if all tasks have completed following shut down
1864       */
1865      public boolean isTerminated() {
1866 <        return runStateOf(runControl) == TERMINATED;
1866 >        return runState >= TERMINATED;
1867      }
1868  
1869      /**
# Line 1163 | Line 1877 | public class ForkJoinPool extends Abstra
1877       * @return {@code true} if terminating but not yet terminated
1878       */
1879      public boolean isTerminating() {
1880 <        return runStateOf(runControl) == TERMINATING;
1880 >        return (runState & (TERMINATING|TERMINATED)) == TERMINATING;
1881      }
1882  
1883      /**
# Line 1172 | Line 1886 | public class ForkJoinPool extends Abstra
1886       * @return {@code true} if this pool has been shut down
1887       */
1888      public boolean isShutdown() {
1889 <        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;
1889 >        return runState >= SHUTDOWN;
1890      }
1891  
1892      /**
# Line 1196 | Line 1902 | public class ForkJoinPool extends Abstra
1902       */
1903      public boolean awaitTermination(long timeout, TimeUnit unit)
1904          throws InterruptedException {
1905 <        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();
1229 <        try {
1230 <            ForkJoinWorkerThread[] ws = workers;
1231 <            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)
1537 <            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 <            }
1778 <        }
1905 >        return terminationLatch.await(timeout, unit);
1906      }
1907  
1908      /**
# Line 1858 | Line 1985 | public class ForkJoinPool extends Abstra
1985                                      boolean maintainParallelism)
1986          throws InterruptedException {
1987          Thread t = Thread.currentThread();
1988 <        ForkJoinPool pool = ((t instanceof ForkJoinWorkerThread) ?
1989 <                             ((ForkJoinWorkerThread) t).pool : null);
1990 <        if (!blocker.isReleasable()) {
1991 <            try {
1992 <                if (pool == null ||
1866 <                    !pool.preBlock(blocker, maintainParallelism))
1867 <                    awaitBlocker(blocker);
1868 <            } finally {
1869 <                if (pool != null)
1870 <                    pool.updateRunningCount(1);
1871 <            }
1872 <        }
1988 >        if (t instanceof ForkJoinWorkerThread)
1989 >            ((ForkJoinWorkerThread) t).pool.
1990 >                awaitBlocker(blocker, maintainParallelism);
1991 >        else
1992 >            awaitBlocker(blocker);
1993      }
1994  
1995 +    /**
1996 +     * Performs Non-FJ blocking
1997 +     */
1998      private static void awaitBlocker(ManagedBlocker blocker)
1999          throws InterruptedException {
2000          do {} while (!blocker.isReleasable() && !blocker.block());
# Line 1892 | Line 2015 | public class ForkJoinPool extends Abstra
2015      // Unsafe mechanics
2016  
2017      private static final sun.misc.Unsafe UNSAFE = getUnsafe();
1895    private static final long eventCountOffset =
1896        objectFieldOffset("eventCount", ForkJoinPool.class);
2018      private static final long workerCountsOffset =
2019          objectFieldOffset("workerCounts", ForkJoinPool.class);
2020 <    private static final long runControlOffset =
2021 <        objectFieldOffset("runControl", ForkJoinPool.class);
2022 <    private static final long syncStackOffset =
2023 <        objectFieldOffset("syncStack",ForkJoinPool.class);
2024 <    private static final long spareStackOffset =
2025 <        objectFieldOffset("spareStack", ForkJoinPool.class);
2026 <
2027 <    private boolean casEventCount(long cmp, long val) {
2028 <        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 <    }
2020 >    private static final long runStateOffset =
2021 >        objectFieldOffset("runState", ForkJoinPool.class);
2022 >    private static final long eventCountOffset =
2023 >        objectFieldOffset("eventCount", ForkJoinPool.class);
2024 >    private static final long eventWaitersOffset =
2025 >        objectFieldOffset("eventWaiters",ForkJoinPool.class);
2026 >    private static final long stealCountOffset =
2027 >        objectFieldOffset("stealCount",ForkJoinPool.class);
2028 >
2029  
2030      private static long objectFieldOffset(String field, Class<?> klazz) {
2031          try {

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines