ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinPool.java
(Generate patch)

Comparing jsr166/src/main/java/util/concurrent/ForkJoinPool.java (file contents):
Revision 1.13 by dl, Sat Dec 5 11:43:01 2009 UTC vs.
Revision 1.14 by dl, Mon Apr 5 16:05:09 2010 UTC

# Line 11 | Line 11 | import java.util.Arrays;
11   import java.util.Collection;
12   import java.util.Collections;
13   import java.util.List;
14 import java.util.concurrent.locks.Condition;
14   import java.util.concurrent.locks.LockSupport;
15   import java.util.concurrent.locks.ReentrantLock;
16   import java.util.concurrent.atomic.AtomicInteger;
17 < import java.util.concurrent.atomic.AtomicLong;
17 > import java.util.concurrent.CountDownLatch;
18  
19   /**
20   * An {@link ExecutorService} for running {@link ForkJoinTask}s.
# Line 51 | Line 50 | import java.util.concurrent.atomic.Atomi
50   * ({@link #setParallelism}). The total number of threads may be
51   * limited using method {@link #setMaximumPoolSize}, in which case it
52   * may become possible for the activities of a pool to stall due to
53 < * the lack of available threads to process new tasks.
53 > * the lack of available threads to process new tasks. When the pool
54 > * is executing tasks, these and other configuration setting methods
55 > * may only gradually affect actual pool sizes. It is normally best
56 > * practice to invoke these methods only when the pool is known to be
57 > * quiescent.
58   *
59   * <p>In addition to execution and lifecycle control methods, this
60   * class provides status check methods (for example
# Line 92 | Line 95 | import java.util.concurrent.atomic.Atomi
95   public class ForkJoinPool extends AbstractExecutorService {
96  
97      /*
98 <     * See the extended comments interspersed below for design,
99 <     * rationale, and walkthroughs.
98 >     * Implementation Overview
99 >     *
100 >     * This class provides the central bookkeeping and control for a
101 >     * set of worker threads: Submissions from non-FJ threads enter
102 >     * into a submission queue. Workers take these tasks and typically
103 >     * split them into subtasks that may be stolen by other workers.
104 >     * The main work-stealing mechanics implemented in class
105 >     * ForkJoinWorkerThread give first priority to processing tasks
106 >     * from their own queues (LIFO or FIFO, depending on mode), then
107 >     * to randomized FIFO steals of tasks in other worker queues, and
108 >     * lastly to new submissions. These mechanics do not consider
109 >     * affinities, loads, cache localities, etc, so rarely provide the
110 >     * best possible performance on a given machine, but portably
111 >     * provide good throughput by averaging over these factors.
112 >     * (Further, even if we did try to use such information, we do not
113 >     * usually have a basis for exploiting it. For example, some sets
114 >     * of tasks profit from cache affinities, but others are harmed by
115 >     * cache pollution effects.)
116 >     *
117 >     * The main throughput advantages of work-stealing stem from
118 >     * decentralized control -- workers mostly steal tasks from each
119 >     * other. We do not want to negate this by creating bottlenecks
120 >     * implementing the management responsibilities of this class. So
121 >     * we use a collection of techniques that avoid, reduce, or cope
122 >     * well with contention. These entail several instances of
123 >     * bit-packing into CASable fields to maintain only the minimally
124 >     * required atomicity. To enable such packing, we restrict maximum
125 >     * parallelism to (1<<15)-1 (enabling twice this to fit into a 16
126 >     * bit field), which is far in excess of normal operating range.
127 >     * Even though updates to some of these bookkeeping fields do
128 >     * sometimes contend with each other, they don't normally
129 >     * cache-contend with updates to others enough to warrant memory
130 >     * padding or isolation. So they are all held as fields of
131 >     * ForkJoinPool objects.  The main capabilities are as follows:
132 >     *
133 >     * 1. Creating and removing workers. Workers are recorded in the
134 >     * "workers" array. This is an array as opposed to some other data
135 >     * structure to support index-based random steals by workers.
136 >     * Updates to the array recording new workers and unrecording
137 >     * terminated ones are protected from each other by a lock
138 >     * (workerLock) but the array is otherwise concurrently readable,
139 >     * and accessed directly by workers. To simplify index-based
140 >     * operations, the array size is always a power of two, and all
141 >     * readers must tolerate null slots. Currently, all but the first
142 >     * worker thread creation is on-demand, triggered by task
143 >     * submissions, replacement of terminated workers, and/or
144 >     * compensation for blocked workers. However, all other support
145 >     * code is set up to work with other policies.
146 >     *
147 >     * 2. Bookkeeping for dynamically adding and removing workers. We
148 >     * maintain a given level of parallelism (or, if
149 >     * maintainsParallelism is false, at least avoid starvation). When
150 >     * some workers are known to be blocked (on joins or via
151 >     * ManagedBlocker), we may create or resume others to take their
152 >     * place until they unblock (see below). Implementing this
153 >     * requires counts of the number of "running" threads (i.e., those
154 >     * that are neither blocked nor artifically suspended) as well as
155 >     * the total number.  These two values are packed into one field,
156 >     * "workerCounts" because we need accurate snapshots when deciding
157 >     * to create, resume or suspend.  To support these decisions,
158 >     * updates must be prospective (not retrospective).  For example,
159 >     * the running count is decremented before blocking by a thread
160 >     * about to block, but incremented by the thread about to unblock
161 >     * it. (In a few cases, these prospective updates may need to be
162 >     * rolled back, for example when deciding to create a new worker
163 >     * but the thread factory fails or returns null. In these cases,
164 >     * we are no worse off wrt other decisions than we would be
165 >     * otherwise.)  Updates to the workerCounts field sometimes
166 >     * transiently encounter a fair amount of contention when join
167 >     * dependencies are such that many threads block or unblock at
168 >     * about the same time. We alleviate this by sometimes bundling
169 >     * updates (for example blocking one thread on join and resuming a
170 >     * spare cancel each other out), and in most other cases
171 >     * performing an alternative action (like releasing waiters and
172 >     * finding spares; see below) as a more productive form of
173 >     * backoff.
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 preJoin and doBlock look for
240 >     * suspended threads to resume before considering creating a new
241 >     * replacement. We don't need a special data structure to maintain
242 >     * 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 preJoin and doBlock. We always need to create one
262 >     * when the number of running threads becomes zero. But because
263 >     * blocked joins are typically dependent, we don't necessarily
264 >     * need or want one-to-one replacement. Using a one-to-one
265 >     * compensation rule often leads to enough useless overhead
266 >     * creating, suspending, resuming, and/or killing threads to
267 >     * signficantly degrade throughput.  We use a rule reflecting the
268 >     * idea that, the more spare threads you already have, the more
269 >     * evidence you need to create another one; where "evidence" is
270 >     * expressed as the current deficit -- target minus running
271 >     * threads. To reduce flickering and drift around target values,
272 >     * the relation is quadratic: adding a spare if (dc*dc)>=(sc*pc)
273 >     * (where dc is deficit, sc is number of spare threads and pc is
274 >     * target parallelism.)  This effectively reduces churn at the
275 >     * price of systematically undershooting target parallelism when
276 >     * many threads are blocked.  However, biasing toward undeshooting
277 >     * partially compensates for the above mechanics to suspend extra
278 >     * threads, that normally lead to overshoot because we can only
279 >     * suspend workers in-between top-level actions. It also better
280 >     * copes with the fact that some of the methods in this class tend
281 >     * to never become compiled (but are interpreted), so some
282 >     * components of the entire set of controls might execute many
283 >     * times faster than others. And similarly for cases where the
284 >     * apparent lack of work is just due to GC stalls and other
285 >     * transient system activity.
286 >     *
287 >     * 7. Maintaining other configuration parameters and monitoring
288 >     * statistics. Updates to fields controlling parallelism level,
289 >     * max size, etc can only meaningfully take effect for individual
290 >     * threads upon their next top-level actions; i.e., between
291 >     * stealing/running tasks/submission, which are separated by calls
292 >     * to preStep.  Memory ordering for these (assumed infrequent)
293 >     * reconfiguration calls is ensured by using reads and writes to
294 >     * volatile field workerCounts (that must be read in preStep anyway)
295 >     * as "fences" -- user-level reads are preceded by reads of
296 >     * workCounts, and writes are followed by no-op CAS to
297 >     * workerCounts. The values reported by other management and
298 >     * monitoring methods are either computed on demand, or are kept
299 >     * in fields that are only updated when threads are otherwise
300 >     * idle.
301 >     *
302 >     * Beware that there is a lot of representation-level coupling
303 >     * among classes ForkJoinPool, ForkJoinWorkerThread, and
304 >     * ForkJoinTask.  For example, direct access to "workers" array by
305 >     * workers, and direct access to ForkJoinTask.status by both
306 >     * ForkJoinPool and ForkJoinWorkerThread.  There is little point
307 >     * trying to reduce this, since any associated future changes in
308 >     * representations will need to be accompanied by algorithmic
309 >     * changes anyway.
310 >     *
311 >     * Style notes: There are lots of inline assignments (of form
312 >     * "while ((local = field) != 0)") which are usually the simplest
313 >     * way to ensure read orderings. Also several occurrences of the
314 >     * unusual "do {} while(!cas...)" which is the simplest way to
315 >     * force an update of a CAS'ed variable. There are also a few
316 >     * other coding oddities that help some methods perform reasonably
317 >     * even when interpreted (not compiled).
318 >     *
319 >     * The order of declarations in this file is: (1) statics (2)
320 >     * fields (along with constants used when unpacking some of them)
321 >     * (3) internal control methods (4) callbacks and other support
322 >     * for ForkJoinTask and ForkJoinWorkerThread classes, (5) exported
323 >     * methods (plus a few little helpers).
324       */
325  
99    /** Mask for packing and unpacking shorts */
100    private static final int  shortMask = 0xffff;
101
102    /** Max pool size -- must be a power of two minus 1 */
103    private static final int MAX_THREADS =  0x7FFF;
104
326      /**
327       * Factory for creating new {@link ForkJoinWorkerThread}s.
328       * A {@code ForkJoinWorkerThreadFactory} must be defined and used
# Line 125 | Line 346 | public class ForkJoinPool extends Abstra
346      static class  DefaultForkJoinWorkerThreadFactory
347          implements ForkJoinWorkerThreadFactory {
348          public ForkJoinWorkerThread newThread(ForkJoinPool pool) {
349 <            try {
129 <                return new ForkJoinWorkerThread(pool);
130 <            } catch (OutOfMemoryError oom)  {
131 <                return null;
132 <            }
349 >            return new ForkJoinWorkerThread(pool);
350          }
351      }
352  
# Line 165 | Line 382 | public class ForkJoinPool extends Abstra
382          new AtomicInteger();
383  
384      /**
385 <     * Array holding all worker threads in the pool. Initialized upon
386 <     * first use. Array size must be a power of two.  Updates and
387 <     * replacements are protected by workerLock, but it is always kept
388 <     * in a consistent enough state to be randomly accessed without
389 <     * locking by workers performing work-stealing.
385 >     * Absolute bound for parallelism level. Twice this number must
386 >     * fit into a 16bit field to enable word-packing for some counts.
387 >     */
388 >    private static final int MAX_THREADS = 0x7fff;
389 >
390 >    /**
391 >     * Array holding all worker threads in the pool.  Array size must
392 >     * be a power of two.  Updates and replacements are protected by
393 >     * workerLock, but the array is always kept in a consistent enough
394 >     * state to be randomly accessed without locking by workers
395 >     * performing work-stealing, as well as other traversal-based
396 >     * methods in this class. All readers must tolerate that some
397 >     * array slots may be null.
398       */
399      volatile ForkJoinWorkerThread[] workers;
400  
401      /**
402 <     * Lock protecting access to workers.
402 >     * Queue for external submissions.
403       */
404 <    private final ReentrantLock workerLock;
404 >    private final LinkedTransferQueue<ForkJoinTask<?>> submissionQueue;
405  
406      /**
407 <     * Condition for awaitTermination.
407 >     * Lock protecting updates to workers array.
408       */
409 <    private final Condition termination;
409 >    private final ReentrantLock workerLock;
410  
411      /**
412 <     * The uncaught exception handler used when any worker
188 <     * abruptly terminates
412 >     * Latch released upon termination.
413       */
414 <    private Thread.UncaughtExceptionHandler ueh;
414 >    private final CountDownLatch terminationLatch;
415  
416      /**
417       * Creation factory for worker threads.
# Line 195 | Line 419 | public class ForkJoinPool extends Abstra
419      private final ForkJoinWorkerThreadFactory factory;
420  
421      /**
422 <     * Head of stack of threads that were created to maintain
423 <     * parallelism when other threads blocked, but have since
200 <     * suspended when the parallelism level rose.
422 >     * Sum of per-thread steal counts, updated only when threads are
423 >     * idle or terminating.
424       */
425 <    private volatile WaitQueueNode spareStack;
425 >    private volatile long stealCount;
426  
427      /**
428 <     * Sum of per-thread steal counts, updated only when threads are
429 <     * idle or terminating.
428 >     * Encoded record of top of treiber stack of threads waiting for
429 >     * events. The top 32 bits contain the count being waited for. The
430 >     * bottom word contains one plus the pool index of waiting worker
431 >     * thread.
432       */
433 <    private final AtomicLong stealCount;
433 >    private volatile long eventWaiters;
434 >
435 >    private static final int  EVENT_COUNT_SHIFT = 32;
436 >    private static final long WAITER_INDEX_MASK = (1L << EVENT_COUNT_SHIFT)-1L;
437  
438      /**
439 <     * Queue for external submissions.
439 >     * A counter for events that may wake up worker threads:
440 >     *   - Submission of a new task to the pool
441 >     *   - A worker pushing a task on an empty queue
442 >     *   - termination and reconfiguration
443       */
444 <    private final LinkedTransferQueue<ForkJoinTask<?>> submissionQueue;
444 >    private volatile int eventCount;
445 >
446 >    /**
447 >     * Lifecycle control. The low word contains the number of workers
448 >     * that are (probably) executing tasks. This value is atomically
449 >     * incremented before a worker gets a task to run, and decremented
450 >     * when worker has no tasks and cannot find any.  Bits 16-18
451 >     * contain runLevel value. When all are zero, the pool is
452 >     * running. Level transitions are monotonic (running -> shutdown
453 >     * -> terminating -> terminated) so each transition adds a bit.
454 >     * These are bundled together to ensure consistent read for
455 >     * termination checks (i.e., that runLevel is at least SHUTDOWN
456 >     * and active threads is zero).
457 >     */
458 >    private volatile int runState;
459 >
460 >    // Note: The order among run level values matters.
461 >    private static final int RUNLEVEL_SHIFT     = 16;
462 >    private static final int SHUTDOWN           = 1 << RUNLEVEL_SHIFT;
463 >    private static final int TERMINATING        = 1 << (RUNLEVEL_SHIFT + 1);
464 >    private static final int TERMINATED         = 1 << (RUNLEVEL_SHIFT + 2);
465 >    private static final int ACTIVE_COUNT_MASK  = (1 << RUNLEVEL_SHIFT) - 1;
466 >    private static final int ONE_ACTIVE         = 1; // active update delta
467  
468      /**
469 <     * Head of Treiber stack for barrier sync. See below for explanation.
469 >     * Holds number of total (i.e., created and not yet terminated)
470 >     * and running (i.e., not blocked on joins or other managed sync)
471 >     * threads, packed together to ensure consistent snapshot when
472 >     * making decisions about creating and suspending spare
473 >     * threads. Updated only by CAS. Note that adding a new worker
474 >     * requires incrementing both counts, since workers start off in
475 >     * running state.  This field is also used for memory-fencing
476 >     * configuration parameters.
477 >     */
478 >    private volatile int workerCounts;
479 >
480 >    private static final int TOTAL_COUNT_SHIFT  = 16;
481 >    private static final int RUNNING_COUNT_MASK = (1 << TOTAL_COUNT_SHIFT) - 1;
482 >    private static final int ONE_RUNNING        = 1;
483 >    private static final int ONE_TOTAL          = 1 << TOTAL_COUNT_SHIFT;
484 >
485 >    /*
486 >     * Fields parallelism. maxPoolSize, locallyFifo,
487 >     * maintainsParallelism, and ueh are non-volatile, but external
488 >     * reads/writes use workerCount fences to ensure visability.
489       */
218    private volatile WaitQueueNode syncStack;
490  
491      /**
492 <     * The count for event barrier
492 >     * The target parallelism level.
493       */
494 <    private volatile long eventCount;
494 >    private int parallelism;
495  
496      /**
497 <     * Pool number, just for assigning useful names to worker threads
497 >     * The maximum allowed pool size.
498       */
499 <    private final int poolNumber;
499 >    private int maxPoolSize;
500  
501      /**
502 <     * The maximum allowed pool size
502 >     * True if use local fifo, not default lifo, for local polling
503 >     * Replicated by ForkJoinWorkerThreads
504       */
505 <    private volatile int maxPoolSize;
505 >    private boolean locallyFifo;
506  
507      /**
508 <     * The desired parallelism level, updated only under workerLock.
508 >     * Controls whether to add spares to maintain parallelism
509       */
510 <    private volatile int parallelism;
510 >    private boolean maintainsParallelism;
511  
512      /**
513 <     * True if use local fifo, not default lifo, for local polling
513 >     * The uncaught exception handler used when any worker
514 >     * abruptly terminates
515       */
516 <    private volatile boolean locallyFifo;
516 >    private Thread.UncaughtExceptionHandler ueh;
517  
518      /**
519 <     * Holds number of total (i.e., created and not yet terminated)
247 <     * and running (i.e., not blocked on joins or other managed sync)
248 <     * threads, packed into one int to ensure consistent snapshot when
249 <     * making decisions about creating and suspending spare
250 <     * threads. Updated only by CAS.  Note: CASes in
251 <     * updateRunningCount and preJoin assume that running active count
252 <     * is in low word, so need to be modified if this changes.
519 >     * Pool number, just for assigning useful names to worker threads
520       */
521 <    private volatile int workerCounts;
521 >    private final int poolNumber;
522  
523 <    private static int totalCountOf(int s)           { return s >>> 16;  }
257 <    private static int runningCountOf(int s)         { return s & shortMask; }
258 <    private static int workerCountsFor(int t, int r) { return (t << 16) + r; }
523 >    // utilities for updating fields
524  
525      /**
526 <     * Adds delta (which may be negative) to running count.  This must
262 <     * be called before (with negative arg) and after (with positive)
263 <     * any managed synchronization (i.e., mainly, joins).
526 >     * Adds delta to running count.  Used mainly by ForkJoinTask.
527       *
528       * @param delta the number to add
529       */
530      final void updateRunningCount(int delta) {
531 <        int s;
532 <        do {} while (!casWorkerCounts(s = workerCounts, s + delta));
531 >        int wc;
532 >        do {} while (!UNSAFE.compareAndSwapInt(this, workerCountsOffset,
533 >                                               wc = workerCounts,
534 >                                               wc + delta));
535      }
536  
537      /**
538 <     * Adds delta (which may be negative) to both total and running
539 <     * count.  This must be called upon creation and termination of
275 <     * worker threads.
276 <     *
277 <     * @param delta the number to add
538 >     * Write fence for user modifications of pool parameters
539 >     * (parallelism. etc).  Note that it doesn't matter if CAS fails.
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 >    private void workerCountWriteFence() {
542 >        int wc;
543 >        UNSAFE.compareAndSwapInt(this, workerCountsOffset,
544 >                                 wc = workerCounts, wc);
545      }
546  
547      /**
548 <     * Lifecycle control. High word contains runState, low word
549 <     * contains the number of workers that are (probably) executing
550 <     * tasks. This value is atomically incremented before a worker
551 <     * gets a task to run, and decremented when worker has no tasks
552 <     * and cannot find any. These two fields are bundled together to
553 <     * support correct termination triggering.  Note: activeCount
292 <     * CAS'es cheat by assuming active count is in low word, so need
293 <     * to be modified if this changes
294 <     */
295 <    private volatile int runControl;
296 <
297 <    // RunState values. Order among values matters
298 <    private static final int RUNNING     = 0;
299 <    private static final int SHUTDOWN    = 1;
300 <    private static final int TERMINATING = 2;
301 <    private static final int TERMINATED  = 3;
302 <
303 <    private static int runStateOf(int c)             { return c >>> 16; }
304 <    private static int activeCountOf(int c)          { return c & shortMask; }
305 <    private static int runControlFor(int r, int a)   { return (r << 16) + a; }
548 >     * Read fence for external reads of pool parameters
549 >     * (parallelism. maxPoolSize, etc).
550 >     */
551 >    private void workerCountReadFence() {
552 >        int ignore = workerCounts;
553 >    }
554  
555      /**
556       * Tries incrementing active count; fails on contention.
557 <     * Called by workers before/during executing tasks.
557 >     * Called by workers before executing tasks.
558       *
559       * @return true on success
560       */
561      final boolean tryIncrementActiveCount() {
562 <        int c = runControl;
563 <        return casRunControl(c, c+1);
562 >        int c;
563 >        return UNSAFE.compareAndSwapInt(this, runStateOffset,
564 >                                        c = runState, c + ONE_ACTIVE);
565      }
566  
567      /**
568       * Tries decrementing active count; fails on contention.
569 <     * Possibly triggers termination on success.
321 <     * Called by workers when they can't find tasks.
322 <     *
323 <     * @return true on success
569 >     * Called when workers cannot find tasks to run.
570       */
571      final boolean tryDecrementActiveCount() {
572 <        int c = runControl;
573 <        int nextc = c - 1;
574 <        if (!casRunControl(c, nextc))
572 >        int c;
573 >        return UNSAFE.compareAndSwapInt(this, runStateOffset,
574 >                                        c = runState, c - ONE_ACTIVE);
575 >    }
576 >
577 >    /**
578 >     * Advances to at least the given level. Returns true if not
579 >     * already in at least the given level.
580 >     */
581 >    private boolean advanceRunLevel(int level) {
582 >        for (;;) {
583 >            int s = runState;
584 >            if ((s & level) != 0)
585 >                return false;
586 >            if (UNSAFE.compareAndSwapInt(this, runStateOffset, s, s | level))
587 >                return true;
588 >        }
589 >    }
590 >
591 >    // workers array maintenance
592 >
593 >    /**
594 >     * Records and returns a workers array index for new worker.
595 >     */
596 >    private int recordWorker(ForkJoinWorkerThread w) {
597 >        // Try using slot totalCount-1. If not available, scan and/or resize
598 >        int k = (workerCounts >>> TOTAL_COUNT_SHIFT) - 1;
599 >        final ReentrantLock lock = this.workerLock;
600 >        lock.lock();
601 >        try {
602 >            ForkJoinWorkerThread[] ws = workers;
603 >            int len = ws.length;
604 >            if (k < 0 || k >= len || ws[k] != null) {
605 >                for (k = 0; k < len && ws[k] != null; ++k)
606 >                    ;
607 >                if (k == len)
608 >                    ws = Arrays.copyOf(ws, len << 1);
609 >            }
610 >            ws[k] = w;
611 >            workers = ws; // volatile array write ensures slot visibility
612 >        } finally {
613 >            lock.unlock();
614 >        }
615 >        return k;
616 >    }
617 >
618 >    /**
619 >     * Nulls out record of worker in workers array
620 >     */
621 >    private void forgetWorker(ForkJoinWorkerThread w) {
622 >        int idx = w.poolIndex;
623 >        // Locking helps method recordWorker avoid unecessary expansion
624 >        final ReentrantLock lock = this.workerLock;
625 >        lock.lock();
626 >        try {
627 >            ForkJoinWorkerThread[] ws = workers;
628 >            if (idx >= 0 && idx < ws.length && ws[idx] == w) // verify
629 >                ws[idx] = null;
630 >        } finally {
631 >            lock.unlock();
632 >        }
633 >    }
634 >
635 >    // adding and removing workers
636 >
637 >    /**
638 >     * Tries to create and add new worker. Assumes that worker counts
639 >     * are already updated to accommodate the worker, so adjusts on
640 >     * failure.
641 >     *
642 >     * @return new worker or null if creation failed
643 >     */
644 >    private ForkJoinWorkerThread addWorker() {
645 >        ForkJoinWorkerThread w = null;
646 >        try {
647 >            w = factory.newThread(this);
648 >        } finally { // Adjust on either null or exceptional factory return
649 >            if (w == null) {
650 >                onWorkerCreationFailure();
651 >                return null;
652 >            }
653 >        }
654 >        w.start(recordWorker(w), locallyFifo, ueh);
655 >        return w;
656 >    }
657 >
658 >    /**
659 >     * Adjusts counts upon failure to create worker
660 >     */
661 >    private void onWorkerCreationFailure() {
662 >        int c;
663 >        do {} while (!UNSAFE.compareAndSwapInt(this, workerCountsOffset,
664 >                                               c = workerCounts,
665 >                                               c - (ONE_RUNNING|ONE_TOTAL)));
666 >        tryTerminate(false); // in case of failure during shutdown
667 >    }
668 >
669 >    /**
670 >     * Create enough total workers to establish target parallelism,
671 >     * giving up if terminating or addWorker fails
672 >     */
673 >    private void ensureEnoughTotalWorkers() {
674 >        int wc;
675 >        while (runState < TERMINATING &&
676 >               ((wc = workerCounts) >>> TOTAL_COUNT_SHIFT) < parallelism) {
677 >            if ((UNSAFE.compareAndSwapInt(this, workerCountsOffset,
678 >                                          wc, wc + (ONE_RUNNING|ONE_TOTAL)) &&
679 >                 addWorker() == null))
680 >                break;
681 >        }
682 >    }
683 >
684 >    /**
685 >     * Final callback from terminating worker.  Removes record of
686 >     * worker from array, and adjusts counts. If pool is shutting
687 >     * down, tries to complete terminatation, else possibly replaces
688 >     * the worker.
689 >     *
690 >     * @param w the worker
691 >     */
692 >    final void workerTerminated(ForkJoinWorkerThread w) {
693 >        if (w.active) { // force inactive
694 >            w.active = false;
695 >            do {} while (!tryDecrementActiveCount());
696 >        }
697 >        forgetWorker(w);
698 >
699 >        // decrement total count, and if was running, running count
700 >        int unit = w.isTrimmed()? ONE_TOTAL : (ONE_RUNNING|ONE_TOTAL);
701 >        int wc;
702 >        do {} while (!UNSAFE.compareAndSwapInt(this, workerCountsOffset,
703 >                                               wc = workerCounts, wc - unit));
704 >
705 >        accumulateStealCount(w); // collect final count
706 >        if (!tryTerminate(false))
707 >            ensureEnoughTotalWorkers();
708 >    }
709 >
710 >    // Waiting for and signalling events
711 >
712 >    /**
713 >     * Ensures eventCount on exit is different (mod 2^32) than on
714 >     * entry.  CAS failures are OK -- any change in count suffices.
715 >     */
716 >    private void advanceEventCount() {
717 >        int c;
718 >        UNSAFE.compareAndSwapInt(this, eventCountOffset, c = eventCount, c+1);
719 >    }
720 >
721 >    /**
722 >     * Releases workers blocked on a count not equal to current count.
723 >     */
724 >    final void releaseWaiters() {
725 >        long top;
726 >        int id;
727 >        while ((id = (int)((top = eventWaiters) & WAITER_INDEX_MASK)) > 0 &&
728 >               (int)(top >>> EVENT_COUNT_SHIFT) != eventCount) {
729 >            ForkJoinWorkerThread[] ws = workers;
730 >            ForkJoinWorkerThread w;
731 >            if (ws.length >= id && (w = ws[id - 1]) != null &&
732 >                UNSAFE.compareAndSwapLong(this, eventWaitersOffset,
733 >                                          top, w.nextWaiter))
734 >                LockSupport.unpark(w);
735 >        }
736 >    }
737 >
738 >    /**
739 >     * Advances eventCount and releases waiters until interference by
740 >     * other releasing threads is detected.
741 >     */
742 >    final void signalWork() {
743 >        int ec;
744 >        UNSAFE.compareAndSwapInt(this, eventCountOffset, ec=eventCount, ec+1);
745 >        outer:for (;;) {
746 >            long top = eventWaiters;
747 >            ec = eventCount;
748 >            for (;;) {
749 >                ForkJoinWorkerThread[] ws; ForkJoinWorkerThread w;
750 >                int id = (int)(top & WAITER_INDEX_MASK);
751 >                if (id <= 0 || (int)(top >>> EVENT_COUNT_SHIFT) == ec)
752 >                    return;
753 >                if ((ws = workers).length < id || (w = ws[id - 1]) == null ||
754 >                    !UNSAFE.compareAndSwapLong(this, eventWaitersOffset,
755 >                                               top, top = w.nextWaiter))
756 >                    continue outer;      // possibly stale; reread
757 >                LockSupport.unpark(w);
758 >                if (top != eventWaiters) // let someone else take over
759 >                    return;
760 >            }
761 >        }
762 >    }
763 >
764 >    /**
765 >     * If worker is inactive, blocks until terminating or event count
766 >     * advances from last value held by worker; in any case helps
767 >     * release others.
768 >     *
769 >     * @param w the calling worker thread
770 >     */
771 >    private void eventSync(ForkJoinWorkerThread w) {
772 >        if (!w.active) {
773 >            int prev = w.lastEventCount;
774 >            long nextTop = (((long)prev << EVENT_COUNT_SHIFT) |
775 >                            ((long)(w.poolIndex + 1)));
776 >            long top;
777 >            while ((runState < SHUTDOWN || !tryTerminate(false)) &&
778 >                   (((int)(top = eventWaiters) & WAITER_INDEX_MASK) == 0 ||
779 >                    (int)(top >>> EVENT_COUNT_SHIFT) == prev) &&
780 >                   eventCount == prev) {
781 >                if (UNSAFE.compareAndSwapLong(this, eventWaitersOffset,
782 >                                              w.nextWaiter = top, nextTop)) {
783 >                    accumulateStealCount(w); // transfer steals while idle
784 >                    Thread.interrupted();    // clear/ignore interrupt
785 >                    while (eventCount == prev)
786 >                        w.doPark();
787 >                    break;
788 >                }
789 >            }
790 >            w.lastEventCount = eventCount;
791 >        }
792 >        releaseWaiters();
793 >    }
794 >
795 >    /**
796 >     * Callback from workers invoked upon each top-level action (i.e.,
797 >     * stealing a task or taking a submission and running
798 >     * it). Performs one or both of the following:
799 >     *
800 >     * * If the worker cannot find work, updates its active status to
801 >     * inactive and updates activeCount unless there is contention, in
802 >     * which case it may try again (either in this or a subsequent
803 >     * call).  Additionally, awaits the next task event and/or helps
804 >     * wake up other releasable waiters.
805 >     *
806 >     * * If there are too many running threads, suspends this worker
807 >     * (first forcing inactivation if necessary).  If it is not
808 >     * resumed before a keepAlive elapses, the worker may be "trimmed"
809 >     * -- killed while suspended within suspendAsSpare. Otherwise,
810 >     * upon resume it rechecks to make sure that it is still needed.
811 >     *
812 >     * @param w the worker
813 >     * @param worked false if the worker scanned for work but didn't
814 >     * find any (in which case it may block waiting for work).
815 >     */
816 >    final void preStep(ForkJoinWorkerThread w, boolean worked) {
817 >        boolean active = w.active;
818 >        boolean inactivate = !worked & active;
819 >        for (;;) {
820 >            if (inactivate) {
821 >                int c = runState;
822 >                if (UNSAFE.compareAndSwapInt(this, runStateOffset,
823 >                                             c, c - ONE_ACTIVE))
824 >                    inactivate = active = w.active = false;
825 >            }
826 >            int wc = workerCounts;
827 >            if ((wc & RUNNING_COUNT_MASK) <= parallelism) {
828 >                if (!worked)
829 >                    eventSync(w);
830 >                return;
831 >            }
832 >            if (!(inactivate |= active) &&  // must inactivate to suspend
833 >                UNSAFE.compareAndSwapInt(this, workerCountsOffset,
834 >                                         wc, wc - ONE_RUNNING) &&
835 >                !w.suspendAsSpare())        // false if trimmed
836 >                return;
837 >        }
838 >    }
839 >
840 >    /**
841 >     * Adjusts counts and creates or resumes compensating threads for
842 >     * a worker about to block on task joinMe, returning early if
843 >     * joinMe becomes ready. First tries resuming an existing spare
844 >     * (which usually also avoids any count adjustment), but must then
845 >     * decrement running count to determine whether a new thread is
846 >     * needed. See above for fuller explanation.
847 >     */
848 >    final void preJoin(ForkJoinTask<?> joinMe) {
849 >        boolean dec = false;       // true when running count decremented
850 >        for (;;) {
851 >            releaseWaiters();      // help other threads progress
852 >
853 >            if (joinMe.status < 0) // surround spare search with done checks
854 >                return;
855 >            ForkJoinWorkerThread spare = null;
856 >            for (ForkJoinWorkerThread w : workers) {
857 >                if (w != null && w.isSuspended()) {
858 >                    spare = w;
859 >                    break;
860 >                }
861 >            }
862 >            if (joinMe.status < 0)
863 >                return;
864 >
865 >            if (spare != null && spare.tryUnsuspend()) {
866 >                if (dec || joinMe.requestSignal() < 0) {
867 >                    int c;
868 >                    do {} while (!UNSAFE.compareAndSwapInt(this,
869 >                                                           workerCountsOffset,
870 >                                                           c = workerCounts,
871 >                                                           c + ONE_RUNNING));
872 >                } // else no net count change
873 >                LockSupport.unpark(spare);
874 >                return;
875 >            }
876 >
877 >            int wc = workerCounts; // decrement running count
878 >            if (!dec && (wc & RUNNING_COUNT_MASK) != 0 &&
879 >                (dec = UNSAFE.compareAndSwapInt(this, workerCountsOffset,
880 >                                                wc, wc -= ONE_RUNNING)) &&
881 >                joinMe.requestSignal() < 0) { // cannot block
882 >                int c;                        // back out
883 >                do {} while (!UNSAFE.compareAndSwapInt(this,
884 >                                                       workerCountsOffset,
885 >                                                       c = workerCounts,
886 >                                                       c + ONE_RUNNING));
887 >                return;
888 >            }
889 >
890 >            if (dec) {
891 >                int tc = wc >>> TOTAL_COUNT_SHIFT;
892 >                int pc = parallelism;
893 >                int dc = pc - (wc & RUNNING_COUNT_MASK); // deficit count
894 >                if ((dc < pc && (dc <= 0 || (dc * dc < (tc - pc) * pc) ||
895 >                                 !maintainsParallelism)) ||
896 >                    tc >= maxPoolSize) // cannot add
897 >                    return;
898 >                if (spare == null &&
899 >                    UNSAFE.compareAndSwapInt(this, workerCountsOffset, wc,
900 >                                             wc + (ONE_RUNNING|ONE_TOTAL))) {
901 >                    addWorker();
902 >                    return;
903 >                }
904 >            }
905 >        }
906 >    }
907 >
908 >    /**
909 >     * Same idea as preJoin but with too many differing details to
910 >     * integrate: There are no task-based signal counts, and only one
911 >     * way to do the actual blocking. So for simplicity it is directly
912 >     * incorporated into this method.
913 >     */
914 >    final void doBlock(ManagedBlocker blocker, boolean maintainPar)
915 >        throws InterruptedException {
916 >        maintainPar &= maintainsParallelism; // override
917 >        boolean dec = false;
918 >        boolean done = false;
919 >        for (;;) {
920 >            releaseWaiters();
921 >            if (done = blocker.isReleasable())
922 >                break;
923 >            ForkJoinWorkerThread spare = null;
924 >            for (ForkJoinWorkerThread w : workers) {
925 >                if (w != null && w.isSuspended()) {
926 >                    spare = w;
927 >                    break;
928 >                }
929 >            }
930 >            if (done = blocker.isReleasable())
931 >                break;
932 >            if (spare != null && spare.tryUnsuspend()) {
933 >                if (dec) {
934 >                    int c;
935 >                    do {} while (!UNSAFE.compareAndSwapInt(this,
936 >                                                           workerCountsOffset,
937 >                                                           c = workerCounts,
938 >                                                           c + ONE_RUNNING));
939 >                }
940 >                LockSupport.unpark(spare);
941 >                break;
942 >            }
943 >            int wc = workerCounts;
944 >            if (!dec && (wc & RUNNING_COUNT_MASK) != 0)
945 >                dec = UNSAFE.compareAndSwapInt(this, workerCountsOffset,
946 >                                               wc, wc -= ONE_RUNNING);
947 >            if (dec) {
948 >                int tc = wc >>> TOTAL_COUNT_SHIFT;
949 >                int pc = parallelism;
950 >                int dc = pc - (wc & RUNNING_COUNT_MASK);
951 >                if ((dc < pc && (dc <= 0 || (dc * dc < (tc - pc) * pc) ||
952 >                                 !maintainPar)) ||
953 >                    tc >= maxPoolSize)
954 >                    break;
955 >                if (spare == null &&
956 >                    UNSAFE.compareAndSwapInt(this, workerCountsOffset, wc,
957 >                                             wc + (ONE_RUNNING|ONE_TOTAL))){
958 >                    addWorker();
959 >                    break;
960 >                }
961 >            }
962 >        }
963 >
964 >        try {
965 >            if (!done)
966 >                do {} while (!blocker.isReleasable() && !blocker.block());
967 >        } finally {
968 >            if (dec) {
969 >                int c;
970 >                do {} while (!UNSAFE.compareAndSwapInt(this,
971 >                                                       workerCountsOffset,
972 >                                                       c = workerCounts,
973 >                                                       c + ONE_RUNNING));
974 >            }
975 >        }
976 >    }
977 >
978 >    /**
979 >     * Possibly initiates and/or completes termination.
980 >     *
981 >     * @param now if true, unconditionally terminate, else only
982 >     * if shutdown and empty queue and no active workers
983 >     * @return true if now terminating or terminated
984 >     */
985 >    private boolean tryTerminate(boolean now) {
986 >        if (now)
987 >            advanceRunLevel(SHUTDOWN); // ensure at least SHUTDOWN
988 >        else if (runState < SHUTDOWN ||
989 >                 !submissionQueue.isEmpty() ||
990 >                 (runState & ACTIVE_COUNT_MASK) != 0)
991              return false;
992 <        if (canTerminateOnShutdown(nextc))
993 <            terminateOnShutdown();
992 >
993 >        if (advanceRunLevel(TERMINATING))
994 >            startTerminating();
995 >
996 >        // Finish now if all threads terminated; else in some subsequent call
997 >        if ((workerCounts >>> TOTAL_COUNT_SHIFT) == 0) {
998 >            advanceRunLevel(TERMINATED);
999 >            terminationLatch.countDown();
1000 >        }
1001          return true;
1002      }
1003  
1004      /**
1005 <     * Returns {@code true} if argument represents zero active count
337 <     * and nonzero runstate, which is the triggering condition for
338 <     * terminating on shutdown.
1005 >     * Actions on transition to TERMINATING
1006       */
1007 <    private static boolean canTerminateOnShutdown(int c) {
1008 <        // i.e. least bit is nonzero runState bit
1009 <        return ((c & -c) >>> 16) != 0;
1007 >    private void startTerminating() {
1008 >        // Clear out and cancel submissions, ignoring exceptions
1009 >        ForkJoinTask<?> task;
1010 >        while ((task = submissionQueue.poll()) != null) {
1011 >            try {
1012 >                task.cancel(false);
1013 >            } catch (Throwable ignore) {
1014 >            }
1015 >        }
1016 >        // Propagate run level
1017 >        for (ForkJoinWorkerThread w : workers) {
1018 >            if (w != null)
1019 >                w.shutdown();    // also resumes suspended workers
1020 >        }
1021 >        // Ensure no straggling local tasks
1022 >        for (ForkJoinWorkerThread w : workers) {
1023 >            if (w != null)
1024 >                w.cancelTasks();
1025 >        }
1026 >        // Wake up idle workers
1027 >        advanceEventCount();
1028 >        releaseWaiters();
1029 >        // Unstick pending joins
1030 >        for (ForkJoinWorkerThread w : workers) {
1031 >            if (w != null && !w.isTerminated()) {
1032 >                try {
1033 >                    w.interrupt();
1034 >                } catch (SecurityException ignore) {
1035 >                }
1036 >            }
1037 >        }
1038      }
1039  
1040 +    // misc support for ForkJoinWorkerThread
1041 +
1042      /**
1043 <     * Transition run state to at least the given state. Return true
347 <     * if not already at least given state.
1043 >     * Returns pool number
1044       */
1045 <    private boolean transitionRunStateTo(int state) {
1046 <        for (;;) {
1047 <            int c = runControl;
1048 <            if (runStateOf(c) >= state)
1049 <                return false;
1050 <            if (casRunControl(c, runControlFor(state, activeCountOf(c))))
1051 <                return true;
1045 >    final int getPoolNumber() {
1046 >        return poolNumber;
1047 >    }
1048 >
1049 >    /**
1050 >     * Accumulates steal count from a worker, clearing
1051 >     * the worker's value
1052 >     */
1053 >    final void accumulateStealCount(ForkJoinWorkerThread w) {
1054 >        int sc = w.stealCount;
1055 >        if (sc != 0) {
1056 >            long c;
1057 >            w.stealCount = 0;
1058 >            do {} while (!UNSAFE.compareAndSwapLong(this, stealCountOffset,
1059 >                                                    c = stealCount, c + sc));
1060          }
1061      }
1062  
1063      /**
1064 <     * Controls whether to add spares to maintain parallelism
1064 >     * Returns the approximate (non-atomic) number of idle threads per
1065 >     * active thread.
1066       */
1067 <    private volatile boolean maintainsParallelism;
1067 >    final int idlePerActive() {
1068 >        int ac = runState;    // no mask -- artifically boosts during shutdown
1069 >        int pc = parallelism; // use targeted parallelism, not rc
1070 >        // Use exact results for small values, saturate past 4
1071 >        return pc <= ac? 0 : pc >>> 1 <= ac? 1 : pc >>> 2 <= ac? 3 : pc >>> 3;
1072 >    }
1073 >
1074 >    /**
1075 >     * Returns the approximate (non-atomic) difference between running
1076 >     * and active counts.
1077 >     */
1078 >    final int inactiveCount() {
1079 >        return (workerCounts & RUNNING_COUNT_MASK) -
1080 >            (runState & ACTIVE_COUNT_MASK);
1081 >    }
1082 >
1083 >    // Public and protected methods
1084  
1085      // Constructors
1086  
# Line 426 | Line 1147 | public class ForkJoinPool extends Abstra
1147       *         java.lang.RuntimePermission}{@code ("modifyThread")}
1148       */
1149      public ForkJoinPool(int parallelism, ForkJoinWorkerThreadFactory factory) {
1150 <        if (parallelism <= 0 || parallelism > MAX_THREADS)
430 <            throw new IllegalArgumentException();
1150 >        checkPermission();
1151          if (factory == null)
1152              throw new NullPointerException();
1153 <        checkPermission();
1154 <        this.factory = factory;
1153 >        if (parallelism <= 0 || parallelism > MAX_THREADS)
1154 >            throw new IllegalArgumentException();
1155 >        this.poolNumber = poolNumberGenerator.incrementAndGet();
1156 >        int arraySize = initialArraySizeFor(parallelism);
1157          this.parallelism = parallelism;
1158 +        this.factory = factory;
1159          this.maxPoolSize = MAX_THREADS;
1160          this.maintainsParallelism = true;
1161 <        this.poolNumber = poolNumberGenerator.incrementAndGet();
439 <        this.workerLock = new ReentrantLock();
440 <        this.termination = workerLock.newCondition();
441 <        this.stealCount = new AtomicLong();
1161 >        this.workers = new ForkJoinWorkerThread[arraySize];
1162          this.submissionQueue = new LinkedTransferQueue<ForkJoinTask<?>>();
1163 <        // worker array and workers are lazily constructed
1164 <    }
1165 <
1166 <    /**
1167 <     * Creates a new worker thread using factory.
448 <     *
449 <     * @param index the index to assign worker
450 <     * @return new worker, or null if factory failed
451 <     */
452 <    private ForkJoinWorkerThread createWorker(int index) {
453 <        Thread.UncaughtExceptionHandler h = ueh;
454 <        ForkJoinWorkerThread w = factory.newThread(this);
455 <        if (w != null) {
456 <            w.poolIndex = index;
457 <            w.setDaemon(true);
458 <            w.setAsyncMode(locallyFifo);
459 <            w.setName("ForkJoinPool-" + poolNumber + "-worker-" + index);
460 <            if (h != null)
461 <                w.setUncaughtExceptionHandler(h);
462 <        }
463 <        return w;
464 <    }
465 <
466 <    /**
467 <     * Returns a good size for worker array given pool size.
468 <     * Currently requires size to be a power of two.
469 <     */
470 <    private static int arraySizeFor(int poolSize) {
471 <        if (poolSize <= 1)
472 <            return 1;
473 <        // See Hackers Delight, sec 3.2
474 <        int c = poolSize >= MAX_THREADS ? MAX_THREADS : (poolSize - 1);
475 <        c |= c >>>  1;
476 <        c |= c >>>  2;
477 <        c |= c >>>  4;
478 <        c |= c >>>  8;
479 <        c |= c >>> 16;
480 <        return c + 1;
481 <    }
482 <
483 <    /**
484 <     * Creates or resizes array if necessary to hold newLength.
485 <     * Call only under exclusion.
486 <     *
487 <     * @return the array
488 <     */
489 <    private ForkJoinWorkerThread[] ensureWorkerArrayCapacity(int newLength) {
490 <        ForkJoinWorkerThread[] ws = workers;
491 <        if (ws == null)
492 <            return workers = new ForkJoinWorkerThread[arraySizeFor(newLength)];
493 <        else if (newLength > ws.length)
494 <            return workers = Arrays.copyOf(ws, arraySizeFor(newLength));
495 <        else
496 <            return ws;
497 <    }
498 <
499 <    /**
500 <     * Tries to shrink workers into smaller array after one or more terminate.
501 <     */
502 <    private void tryShrinkWorkerArray() {
503 <        ForkJoinWorkerThread[] ws = workers;
504 <        if (ws != null) {
505 <            int len = ws.length;
506 <            int last = len - 1;
507 <            while (last >= 0 && ws[last] == null)
508 <                --last;
509 <            int newLength = arraySizeFor(last+1);
510 <            if (newLength < len)
511 <                workers = Arrays.copyOf(ws, newLength);
512 <        }
513 <    }
514 <
515 <    /**
516 <     * Initializes workers if necessary.
517 <     */
518 <    final void ensureWorkerInitialization() {
519 <        ForkJoinWorkerThread[] ws = workers;
520 <        if (ws == null) {
521 <            final ReentrantLock lock = this.workerLock;
522 <            lock.lock();
523 <            try {
524 <                ws = workers;
525 <                if (ws == null) {
526 <                    int ps = parallelism;
527 <                    updateWorkerCount(ps);
528 <                    ws = ensureWorkerArrayCapacity(ps);
529 <                    for (int i = 0; i < ps; ++i) {
530 <                        ForkJoinWorkerThread w = createWorker(i);
531 <                        if (w != null) {
532 <                            ws[i] = w;
533 <                            w.start();
534 <                        }
535 <                        else
536 <                            updateWorkerCount(-1);
537 <                    }
538 <                }
539 <            } finally {
540 <                lock.unlock();
541 <            }
542 <        }
1163 >        this.workerLock = new ReentrantLock();
1164 >        this.terminationLatch = new CountDownLatch(1);
1165 >        // Start first worker; remaining workers added upon first submission
1166 >        workerCounts = ONE_RUNNING | ONE_TOTAL;
1167 >        addWorker();
1168      }
1169  
1170      /**
1171 <     * Worker creation and startup for threads added via setParallelism.
1172 <     */
1173 <    private void createAndStartAddedWorkers() {
1174 <        resumeAllSpares();  // Allow spares to convert to nonspare
1175 <        int ps = parallelism;
1176 <        ForkJoinWorkerThread[] ws = ensureWorkerArrayCapacity(ps);
1177 <        int len = ws.length;
1178 <        // Sweep through slots, to keep lowest indices most populated
1179 <        int k = 0;
1180 <        while (k < len) {
1181 <            if (ws[k] != null) {
557 <                ++k;
558 <                continue;
559 <            }
560 <            int s = workerCounts;
561 <            int tc = totalCountOf(s);
562 <            int rc = runningCountOf(s);
563 <            if (rc >= ps || tc >= ps)
564 <                break;
565 <            if (casWorkerCounts (s, workerCountsFor(tc+1, rc+1))) {
566 <                ForkJoinWorkerThread w = createWorker(k);
567 <                if (w != null) {
568 <                    ws[k++] = w;
569 <                    w.start();
570 <                }
571 <                else {
572 <                    updateWorkerCount(-1); // back out on failed creation
573 <                    break;
574 <                }
575 <            }
576 <        }
1171 >     * Returns initial power of two size for workers array.
1172 >     * @param pc the initial parallelism level
1173 >     */
1174 >    private static int initialArraySizeFor(int pc) {
1175 >        // See Hackers Delight, sec 3.2. We know MAX_THREADS < (1 >>> 16)
1176 >        int size = pc < MAX_THREADS ? pc + 1 : MAX_THREADS;
1177 >        size |= size >>> 1;
1178 >        size |= size >>> 2;
1179 >        size |= size >>> 4;
1180 >        size |= size >>> 8;
1181 >        return size + 1;
1182      }
1183  
1184      // Execution methods
# Line 584 | Line 1189 | public class ForkJoinPool extends Abstra
1189      private <T> void doSubmit(ForkJoinTask<T> task) {
1190          if (task == null)
1191              throw new NullPointerException();
1192 <        if (isShutdown())
1192 >        if (runState >= SHUTDOWN)
1193              throw new RejectedExecutionException();
589        if (workers == null)
590            ensureWorkerInitialization();
1194          submissionQueue.offer(task);
1195 <        signalIdleWorkers();
1195 >        advanceEventCount();
1196 >        releaseWaiters();
1197 >        if ((workerCounts >>> TOTAL_COUNT_SHIFT) < parallelism)
1198 >            ensureEnoughTotalWorkers();
1199      }
1200  
1201      /**
# Line 685 | Line 1291 | public class ForkJoinPool extends Abstra
1291          return task;
1292      }
1293  
688
1294      /**
1295       * @throws NullPointerException       {@inheritDoc}
1296       * @throws RejectedExecutionException {@inheritDoc}
# Line 712 | Line 1317 | public class ForkJoinPool extends Abstra
1317          private static final long serialVersionUID = -7914297376763021607L;
1318      }
1319  
715    // Configuration and status settings and queries
716
1320      /**
1321       * Returns the factory used for constructing new workers.
1322       *
# Line 730 | Line 1333 | public class ForkJoinPool extends Abstra
1333       * @return the handler, or {@code null} if none
1334       */
1335      public Thread.UncaughtExceptionHandler getUncaughtExceptionHandler() {
1336 <        Thread.UncaughtExceptionHandler h;
1337 <        final ReentrantLock lock = this.workerLock;
735 <        lock.lock();
736 <        try {
737 <            h = ueh;
738 <        } finally {
739 <            lock.unlock();
740 <        }
741 <        return h;
1336 >        workerCountReadFence();
1337 >        return ueh;
1338      }
1339  
1340      /**
# Line 757 | Line 1353 | public class ForkJoinPool extends Abstra
1353      public Thread.UncaughtExceptionHandler
1354          setUncaughtExceptionHandler(Thread.UncaughtExceptionHandler h) {
1355          checkPermission();
1356 <        Thread.UncaughtExceptionHandler old = null;
1357 <        final ReentrantLock lock = this.workerLock;
1358 <        lock.lock();
763 <        try {
764 <            old = ueh;
1356 >        workerCountReadFence();
1357 >        Thread.UncaughtExceptionHandler old = ueh;
1358 >        if (h != old) {
1359              ueh = h;
1360 <            ForkJoinWorkerThread[] ws = workers;
1361 <            if (ws != null) {
1362 <                for (int i = 0; i < ws.length; ++i) {
1363 <                    ForkJoinWorkerThread w = ws[i];
770 <                    if (w != null)
771 <                        w.setUncaughtExceptionHandler(h);
772 <                }
1360 >            workerCountWriteFence();
1361 >            for (ForkJoinWorkerThread w : workers) {
1362 >                if (w != null)
1363 >                    w.setUncaughtExceptionHandler(h);
1364              }
774        } finally {
775            lock.unlock();
1365          }
1366          return old;
1367      }
1368  
780
1369      /**
1370       * Sets the target parallelism level of this pool.
1371       *
# Line 793 | Line 1381 | public class ForkJoinPool extends Abstra
1381          checkPermission();
1382          if (parallelism <= 0 || parallelism > maxPoolSize)
1383              throw new IllegalArgumentException();
1384 <        final ReentrantLock lock = this.workerLock;
1385 <        lock.lock();
1386 <        try {
1387 <            if (isProcessingTasks()) {
1388 <                int p = this.parallelism;
1389 <                this.parallelism = parallelism;
1390 <                if (workers != null) {
1391 <                    if (parallelism > p)
1392 <                        createAndStartAddedWorkers();
1393 <                    else
806 <                        trimSpares();
1384 >        workerCountReadFence();
1385 >        int pc = this.parallelism;
1386 >        if (pc != parallelism) {
1387 >            this.parallelism = parallelism;
1388 >            workerCountWriteFence();
1389 >            // Release spares. If too many, some will die after re-suspend
1390 >            for (ForkJoinWorkerThread w : workers) {
1391 >                if (w != null && w.tryUnsuspend()) {
1392 >                    updateRunningCount(1);
1393 >                    LockSupport.unpark(w);
1394                  }
1395              }
1396 <        } finally {
1397 <            lock.unlock();
1396 >            ensureEnoughTotalWorkers();
1397 >            advanceEventCount();
1398 >            releaseWaiters(); // force config recheck by existing workers
1399          }
812        signalIdleWorkers();
1400      }
1401  
1402      /**
# Line 818 | Line 1405 | public class ForkJoinPool extends Abstra
1405       * @return the targeted parallelism level of this pool
1406       */
1407      public int getParallelism() {
1408 +        //        workerCountReadFence(); // inlined below
1409 +        int ignore = workerCounts;
1410          return parallelism;
1411      }
1412  
# Line 830 | Line 1419 | public class ForkJoinPool extends Abstra
1419       * @return the number of worker threads
1420       */
1421      public int getPoolSize() {
1422 <        return totalCountOf(workerCounts);
1422 >        return workerCounts >>> TOTAL_COUNT_SHIFT;
1423      }
1424  
1425      /**
# Line 842 | Line 1431 | public class ForkJoinPool extends Abstra
1431       * @return the maximum
1432       */
1433      public int getMaximumPoolSize() {
1434 +        workerCountReadFence();
1435          return maxPoolSize;
1436      }
1437  
# Line 859 | Line 1449 | public class ForkJoinPool extends Abstra
1449          if (newMax < 0 || newMax > MAX_THREADS)
1450              throw new IllegalArgumentException();
1451          maxPoolSize = newMax;
1452 +        workerCountWriteFence();
1453      }
1454  
864
1455      /**
1456       * Returns {@code true} if this pool dynamically maintains its
1457       * target parallelism level. If false, new threads are added only
# Line 870 | Line 1460 | public class ForkJoinPool extends Abstra
1460       * @return {@code true} if maintains parallelism
1461       */
1462      public boolean getMaintainsParallelism() {
1463 +        workerCountReadFence();
1464          return maintainsParallelism;
1465      }
1466  
# Line 882 | Line 1473 | public class ForkJoinPool extends Abstra
1473       */
1474      public void setMaintainsParallelism(boolean enable) {
1475          maintainsParallelism = enable;
1476 +        workerCountWriteFence();
1477      }
1478  
1479      /**
# Line 898 | Line 1490 | public class ForkJoinPool extends Abstra
1490       * @see #getAsyncMode
1491       */
1492      public boolean setAsyncMode(boolean async) {
1493 +        workerCountReadFence();
1494          boolean oldMode = locallyFifo;
1495 <        locallyFifo = async;
1496 <        ForkJoinWorkerThread[] ws = workers;
1497 <        if (ws != null) {
1498 <            for (int i = 0; i < ws.length; ++i) {
1499 <                ForkJoinWorkerThread t = ws[i];
1500 <                if (t != null)
908 <                    t.setAsyncMode(async);
1495 >        if (oldMode != async) {
1496 >            locallyFifo = async;
1497 >            workerCountWriteFence();
1498 >            for (ForkJoinWorkerThread w : workers) {
1499 >                if (w != null)
1500 >                    w.setAsyncMode(async);
1501              }
1502          }
1503          return oldMode;
# Line 919 | Line 1511 | public class ForkJoinPool extends Abstra
1511       * @see #setAsyncMode
1512       */
1513      public boolean getAsyncMode() {
1514 +        workerCountReadFence();
1515          return locallyFifo;
1516      }
1517  
1518      /**
1519       * Returns an estimate of the number of worker threads that are
1520       * not blocked waiting to join tasks or for other managed
1521 <     * synchronization.
1521 >     * synchronization. This method may overestimate the
1522 >     * number of running threads.
1523       *
1524       * @return the number of worker threads
1525       */
1526      public int getRunningThreadCount() {
1527 <        return runningCountOf(workerCounts);
1527 >        return workerCounts & RUNNING_COUNT_MASK;
1528      }
1529  
1530      /**
# Line 941 | Line 1535 | public class ForkJoinPool extends Abstra
1535       * @return the number of active threads
1536       */
1537      public int getActiveThreadCount() {
1538 <        return activeCountOf(runControl);
945 <    }
946 <
947 <    /**
948 <     * Returns an estimate of the number of threads that are currently
949 <     * idle waiting for tasks. This method may underestimate the
950 <     * number of idle threads.
951 <     *
952 <     * @return the number of idle threads
953 <     */
954 <    final int getIdleThreadCount() {
955 <        int c = runningCountOf(workerCounts) - activeCountOf(runControl);
956 <        return (c <= 0) ? 0 : c;
1538 >        return runState & ACTIVE_COUNT_MASK;
1539      }
1540  
1541      /**
# Line 968 | Line 1550 | public class ForkJoinPool extends Abstra
1550       * @return {@code true} if all threads are currently idle
1551       */
1552      public boolean isQuiescent() {
1553 <        return activeCountOf(runControl) == 0;
1553 >        return (runState & ACTIVE_COUNT_MASK) == 0;
1554      }
1555  
1556      /**
# Line 983 | Line 1565 | public class ForkJoinPool extends Abstra
1565       * @return the number of steals
1566       */
1567      public long getStealCount() {
1568 <        return stealCount.get();
987 <    }
988 <
989 <    /**
990 <     * Accumulates steal count from a worker.
991 <     * Call only when worker known to be idle.
992 <     */
993 <    private void updateStealCount(ForkJoinWorkerThread w) {
994 <        int sc = w.getAndClearStealCount();
995 <        if (sc != 0)
996 <            stealCount.addAndGet(sc);
1568 >        return stealCount;
1569      }
1570  
1571      /**
# Line 1008 | Line 1580 | public class ForkJoinPool extends Abstra
1580       */
1581      public long getQueuedTaskCount() {
1582          long count = 0;
1583 <        ForkJoinWorkerThread[] ws = workers;
1584 <        if (ws != null) {
1585 <            for (int i = 0; i < ws.length; ++i) {
1014 <                ForkJoinWorkerThread t = ws[i];
1015 <                if (t != null)
1016 <                    count += t.getQueueSize();
1017 <            }
1583 >        for (ForkJoinWorkerThread w : workers) {
1584 >            if (w != null)
1585 >                count += w.getQueueSize();
1586          }
1587          return count;
1588      }
# Line 1070 | Line 1638 | public class ForkJoinPool extends Abstra
1638       */
1639      protected int drainTasksTo(Collection<? super ForkJoinTask<?>> c) {
1640          int n = submissionQueue.drainTo(c);
1641 <        ForkJoinWorkerThread[] ws = workers;
1642 <        if (ws != null) {
1643 <            for (int i = 0; i < ws.length; ++i) {
1076 <                ForkJoinWorkerThread w = ws[i];
1077 <                if (w != null)
1078 <                    n += w.drainTasksTo(c);
1079 <            }
1641 >        for (ForkJoinWorkerThread w : workers) {
1642 >            if (w != null)
1643 >                n += w.drainTasksTo(c);
1644          }
1645          return n;
1646      }
# Line 1089 | Line 1653 | public class ForkJoinPool extends Abstra
1653       * @return a string identifying this pool, as well as its state
1654       */
1655      public String toString() {
1092        int ps = parallelism;
1093        int wc = workerCounts;
1094        int rc = runControl;
1656          long st = getStealCount();
1657          long qt = getQueuedTaskCount();
1658          long qs = getQueuedSubmissionCount();
1659 +        int wc = workerCounts;
1660 +        int tc = wc >>> TOTAL_COUNT_SHIFT;
1661 +        int rc = wc & RUNNING_COUNT_MASK;
1662 +        int pc = parallelism;
1663 +        int rs = runState;
1664 +        int ac = rs & ACTIVE_COUNT_MASK;
1665          return super.toString() +
1666 <            "[" + runStateToString(runStateOf(rc)) +
1667 <            ", parallelism = " + ps +
1668 <            ", size = " + totalCountOf(wc) +
1669 <            ", active = " + activeCountOf(rc) +
1670 <            ", running = " + runningCountOf(wc) +
1666 >            "[" + runLevelToString(rs) +
1667 >            ", parallelism = " + pc +
1668 >            ", size = " + tc +
1669 >            ", active = " + ac +
1670 >            ", running = " + rc +
1671              ", steals = " + st +
1672              ", tasks = " + qt +
1673              ", submissions = " + qs +
1674              "]";
1675      }
1676  
1677 <    private static String runStateToString(int rs) {
1678 <        switch (rs) {
1679 <        case RUNNING: return "Running";
1680 <        case SHUTDOWN: return "Shutting down";
1681 <        case TERMINATING: return "Terminating";
1115 <        case TERMINATED: return "Terminated";
1116 <        default: throw new Error("Unknown run state");
1117 <        }
1677 >    private static String runLevelToString(int s) {
1678 >        return ((s & TERMINATED) != 0 ? "Terminated" :
1679 >                ((s & TERMINATING) != 0 ? "Terminating" :
1680 >                 ((s & SHUTDOWN) != 0 ? "Shutting down" :
1681 >                  "Running")));
1682      }
1683  
1120    // lifecycle control
1121
1684      /**
1685       * Initiates an orderly shutdown in which previously submitted
1686       * tasks are executed, but no new tasks will be accepted.
# Line 1133 | Line 1695 | public class ForkJoinPool extends Abstra
1695       */
1696      public void shutdown() {
1697          checkPermission();
1698 <        transitionRunStateTo(SHUTDOWN);
1699 <        if (canTerminateOnShutdown(runControl)) {
1138 <            if (workers == null) { // shutting down before workers created
1139 <                final ReentrantLock lock = this.workerLock;
1140 <                lock.lock();
1141 <                try {
1142 <                    if (workers == null) {
1143 <                        terminate();
1144 <                        transitionRunStateTo(TERMINATED);
1145 <                        termination.signalAll();
1146 <                    }
1147 <                } finally {
1148 <                    lock.unlock();
1149 <                }
1150 <            }
1151 <            terminateOnShutdown();
1152 <        }
1698 >        advanceRunLevel(SHUTDOWN);
1699 >        tryTerminate(false);
1700      }
1701  
1702      /**
# Line 1170 | Line 1717 | public class ForkJoinPool extends Abstra
1717       */
1718      public List<Runnable> shutdownNow() {
1719          checkPermission();
1720 <        terminate();
1720 >        tryTerminate(true);
1721          return Collections.emptyList();
1722      }
1723  
# Line 1180 | Line 1727 | public class ForkJoinPool extends Abstra
1727       * @return {@code true} if all tasks have completed following shut down
1728       */
1729      public boolean isTerminated() {
1730 <        return runStateOf(runControl) == TERMINATED;
1730 >        return runState >= TERMINATED;
1731      }
1732  
1733      /**
# Line 1194 | Line 1741 | public class ForkJoinPool extends Abstra
1741       * @return {@code true} if terminating but not yet terminated
1742       */
1743      public boolean isTerminating() {
1744 <        return runStateOf(runControl) == TERMINATING;
1744 >        return (runState & (TERMINATING|TERMINATED)) == TERMINATING;
1745      }
1746  
1747      /**
# Line 1203 | Line 1750 | public class ForkJoinPool extends Abstra
1750       * @return {@code true} if this pool has been shut down
1751       */
1752      public boolean isShutdown() {
1753 <        return runStateOf(runControl) >= SHUTDOWN;
1207 <    }
1208 <
1209 <    /**
1210 <     * Returns true if pool is not terminating or terminated.
1211 <     * Used internally to suppress execution when terminating.
1212 <     */
1213 <    final boolean isProcessingTasks() {
1214 <        return runStateOf(runControl) < TERMINATING;
1753 >        return runState >= SHUTDOWN;
1754      }
1755  
1756      /**
# Line 1227 | Line 1766 | public class ForkJoinPool extends Abstra
1766       */
1767      public boolean awaitTermination(long timeout, TimeUnit unit)
1768          throws InterruptedException {
1769 <        long nanos = unit.toNanos(timeout);
1231 <        final ReentrantLock lock = this.workerLock;
1232 <        lock.lock();
1233 <        try {
1234 <            for (;;) {
1235 <                if (isTerminated())
1236 <                    return true;
1237 <                if (nanos <= 0)
1238 <                    return false;
1239 <                nanos = termination.awaitNanos(nanos);
1240 <            }
1241 <        } finally {
1242 <            lock.unlock();
1243 <        }
1244 <    }
1245 <
1246 <    // Shutdown and termination support
1247 <
1248 <    /**
1249 <     * Callback from terminating worker. Nulls out the corresponding
1250 <     * workers slot, and if terminating, tries to terminate; else
1251 <     * tries to shrink workers array.
1252 <     *
1253 <     * @param w the worker
1254 <     */
1255 <    final void workerTerminated(ForkJoinWorkerThread w) {
1256 <        updateStealCount(w);
1257 <        updateWorkerCount(-1);
1258 <        final ReentrantLock lock = this.workerLock;
1259 <        lock.lock();
1260 <        try {
1261 <            ForkJoinWorkerThread[] ws = workers;
1262 <            if (ws != null) {
1263 <                int idx = w.poolIndex;
1264 <                if (idx >= 0 && idx < ws.length && ws[idx] == w)
1265 <                    ws[idx] = null;
1266 <                if (totalCountOf(workerCounts) == 0) {
1267 <                    terminate(); // no-op if already terminating
1268 <                    transitionRunStateTo(TERMINATED);
1269 <                    termination.signalAll();
1270 <                }
1271 <                else if (isProcessingTasks()) {
1272 <                    tryShrinkWorkerArray();
1273 <                    tryResumeSpare(true); // allow replacement
1274 <                }
1275 <            }
1276 <        } finally {
1277 <            lock.unlock();
1278 <        }
1279 <        signalIdleWorkers();
1280 <    }
1281 <
1282 <    /**
1283 <     * Initiates termination.
1284 <     */
1285 <    private void terminate() {
1286 <        if (transitionRunStateTo(TERMINATING)) {
1287 <            stopAllWorkers();
1288 <            resumeAllSpares();
1289 <            signalIdleWorkers();
1290 <            cancelQueuedSubmissions();
1291 <            cancelQueuedWorkerTasks();
1292 <            interruptUnterminatedWorkers();
1293 <            signalIdleWorkers(); // resignal after interrupt
1294 <        }
1295 <    }
1296 <
1297 <    /**
1298 <     * Possibly terminates when on shutdown state.
1299 <     */
1300 <    private void terminateOnShutdown() {
1301 <        if (!hasQueuedSubmissions() && canTerminateOnShutdown(runControl))
1302 <            terminate();
1303 <    }
1304 <
1305 <    /**
1306 <     * Clears out and cancels submissions.
1307 <     */
1308 <    private void cancelQueuedSubmissions() {
1309 <        ForkJoinTask<?> task;
1310 <        while ((task = pollSubmission()) != null)
1311 <            task.cancel(false);
1312 <    }
1313 <
1314 <    /**
1315 <     * Cleans out worker queues.
1316 <     */
1317 <    private void cancelQueuedWorkerTasks() {
1318 <        final ReentrantLock lock = this.workerLock;
1319 <        lock.lock();
1320 <        try {
1321 <            ForkJoinWorkerThread[] ws = workers;
1322 <            if (ws != null) {
1323 <                for (int i = 0; i < ws.length; ++i) {
1324 <                    ForkJoinWorkerThread t = ws[i];
1325 <                    if (t != null)
1326 <                        t.cancelTasks();
1327 <                }
1328 <            }
1329 <        } finally {
1330 <            lock.unlock();
1331 <        }
1332 <    }
1333 <
1334 <    /**
1335 <     * Sets each worker's status to terminating. Requires lock to avoid
1336 <     * conflicts with add/remove.
1337 <     */
1338 <    private void stopAllWorkers() {
1339 <        final ReentrantLock lock = this.workerLock;
1340 <        lock.lock();
1341 <        try {
1342 <            ForkJoinWorkerThread[] ws = workers;
1343 <            if (ws != null) {
1344 <                for (int i = 0; i < ws.length; ++i) {
1345 <                    ForkJoinWorkerThread t = ws[i];
1346 <                    if (t != null)
1347 <                        t.shutdownNow();
1348 <                }
1349 <            }
1350 <        } finally {
1351 <            lock.unlock();
1352 <        }
1353 <    }
1354 <
1355 <    /**
1356 <     * Interrupts all unterminated workers.  This is not required for
1357 <     * sake of internal control, but may help unstick user code during
1358 <     * shutdown.
1359 <     */
1360 <    private void interruptUnterminatedWorkers() {
1361 <        final ReentrantLock lock = this.workerLock;
1362 <        lock.lock();
1363 <        try {
1364 <            ForkJoinWorkerThread[] ws = workers;
1365 <            if (ws != null) {
1366 <                for (int i = 0; i < ws.length; ++i) {
1367 <                    ForkJoinWorkerThread t = ws[i];
1368 <                    if (t != null && !t.isTerminated()) {
1369 <                        try {
1370 <                            t.interrupt();
1371 <                        } catch (SecurityException ignore) {
1372 <                        }
1373 <                    }
1374 <                }
1375 <            }
1376 <        } finally {
1377 <            lock.unlock();
1378 <        }
1379 <    }
1380 <
1381 <    /*
1382 <     * Nodes for event barrier to manage idle threads.  Queue nodes
1383 <     * are basic Treiber stack nodes, also used for spare stack.
1384 <     *
1385 <     * The event barrier has an event count and a wait queue (actually
1386 <     * a Treiber stack).  Workers are enabled to look for work when
1387 <     * the eventCount is incremented. If they fail to find work, they
1388 <     * may wait for next count. Upon release, threads help others wake
1389 <     * up.
1390 <     *
1391 <     * Synchronization events occur only in enough contexts to
1392 <     * maintain overall liveness:
1393 <     *
1394 <     *   - Submission of a new task to the pool
1395 <     *   - Resizes or other changes to the workers array
1396 <     *   - pool termination
1397 <     *   - A worker pushing a task on an empty queue
1398 <     *
1399 <     * The case of pushing a task occurs often enough, and is heavy
1400 <     * enough compared to simple stack pushes, to require special
1401 <     * handling: Method signalWork returns without advancing count if
1402 <     * the queue appears to be empty.  This would ordinarily result in
1403 <     * races causing some queued waiters not to be woken up. To avoid
1404 <     * this, the first worker enqueued in method sync rescans for
1405 <     * tasks after being enqueued, and helps signal if any are
1406 <     * found. This works well because the worker has nothing better to
1407 <     * do, and so might as well help alleviate the overhead and
1408 <     * contention on the threads actually doing work.  Also, since
1409 <     * event counts increments on task availability exist to maintain
1410 <     * liveness (rather than to force refreshes etc), it is OK for
1411 <     * callers to exit early if contending with another signaller.
1412 <     */
1413 <    static final class WaitQueueNode {
1414 <        WaitQueueNode next; // only written before enqueued
1415 <        volatile ForkJoinWorkerThread thread; // nulled to cancel wait
1416 <        final long count; // unused for spare stack
1417 <
1418 <        WaitQueueNode(long c, ForkJoinWorkerThread w) {
1419 <            count = c;
1420 <            thread = w;
1421 <        }
1422 <
1423 <        /**
1424 <         * Wakes up waiter, also clearing thread field
1425 <         */
1426 <        void signal() {
1427 <            ForkJoinWorkerThread t = thread;
1428 <            if (t != null) {
1429 <                thread = null;
1430 <                LockSupport.unpark(t);
1431 <            }
1432 <        }
1433 <    }
1434 <
1435 <    /**
1436 <     * Ensures that no thread is waiting for count to advance from the
1437 <     * current value of eventCount read on entry to this method, by
1438 <     * releasing waiting threads if necessary.
1439 <     */
1440 <    final void ensureSync() {
1441 <        long c = eventCount;
1442 <        WaitQueueNode q;
1443 <        while ((q = syncStack) != null && q.count < c) {
1444 <            if (casBarrierStack(q, null)) {
1445 <                do {
1446 <                    q.signal();
1447 <                } while ((q = q.next) != null);
1448 <                break;
1449 <            }
1450 <        }
1451 <    }
1452 <
1453 <    /**
1454 <     * Increments event count and releases waiting threads.
1455 <     */
1456 <    private void signalIdleWorkers() {
1457 <        long c;
1458 <        do {} while (!casEventCount(c = eventCount, c+1));
1459 <        ensureSync();
1460 <    }
1461 <
1462 <    /**
1463 <     * Signals threads waiting to poll a task. Because method sync
1464 <     * rechecks availability, it is OK to only proceed if queue
1465 <     * appears to be non-empty, and OK if CAS to increment count
1466 <     * fails (since some other thread succeeded).
1467 <     */
1468 <    final void signalWork() {
1469 <        if (syncStack != null) {
1470 <            long c = eventCount;
1471 <            casEventCount(c, c+1);
1472 <            WaitQueueNode q = syncStack;
1473 <            if (q != null && q.count <= c) {
1474 <                if (casBarrierStack(q, q.next))
1475 <                    q.signal();
1476 <                else
1477 <                    ensureSync(); // awaken all on contention
1478 <            }
1479 <        }
1480 <    }
1481 <
1482 <    /**
1483 <     * Possibly blocks until event count advances from last value held
1484 <     * by caller, or if excess threads, caller is resumed as spare, or
1485 <     * caller or pool is terminating. Updates caller's event on exit.
1486 <     *
1487 <     * @param w the calling worker thread
1488 <     */
1489 <    final void sync(ForkJoinWorkerThread w) {
1490 <        updateStealCount(w); // Transfer w's count while it is idle
1491 <
1492 <        if (!w.isShutdown() && isProcessingTasks() && !suspendIfSpare(w)) {
1493 <            long prev = w.lastEventCount;
1494 <            WaitQueueNode node = null;
1495 <            WaitQueueNode h;
1496 <            long c;
1497 <            while ((c = eventCount) == prev &&
1498 <                   ((h = syncStack) == null || h.count == prev)) {
1499 <                if (node == null)
1500 <                    node = new WaitQueueNode(prev, w);
1501 <                if (casBarrierStack(node.next = h, node)) {
1502 <                    if (!Thread.interrupted() &&
1503 <                        node.thread != null &&
1504 <                        eventCount == prev &&
1505 <                        (h != null || // cover signalWork race
1506 <                         (!ForkJoinWorkerThread.hasQueuedTasks(workers) &&
1507 <                          eventCount == prev)))
1508 <                        LockSupport.park(this);
1509 <                    c = eventCount;
1510 <                    if (node.thread != null) { // help signal if not unparked
1511 <                        node.thread = null;
1512 <                        if (c == prev)
1513 <                            casEventCount(prev, prev + 1);
1514 <                    }
1515 <                    break;
1516 <                }
1517 <            }
1518 <            w.lastEventCount = c;
1519 <            ensureSync();
1520 <        }
1521 <    }
1522 <
1523 <    /**
1524 <     * Returns {@code true} if a new sync event occurred since last
1525 <     * call to sync or this method, if so, updating caller's count.
1526 <     */
1527 <    final boolean hasNewSyncEvent(ForkJoinWorkerThread w) {
1528 <        long wc = w.lastEventCount;
1529 <        long c = eventCount;
1530 <        if (wc != c)
1531 <            w.lastEventCount = c;
1532 <        ensureSync();
1533 <        return wc != c || wc != eventCount;
1534 <    }
1535 <
1536 <    //  Parallelism maintenance
1537 <
1538 <    /**
1539 <     * Decrements running count; if too low, adds spare.
1540 <     *
1541 <     * Conceptually, all we need to do here is add or resume a
1542 <     * spare thread when one is about to block (and remove or
1543 <     * suspend it later when unblocked -- see suspendIfSpare).
1544 <     * However, implementing this idea requires coping with
1545 <     * several problems: we have imperfect information about the
1546 <     * states of threads. Some count updates can and usually do
1547 <     * lag run state changes, despite arrangements to keep them
1548 <     * accurate (for example, when possible, updating counts
1549 <     * before signalling or resuming), especially when running on
1550 <     * dynamic JVMs that don't optimize the infrequent paths that
1551 <     * update counts. Generating too many threads can make these
1552 <     * problems become worse, because excess threads are more
1553 <     * likely to be context-switched with others, slowing them all
1554 <     * down, especially if there is no work available, so all are
1555 <     * busy scanning or idling.  Also, excess spare threads can
1556 <     * only be suspended or removed when they are idle, not
1557 <     * immediately when they aren't needed. So adding threads will
1558 <     * raise parallelism level for longer than necessary.  Also,
1559 <     * FJ applications often encounter highly transient peaks when
1560 <     * many threads are blocked joining, but for less time than it
1561 <     * takes to create or resume spares.
1562 <     *
1563 <     * @param joinMe if non-null, return early if done
1564 <     * @param maintainParallelism if true, try to stay within
1565 <     * target counts, else create only to avoid starvation
1566 <     * @return true if joinMe known to be done
1567 <     */
1568 <    final boolean preJoin(ForkJoinTask<?> joinMe,
1569 <                          boolean maintainParallelism) {
1570 <        maintainParallelism &= maintainsParallelism; // overrride
1571 <        boolean dec = false;  // true when running count decremented
1572 <        while (spareStack == null || !tryResumeSpare(dec)) {
1573 <            int counts = workerCounts;
1574 <            if (dec || (dec = casWorkerCounts(counts, --counts))) {
1575 <                if (!needSpare(counts, maintainParallelism))
1576 <                    break;
1577 <                if (joinMe.status < 0)
1578 <                    return true;
1579 <                if (tryAddSpare(counts))
1580 <                    break;
1581 <            }
1582 <        }
1583 <        return false;
1584 <    }
1585 <
1586 <    /**
1587 <     * Same idea as preJoin
1588 <     */
1589 <    final boolean preBlock(ManagedBlocker blocker,
1590 <                           boolean maintainParallelism) {
1591 <        maintainParallelism &= maintainsParallelism;
1592 <        boolean dec = false;
1593 <        while (spareStack == null || !tryResumeSpare(dec)) {
1594 <            int counts = workerCounts;
1595 <            if (dec || (dec = casWorkerCounts(counts, --counts))) {
1596 <                if (!needSpare(counts, maintainParallelism))
1597 <                    break;
1598 <                if (blocker.isReleasable())
1599 <                    return true;
1600 <                if (tryAddSpare(counts))
1601 <                    break;
1602 <            }
1603 <        }
1604 <        return false;
1605 <    }
1606 <
1607 <    /**
1608 <     * Returns {@code true} if a spare thread appears to be needed.
1609 <     * If maintaining parallelism, returns true when the deficit in
1610 <     * running threads is more than the surplus of total threads, and
1611 <     * there is apparently some work to do.  This self-limiting rule
1612 <     * means that the more threads that have already been added, the
1613 <     * less parallelism we will tolerate before adding another.
1614 <     *
1615 <     * @param counts current worker counts
1616 <     * @param maintainParallelism try to maintain parallelism
1617 <     */
1618 <    private boolean needSpare(int counts, boolean maintainParallelism) {
1619 <        int ps = parallelism;
1620 <        int rc = runningCountOf(counts);
1621 <        int tc = totalCountOf(counts);
1622 <        int runningDeficit = ps - rc;
1623 <        int totalSurplus = tc - ps;
1624 <        return (tc < maxPoolSize &&
1625 <                (rc == 0 || totalSurplus < 0 ||
1626 <                 (maintainParallelism &&
1627 <                  runningDeficit > totalSurplus &&
1628 <                  ForkJoinWorkerThread.hasQueuedTasks(workers))));
1629 <    }
1630 <
1631 <    /**
1632 <     * Adds a spare worker if lock available and no more than the
1633 <     * expected numbers of threads exist.
1634 <     *
1635 <     * @return true if successful
1636 <     */
1637 <    private boolean tryAddSpare(int expectedCounts) {
1638 <        final ReentrantLock lock = this.workerLock;
1639 <        int expectedRunning = runningCountOf(expectedCounts);
1640 <        int expectedTotal = totalCountOf(expectedCounts);
1641 <        boolean success = false;
1642 <        boolean locked = false;
1643 <        // confirm counts while locking; CAS after obtaining lock
1644 <        try {
1645 <            for (;;) {
1646 <                int s = workerCounts;
1647 <                int tc = totalCountOf(s);
1648 <                int rc = runningCountOf(s);
1649 <                if (rc > expectedRunning || tc > expectedTotal)
1650 <                    break;
1651 <                if (!locked && !(locked = lock.tryLock()))
1652 <                    break;
1653 <                if (casWorkerCounts(s, workerCountsFor(tc+1, rc+1))) {
1654 <                    createAndStartSpare(tc);
1655 <                    success = true;
1656 <                    break;
1657 <                }
1658 <            }
1659 <        } finally {
1660 <            if (locked)
1661 <                lock.unlock();
1662 <        }
1663 <        return success;
1664 <    }
1665 <
1666 <    /**
1667 <     * Adds the kth spare worker. On entry, pool counts are already
1668 <     * adjusted to reflect addition.
1669 <     */
1670 <    private void createAndStartSpare(int k) {
1671 <        ForkJoinWorkerThread w = null;
1672 <        ForkJoinWorkerThread[] ws = ensureWorkerArrayCapacity(k + 1);
1673 <        int len = ws.length;
1674 <        // Probably, we can place at slot k. If not, find empty slot
1675 <        if (k < len && ws[k] != null) {
1676 <            for (k = 0; k < len && ws[k] != null; ++k)
1677 <                ;
1678 <        }
1679 <        if (k < len && isProcessingTasks() && (w = createWorker(k)) != null) {
1680 <            ws[k] = w;
1681 <            w.start();
1682 <        }
1683 <        else
1684 <            updateWorkerCount(-1); // adjust on failure
1685 <        signalIdleWorkers();
1686 <    }
1687 <
1688 <    /**
1689 <     * Suspends calling thread w if there are excess threads.  Called
1690 <     * only from sync.  Spares are enqueued in a Treiber stack using
1691 <     * the same WaitQueueNodes as barriers.  They are resumed mainly
1692 <     * in preJoin, but are also woken on pool events that require all
1693 <     * threads to check run state.
1694 <     *
1695 <     * @param w the caller
1696 <     */
1697 <    private boolean suspendIfSpare(ForkJoinWorkerThread w) {
1698 <        WaitQueueNode node = null;
1699 <        for (;;) {
1700 <            int s = workerCounts;
1701 <            int rc = runningCountOf(s);
1702 <            int tc = totalCountOf(s);
1703 <            int ps = parallelism;
1704 <            // use tc as bound if rc transiently out of sync
1705 <            if (tc <= ps || rc <= ps)
1706 <                return false; // not a spare
1707 <            if (node == null)
1708 <                node = new WaitQueueNode(0, w);
1709 <            if (casWorkerCounts(s, workerCountsFor(tc, rc - 1)))
1710 <                break;
1711 <        }
1712 <        // push onto stack
1713 <        do {} while (!casSpareStack(node.next = spareStack, node));
1714 <        // block until released by resumeSpare
1715 <        while (!Thread.interrupted() && node.thread != null)
1716 <            LockSupport.park(this);
1717 <        return true;
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 <        }
1769 >        return terminationLatch.await(timeout, unit);
1770      }
1771  
1772      /**
# Line 1858 | Line 1849 | public class ForkJoinPool extends Abstra
1849                                      boolean maintainParallelism)
1850          throws InterruptedException {
1851          Thread t = Thread.currentThread();
1852 <        ForkJoinPool pool = ((t instanceof ForkJoinWorkerThread) ?
1853 <                             ((ForkJoinWorkerThread) t).pool : null);
1854 <        if (!blocker.isReleasable()) {
1855 <            try {
1856 <                if (pool == null ||
1866 <                    !pool.preBlock(blocker, maintainParallelism))
1867 <                    awaitBlocker(blocker);
1868 <            } finally {
1869 <                if (pool != null)
1870 <                    pool.updateRunningCount(1);
1871 <            }
1872 <        }
1852 >        if (t instanceof ForkJoinWorkerThread)
1853 >            ((ForkJoinWorkerThread) t).pool.
1854 >                doBlock(blocker, maintainParallelism);
1855 >        else
1856 >            awaitBlocker(blocker);
1857      }
1858  
1859 +    /**
1860 +     * Performs Non-FJ blocking
1861 +     */
1862      private static void awaitBlocker(ManagedBlocker blocker)
1863          throws InterruptedException {
1864          do {} while (!blocker.isReleasable() && !blocker.block());
# Line 1892 | Line 1879 | public class ForkJoinPool extends Abstra
1879      // Unsafe mechanics
1880  
1881      private static final sun.misc.Unsafe UNSAFE = sun.misc.Unsafe.getUnsafe();
1895    private static final long eventCountOffset =
1896        objectFieldOffset("eventCount", ForkJoinPool.class);
1882      private static final long workerCountsOffset =
1883          objectFieldOffset("workerCounts", ForkJoinPool.class);
1884 <    private static final long runControlOffset =
1885 <        objectFieldOffset("runControl", ForkJoinPool.class);
1886 <    private static final long syncStackOffset =
1887 <        objectFieldOffset("syncStack",ForkJoinPool.class);
1888 <    private static final long spareStackOffset =
1889 <        objectFieldOffset("spareStack", ForkJoinPool.class);
1890 <
1891 <    private boolean casEventCount(long cmp, long val) {
1892 <        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 <    }
1884 >    private static final long runStateOffset =
1885 >        objectFieldOffset("runState", ForkJoinPool.class);
1886 >    private static final long eventCountOffset =
1887 >        objectFieldOffset("eventCount", ForkJoinPool.class);
1888 >    private static final long eventWaitersOffset =
1889 >        objectFieldOffset("eventWaiters",ForkJoinPool.class);
1890 >    private static final long stealCountOffset =
1891 >        objectFieldOffset("stealCount",ForkJoinPool.class);
1892 >
1893  
1894      private static long objectFieldOffset(String field, Class<?> klazz) {
1895          try {

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines