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

Comparing jsr166/src/jsr166y/ForkJoinPool.java (file contents):
Revision 1.115 by jsr166, Thu Jan 26 19:10:27 2012 UTC vs.
Revision 1.127 by dl, Sun Mar 4 15:52:45 2012 UTC

# Line 5 | Line 5
5   */
6  
7   package jsr166y;
8
8   import java.util.ArrayList;
9   import java.util.Arrays;
10   import java.util.Collection;
# Line 21 | Line 20 | import java.util.concurrent.RunnableFutu
20   import java.util.concurrent.TimeUnit;
21   import java.util.concurrent.atomic.AtomicInteger;
22   import java.util.concurrent.atomic.AtomicLong;
23 < import java.util.concurrent.locks.ReentrantLock;
23 > import java.util.concurrent.locks.AbstractQueuedSynchronizer;
24   import java.util.concurrent.locks.Condition;
25  
26   /**
# Line 60 | Line 59 | import java.util.concurrent.locks.Condit
59   * convenient form for informal monitoring.
60   *
61   * <p> As is the case with other ExecutorServices, there are three
62 < * main task execution methods summarized in the following
63 < * table. These are designed to be used primarily by clients not
64 < * already engaged in fork/join computations in the current pool.  The
65 < * main forms of these methods accept instances of {@code
66 < * ForkJoinTask}, but overloaded forms also allow mixed execution of
67 < * plain {@code Runnable}- or {@code Callable}- based activities as
68 < * well.  However, tasks that are already executing in a pool should
69 < * normally instead use the within-computation forms listed in the
70 < * table unless using async event-style tasks that are not usually
71 < * joined, in which case there is little difference among choice of
73 < * methods.
62 > * main task execution methods summarized in the following table.
63 > * These are designed to be used primarily by clients not already
64 > * engaged in fork/join computations in the current pool.  The main
65 > * forms of these methods accept instances of {@code ForkJoinTask},
66 > * but overloaded forms also allow mixed execution of plain {@code
67 > * Runnable}- or {@code Callable}- based activities as well.  However,
68 > * tasks that are already executing in a pool should normally instead
69 > * use the within-computation forms listed in the table unless using
70 > * async event-style tasks that are not usually joined, in which case
71 > * there is little difference among choice of methods.
72   *
73   * <table BORDER CELLPADDING=3 CELLSPACING=1>
74   *  <tr>
# Line 131 | Line 129 | public class ForkJoinPool extends Abstra
129       *
130       * This class and its nested classes provide the main
131       * functionality and control for a set of worker threads:
132 <     * Submissions from non-FJ threads enter into submission
133 <     * queues. Workers take these tasks and typically split them into
134 <     * subtasks that may be stolen by other workers.  Preference rules
135 <     * give first priority to processing tasks from their own queues
136 <     * (LIFO or FIFO, depending on mode), then to randomized FIFO
137 <     * steals of tasks in other queues.
132 >     * Submissions from non-FJ threads enter into submission queues.
133 >     * Workers take these tasks and typically split them into subtasks
134 >     * that may be stolen by other workers.  Preference rules give
135 >     * first priority to processing tasks from their own queues (LIFO
136 >     * or FIFO, depending on mode), then to randomized FIFO steals of
137 >     * tasks in other queues.
138       *
139 <     * WorkQueues.
139 >     * WorkQueues
140       * ==========
141       *
142       * Most operations occur within work-stealing queues (in nested
# Line 156 | Line 154 | public class ForkJoinPool extends Abstra
154       * (http://research.sun.com/scalable/pubs/index.html) and
155       * "Idempotent work stealing" by Michael, Saraswat, and Vechev,
156       * PPoPP 2009 (http://portal.acm.org/citation.cfm?id=1504186).
157 <     * The main differences ultimately stem from gc requirements that
157 >     * The main differences ultimately stem from GC requirements that
158       * we null out taken slots as soon as we can, to maintain as small
159       * a footprint as possible even in programs generating huge
160       * numbers of tasks. To accomplish this, we shift the CAS
# Line 178 | Line 176 | public class ForkJoinPool extends Abstra
176       * If an attempted steal fails, a thief always chooses a different
177       * random victim target to try next. So, in order for one thief to
178       * progress, it suffices for any in-progress poll or new push on
179 <     * any empty queue to complete.
179 >     * any empty queue to complete. (This is why we normally use
180 >     * method pollAt and its variants that try once at the apparent
181 >     * base index, else consider alternative actions, rather than
182 >     * method poll.)
183       *
184       * This approach also enables support of a user mode in which local
185       * task processing is in FIFO, not LIFO order, simply by using
# Line 188 | Line 189 | public class ForkJoinPool extends Abstra
189       * rarely provide the best possible performance on a given
190       * machine, but portably provide good throughput by averaging over
191       * these factors.  (Further, even if we did try to use such
192 <     * information, we do not usually have a basis for exploiting
193 <     * it. For example, some sets of tasks profit from cache
194 <     * affinities, but others are harmed by cache pollution effects.)
192 >     * information, we do not usually have a basis for exploiting it.
193 >     * For example, some sets of tasks profit from cache affinities,
194 >     * but others are harmed by cache pollution effects.)
195       *
196       * WorkQueues are also used in a similar way for tasks submitted
197       * to the pool. We cannot mix these tasks in the same queues used
198       * for work-stealing (this would contaminate lifo/fifo
199 <     * processing). Instead, we loosely associate (via hashing)
200 <     * submission queues with submitting threads, and randomly scan
201 <     * these queues as well when looking for work. In essence,
202 <     * submitters act like workers except that they never take tasks,
203 <     * and they are multiplexed on to a finite number of shared work
204 <     * queues. However, classes are set up so that future extensions
205 <     * could allow submitters to optionally help perform tasks as
206 <     * well. Pool submissions from internal workers are also allowed,
207 <     * but use randomized rather than thread-hashed queue indices to
208 <     * avoid imbalance.  Insertion of tasks in shared mode requires a
199 >     * processing). Instead, we loosely associate submission queues
200 >     * with submitting threads, using a form of hashing.  The
201 >     * ThreadLocal Submitter class contains a value initially used as
202 >     * a hash code for choosing existing queues, but may be randomly
203 >     * repositioned upon contention with other submitters.  In
204 >     * essence, submitters act like workers except that they never
205 >     * take tasks, and they are multiplexed on to a finite number of
206 >     * shared work queues. However, classes are set up so that future
207 >     * extensions could allow submitters to optionally help perform
208 >     * tasks as well. Insertion of tasks in shared mode requires a
209       * lock (mainly to protect in the case of resizing) but we use
210       * only a simple spinlock (using bits in field runState), because
211 <     * submitters encountering a busy queue try or create others so
212 <     * never block.
211 >     * submitters encountering a busy queue move on to try or create
212 >     * other queues -- they block only when creating and registering
213 >     * new queues.
214       *
215 <     * Management.
215 >     * Management
216       * ==========
217       *
218       * The main throughput advantages of work-stealing stem from
# Line 220 | Line 222 | public class ForkJoinPool extends Abstra
222       * tactic for avoiding bottlenecks is packing nearly all
223       * essentially atomic control state into two volatile variables
224       * that are by far most often read (not written) as status and
225 <     * consistency checks
225 >     * consistency checks.
226       *
227       * Field "ctl" contains 64 bits holding all the information needed
228       * to atomically decide to add, inactivate, enqueue (on an event
# Line 246 | Line 248 | public class ForkJoinPool extends Abstra
248       * readers must tolerate null slots. Shared (submission) queues
249       * are at even indices, worker queues at odd indices. Grouping
250       * them together in this way simplifies and speeds up task
251 <     * scanning. To avoid flailing during start-up, the array is
252 <     * presized to hold twice #parallelism workers (which is unlikely
253 <     * to need further resizing during execution). But to avoid
254 <     * dealing with so many null slots, variable runState includes a
253 <     * mask for the nearest power of two that contains all current
254 <     * workers.  All worker thread creation is on-demand, triggered by
255 <     * task submissions, replacement of terminated workers, and/or
251 >     * scanning.
252 >     *
253 >     * All worker thread creation is on-demand, triggered by task
254 >     * submissions, replacement of terminated workers, and/or
255       * compensation for blocked workers. However, all other support
256       * code is set up to work with other policies.  To ensure that we
257       * do not hold on to worker references that would prevent GC, ALL
# Line 265 | Line 264 | public class ForkJoinPool extends Abstra
264       * both index-check and null-check the IDs. All such accesses
265       * ignore bad IDs by returning out early from what they are doing,
266       * since this can only be associated with termination, in which
267 <     * case it is OK to give up.
268 <     *
269 <     * All uses of the workQueues array check that it is non-null
270 <     * (even if previously non-null). This allows nulling during
271 <     * termination, which is currently not necessary, but remains an
272 <     * option for resource-revocation-based shutdown schemes. It also
274 <     * helps reduce JIT issuance of uncommon-trap code, which tends to
267 >     * case it is OK to give up.  All uses of the workQueues array
268 >     * also check that it is non-null (even if previously
269 >     * non-null). This allows nulling during termination, which is
270 >     * currently not necessary, but remains an option for
271 >     * resource-revocation-based shutdown schemes. It also helps
272 >     * reduce JIT issuance of uncommon-trap code, which tends to
273       * unnecessarily complicate control flow in some methods.
274       *
275       * Event Queuing. Unlike HPC work-stealing frameworks, we cannot
# Line 299 | Line 297 | public class ForkJoinPool extends Abstra
297       * some other queued worker rather than itself, which has the same
298       * net effect. Because enqueued workers may actually be rescanning
299       * rather than waiting, we set and clear the "parker" field of
300 <     * Workqueues to reduce unnecessary calls to unpark.  (This
300 >     * WorkQueues to reduce unnecessary calls to unpark.  (This
301       * requires a secondary recheck to avoid missed signals.)  Note
302       * the unusual conventions about Thread.interrupts surrounding
303       * parking and other blocking: Because interrupts are used solely
# Line 327 | Line 325 | public class ForkJoinPool extends Abstra
325       * terminating all workers after long periods of non-use.
326       *
327       * Shutdown and Termination. A call to shutdownNow atomically sets
328 <     * a runState bit and then (non-atomically) sets each workers
328 >     * a runState bit and then (non-atomically) sets each worker's
329       * runState status, cancels all unprocessed tasks, and wakes up
330       * all waiting workers.  Detecting whether termination should
331       * commence after a non-abrupt shutdown() call requires more work
# Line 336 | Line 334 | public class ForkJoinPool extends Abstra
334       * indication but non-abrupt shutdown still requires a rechecking
335       * scan for any workers that are inactive but not queued.
336       *
337 <     * Joining Tasks.
338 <     * ==============
337 >     * Joining Tasks
338 >     * =============
339       *
340       * Any of several actions may be taken when one worker is waiting
341 <     * to join a task stolen (or always held by) another.  Because we
341 >     * to join a task stolen (or always held) by another.  Because we
342       * are multiplexing many tasks on to a pool of workers, we can't
343       * just let them block (as in Thread.join).  We also cannot just
344       * reassign the joiner's run-time stack with another and replace
345       * it later, which would be a form of "continuation", that even if
346       * possible is not necessarily a good idea since we sometimes need
347 <     * both an unblocked task and its continuation to
348 <     * progress. Instead we combine two tactics:
347 >     * both an unblocked task and its continuation to progress.
348 >     * Instead we combine two tactics:
349       *
350       *   Helping: Arranging for the joiner to execute some task that it
351       *      would be running if the steal had not occurred.
# Line 382 | Line 380 | public class ForkJoinPool extends Abstra
380       * (http://portal.acm.org/citation.cfm?id=155354). It differs in
381       * that: (1) We only maintain dependency links across workers upon
382       * steals, rather than use per-task bookkeeping.  This sometimes
383 <     * requires a linear scan of workers array to locate stealers, but
384 <     * often doesn't because stealers leave hints (that may become
383 >     * requires a linear scan of workQueues array to locate stealers,
384 >     * but often doesn't because stealers leave hints (that may become
385       * stale/wrong) of where to locate them.  A stealHint is only a
386       * hint because a worker might have had multiple steals and the
387       * hint records only one of them (usually the most current).
# Line 394 | Line 392 | public class ForkJoinPool extends Abstra
392       * which means that we miss links in the chain during long-lived
393       * tasks, GC stalls etc (which is OK since blocking in such cases
394       * is usually a good idea).  (4) We bound the number of attempts
395 <     * to find work (see MAX_HELP_DEPTH) and fall back to suspending
396 <     * the worker and if necessary replacing it with another.
395 >     * to find work (see MAX_HELP) and fall back to suspending the
396 >     * worker and if necessary replacing it with another.
397       *
398       * It is impossible to keep exactly the target parallelism number
399       * of threads running at any given time.  Determining the
400       * existence of conservatively safe helping targets, the
401       * availability of already-created spares, and the apparent need
402       * to create new spares are all racy, so we rely on multiple
403 <     * retries of each.  Currently, in keeping with on-demand
404 <     * signalling policy, we compensate only if blocking would leave
405 <     * less than one active (non-waiting, non-blocked) worker.
406 <     * Additionally, to avoid some false alarms due to GC, lagging
407 <     * counters, system activity, etc, compensated blocking for joins
408 <     * is only attempted after rechecks stabilize in
409 <     * ForkJoinTask.awaitJoin. (Retries are interspersed with
410 <     * Thread.yield, for good citizenship.)
403 >     * retries of each.  Compensation in the apparent absence of
404 >     * helping opportunities is challenging to control on JVMs, where
405 >     * GC and other activities can stall progress of tasks that in
406 >     * turn stall out many other dependent tasks, without us being
407 >     * able to determine whether they will ever require compensation.
408 >     * Even though work-stealing otherwise encounters little
409 >     * degradation in the presence of more threads than cores,
410 >     * aggressively adding new threads in such cases entails risk of
411 >     * unwanted positive feedback control loops in which more threads
412 >     * cause more dependent stalls (as well as delayed progress of
413 >     * unblocked threads to the point that we know they are available)
414 >     * leading to more situations requiring more threads, and so
415 >     * on. This aspect of control can be seen as an (analytically
416 >     * intractable) game with an opponent that may choose the worst
417 >     * (for us) active thread to stall at any time.  We take several
418 >     * precautions to bound losses (and thus bound gains), mainly in
419 >     * methods tryCompensate and awaitJoin: (1) We only try
420 >     * compensation after attempting enough helping steps (measured
421 >     * via counting and timing) that we have already consumed the
422 >     * estimated cost of creating and activating a new thread.  (2) We
423 >     * allow up to 50% of threads to be blocked before initially
424 >     * adding any others, and unless completely saturated, check that
425 >     * some work is available for a new worker before adding. Also, we
426 >     * create up to only 50% more threads until entering a mode that
427 >     * only adds a thread if all others are possibly blocked.  All
428 >     * together, this means that we might be half as fast to react,
429 >     * and create half as many threads as possible in the ideal case,
430 >     * but present vastly fewer anomalies in all other cases compared
431 >     * to both more aggressive and more conservative alternatives.
432       *
433       * Style notes: There is a lot of representation-level coupling
434       * among classes ForkJoinPool, ForkJoinWorkerThread, and
# Line 417 | Line 436 | public class ForkJoinPool extends Abstra
436       * managed by ForkJoinPool, so are directly accessed.  There is
437       * little point trying to reduce this, since any associated future
438       * changes in representations will need to be accompanied by
439 <     * algorithmic changes anyway. All together, these low-level
440 <     * implementation choices produce as much as a factor of 4
441 <     * performance improvement compared to naive implementations, and
442 <     * enable the processing of billions of tasks per second, at the
443 <     * expense of some ugliness.
444 <     *
445 <     * Methods signalWork() and scan() are the main bottlenecks so are
446 <     * especially heavily micro-optimized/mangled.  There are lots of
447 <     * inline assignments (of form "while ((local = field) != 0)")
448 <     * which are usually the simplest way to ensure the required read
449 <     * orderings (which are sometimes critical). This leads to a
450 <     * "C"-like style of listing declarations of these locals at the
451 <     * heads of methods or blocks.  There are several occurrences of
452 <     * the unusual "do {} while (!cas...)"  which is the simplest way
453 <     * to force an update of a CAS'ed variable. There are also other
454 <     * coding oddities that help some methods perform reasonably even
455 <     * when interpreted (not compiled).
456 <     *
457 <     * The order of declarations in this file is: (1) declarations of
458 <     * statics (2) fields (along with constants used when unpacking
459 <     * some of them), listed in an order that tends to reduce
460 <     * contention among them a bit under most JVMs; (3) nested
461 <     * classes; (4) internal control methods; (5) callbacks and other
462 <     * support for ForkJoinTask methods; (6) exported methods (plus a
444 <     * few little helpers); (7) static block initializing all statics
445 <     * in a minimally dependent order.
439 >     * algorithmic changes anyway. Several methods intrinsically
440 >     * sprawl because they must accumulate sets of consistent reads of
441 >     * volatiles held in local variables.  Methods signalWork() and
442 >     * scan() are the main bottlenecks, so are especially heavily
443 >     * micro-optimized/mangled.  There are lots of inline assignments
444 >     * (of form "while ((local = field) != 0)") which are usually the
445 >     * simplest way to ensure the required read orderings (which are
446 >     * sometimes critical). This leads to a "C"-like style of listing
447 >     * declarations of these locals at the heads of methods or blocks.
448 >     * There are several occurrences of the unusual "do {} while
449 >     * (!cas...)"  which is the simplest way to force an update of a
450 >     * CAS'ed variable. There are also other coding oddities that help
451 >     * some methods perform reasonably even when interpreted (not
452 >     * compiled).
453 >     *
454 >     * The order of declarations in this file is:
455 >     * (1) Static utility functions
456 >     * (2) Nested (static) classes
457 >     * (3) Static fields
458 >     * (4) Fields, along with constants used when unpacking some of them
459 >     * (5) Internal control methods
460 >     * (6) Callbacks and other support for ForkJoinTask methods
461 >     * (7) Exported methods
462 >     * (8) Static block initializing statics in minimally dependent order
463       */
464  
465 +    // Static utilities
466 +
467 +    /**
468 +     * If there is a security manager, makes sure caller has
469 +     * permission to modify threads.
470 +     */
471 +    private static void checkPermission() {
472 +        SecurityManager security = System.getSecurityManager();
473 +        if (security != null)
474 +            security.checkPermission(modifyThreadPermission);
475 +    }
476 +
477 +    // Nested classes
478 +
479      /**
480       * Factory for creating new {@link ForkJoinWorkerThread}s.
481       * A {@code ForkJoinWorkerThreadFactory} must be defined and used
# Line 473 | Line 504 | public class ForkJoinPool extends Abstra
504      }
505  
506      /**
507 <     * Creates a new ForkJoinWorkerThread. This factory is used unless
508 <     * overridden in ForkJoinPool constructors.
509 <     */
510 <    public static final ForkJoinWorkerThreadFactory
511 <        defaultForkJoinWorkerThreadFactory;
512 <
513 <    /**
514 <     * Permission required for callers of methods that may start or
515 <     * kill threads.
516 <     */
517 <    private static final RuntimePermission modifyThreadPermission;
518 <
519 <    /**
520 <     * If there is a security manager, makes sure caller has
521 <     * permission to modify threads.
522 <     */
523 <    private static void checkPermission() {
524 <        SecurityManager security = System.getSecurityManager();
525 <        if (security != null)
526 <            security.checkPermission(modifyThreadPermission);
507 >     * A simple non-reentrant lock used for exclusion when managing
508 >     * queues and workers. We use a custom lock so that we can readily
509 >     * probe lock state in constructions that check among alternative
510 >     * actions. The lock is normally only very briefly held, and
511 >     * sometimes treated as a spinlock, but other usages block to
512 >     * reduce overall contention in those cases where locked code
513 >     * bodies perform allocation/resizing.
514 >     */
515 >    static final class Mutex extends AbstractQueuedSynchronizer {
516 >        public final boolean tryAcquire(int ignore) {
517 >            return compareAndSetState(0, 1);
518 >        }
519 >        public final boolean tryRelease(int ignore) {
520 >            setState(0);
521 >            return true;
522 >        }
523 >        public final void lock() { acquire(0); }
524 >        public final void unlock() { release(0); }
525 >        public final boolean isHeldExclusively() { return getState() == 1; }
526 >        public final Condition newCondition() { return new ConditionObject(); }
527      }
528  
529      /**
530 <     * Generator for assigning sequence numbers as pool names.
531 <     */
532 <    private static final AtomicInteger poolNumberGenerator;
533 <
503 <    /**
504 <     * Bits and masks for control variables
505 <     *
506 <     * Field ctl is a long packed with:
507 <     * AC: Number of active running workers minus target parallelism (16 bits)
508 <     * TC: Number of total workers minus target parallelism (16 bits)
509 <     * ST: true if pool is terminating (1 bit)
510 <     * EC: the wait count of top waiting thread (15 bits)
511 <     * ID: ~(poolIndex >>> 1) of top of Treiber stack of waiters (16 bits)
512 <     *
513 <     * When convenient, we can extract the upper 32 bits of counts and
514 <     * the lower 32 bits of queue state, u = (int)(ctl >>> 32) and e =
515 <     * (int)ctl.  The ec field is never accessed alone, but always
516 <     * together with id and st. The offsets of counts by the target
517 <     * parallelism and the positionings of fields makes it possible to
518 <     * perform the most common checks via sign tests of fields: When
519 <     * ac is negative, there are not enough active workers, when tc is
520 <     * negative, there are not enough total workers, when id is
521 <     * negative, there is at least one waiting worker, and when e is
522 <     * negative, the pool is terminating.  To deal with these possibly
523 <     * negative fields, we use casts in and out of "short" and/or
524 <     * signed shifts to maintain signedness.
525 <     *
526 <     * When a thread is queued (inactivated), its eventCount field is
527 <     * negative, which is the only way to tell if a worker is
528 <     * prevented from executing tasks, even though it must continue to
529 <     * scan for them to avoid queuing races.
530 <     *
531 <     * Field runState is an int packed with:
532 <     * SHUTDOWN: true if shutdown is enabled (1 bit)
533 <     * SEQ:  a sequence number updated upon (de)registering workers (15 bits)
534 <     * MASK: mask (power of 2 - 1) covering all registered poolIndexes (16 bits)
535 <     *
536 <     * The combination of mask and sequence number enables simple
537 <     * consistency checks: Staleness of read-only operations on the
538 <     * workers and queues arrays can be checked by comparing runState
539 <     * before vs after the reads. The low 16 bits (i.e, anding with
540 <     * SMASK) hold (the smallest power of two covering all worker
541 <     * indices, minus one.  The mask for queues (vs workers) is twice
542 <     * this value plus 1.
543 <     */
544 <
545 <    // bit positions/shifts for fields
546 <    private static final int  AC_SHIFT   = 48;
547 <    private static final int  TC_SHIFT   = 32;
548 <    private static final int  ST_SHIFT   = 31;
549 <    private static final int  EC_SHIFT   = 16;
550 <
551 <    // bounds
552 <    private static final int  MAX_ID     = 0x7fff;  // max poolIndex
553 <    private static final int  SMASK      = 0xffff;  // mask short bits
554 <    private static final int  SHORT_SIGN = 1 << 15;
555 <    private static final int  INT_SIGN   = 1 << 31;
556 <
557 <    // masks
558 <    private static final long STOP_BIT   = 0x0001L << ST_SHIFT;
559 <    private static final long AC_MASK    = ((long)SMASK) << AC_SHIFT;
560 <    private static final long TC_MASK    = ((long)SMASK) << TC_SHIFT;
561 <
562 <    // units for incrementing and decrementing
563 <    private static final long TC_UNIT    = 1L << TC_SHIFT;
564 <    private static final long AC_UNIT    = 1L << AC_SHIFT;
565 <
566 <    // masks and units for dealing with u = (int)(ctl >>> 32)
567 <    private static final int  UAC_SHIFT  = AC_SHIFT - 32;
568 <    private static final int  UTC_SHIFT  = TC_SHIFT - 32;
569 <    private static final int  UAC_MASK   = SMASK << UAC_SHIFT;
570 <    private static final int  UTC_MASK   = SMASK << UTC_SHIFT;
571 <    private static final int  UAC_UNIT   = 1 << UAC_SHIFT;
572 <    private static final int  UTC_UNIT   = 1 << UTC_SHIFT;
573 <
574 <    // masks and units for dealing with e = (int)ctl
575 <    private static final int E_MASK      = 0x7fffffff; // no STOP_BIT
576 <    private static final int E_SEQ       = 1 << EC_SHIFT;
577 <
578 <    // runState bits
579 <    private static final int SHUTDOWN    = 1 << 31;
580 <    private static final int RS_SEQ      = 1 << 16;
581 <    private static final int RS_SEQ_MASK = 0x7fff0000;
582 <
583 <    // access mode for WorkQueue
584 <    static final int LIFO_QUEUE          =  0;
585 <    static final int FIFO_QUEUE          =  1;
586 <    static final int SHARED_QUEUE        = -1;
587 <
588 <    /**
589 <     * The wakeup interval (in nanoseconds) for a worker waiting for a
590 <     * task when the pool is quiescent to instead try to shrink the
591 <     * number of workers.  The exact value does not matter too
592 <     * much. It must be short enough to release resources during
593 <     * sustained periods of idleness, but not so short that threads
594 <     * are continually re-created.
595 <     */
596 <    private static final long SHRINK_RATE =
597 <        4L * 1000L * 1000L * 1000L; // 4 seconds
598 <
599 <    /**
600 <     * The timeout value for attempted shrinkage, includes
601 <     * some slop to cope with system timer imprecision.
602 <     */
603 <    private static final long SHRINK_TIMEOUT = SHRINK_RATE - (SHRINK_RATE / 10);
604 <
605 <    /**
606 <     * The maximum stolen->joining link depth allowed in tryHelpStealer.
607 <     * Depths for legitimate chains are unbounded, but we use a fixed
608 <     * constant to avoid (otherwise unchecked) cycles and to bound
609 <     * staleness of traversal parameters at the expense of sometimes
610 <     * blocking when we could be helping.
611 <     */
612 <    private static final int MAX_HELP_DEPTH = 16;
613 <
614 <    /*
615 <     * Field layout order in this class tends to matter more than one
616 <     * would like. Runtime layout order is only loosely related to
617 <     * declaration order and may differ across JVMs, but the following
618 <     * empirically works OK on current JVMs.
530 >     * Class for artificial tasks that are used to replace the target
531 >     * of local joins if they are removed from an interior queue slot
532 >     * in WorkQueue.tryRemoveAndExec. We don't need the proxy to
533 >     * actually do anything beyond having a unique identity.
534       */
535 <
536 <    volatile long ctl;                       // main pool control
537 <    final int parallelism;                   // parallelism level
538 <    final int localMode;                     // per-worker scheduling mode
539 <    int nextPoolIndex;                       // hint used in registerWorker
540 <    volatile int runState;                   // shutdown status, seq, and mask
626 <    WorkQueue[] workQueues;                  // main registry
627 <    final ReentrantLock lock;                // for registration
628 <    final Condition termination;             // for awaitTermination
629 <    final ForkJoinWorkerThreadFactory factory; // factory for new workers
630 <    final Thread.UncaughtExceptionHandler ueh; // per-worker UEH
631 <    final AtomicLong stealCount;             // collect counts when terminated
632 <    final AtomicInteger nextWorkerNumber;    // to create worker name string
633 <    final String workerNamePrefix;           // Prefix for assigning worker names
535 >    static final class EmptyTask extends ForkJoinTask<Void> {
536 >        EmptyTask() { status = ForkJoinTask.NORMAL; } // force done
537 >        public final Void getRawResult() { return null; }
538 >        public final void setRawResult(Void x) {}
539 >        public final boolean exec() { return true; }
540 >    }
541  
542      /**
543       * Queues supporting work-stealing as well as external task
# Line 681 | Line 588 | public class ForkJoinPool extends Abstra
588       * avoiding really bad worst-case access. (Until better JVM
589       * support is in place, this padding is dependent on transient
590       * properties of JVM field layout rules.)  We also take care in
591 <     * allocating and sizing and resizing the array. Non-shared queue
591 >     * allocating, sizing and resizing the array. Non-shared queue
592       * arrays are initialized (via method growArray) by workers before
593       * use. Others are allocated on first use.
594       */
595      static final class WorkQueue {
596          /**
597           * Capacity of work-stealing queue array upon initialization.
598 <         * Must be a power of two; at least 4, but set larger to
599 <         * reduce cacheline sharing among queues.
598 >         * Must be a power of two; at least 4, but should be larger to
599 >         * reduce or eliminate cacheline sharing among queues.
600 >         * Currently, it is much larger, as a partial workaround for
601 >         * the fact that JVMs often place arrays in locations that
602 >         * share GC bookkeeping (especially cardmarks) such that
603 >         * per-write accesses encounter serious memory contention.
604           */
605 <        static final int INITIAL_QUEUE_CAPACITY = 1 << 8;
605 >        static final int INITIAL_QUEUE_CAPACITY = 1 << 13;
606  
607          /**
608           * Maximum size for queue arrays. Must be a power of two less
# Line 715 | Line 626 | public class ForkJoinPool extends Abstra
626          volatile int base;         // index of next slot for poll
627          int top;                   // index of next slot for push
628          ForkJoinTask<?>[] array;   // the elements (initially unallocated)
629 +        final ForkJoinPool pool;   // the containing pool (may be null)
630          final ForkJoinWorkerThread owner; // owning thread or null if shared
631          volatile Thread parker;    // == owner during call to park; else null
632          ForkJoinTask<?> currentJoin;  // task being joined in awaitJoin
633          ForkJoinTask<?> currentSteal; // current non-local task being executed
634          // Heuristic padding to ameliorate unfortunate memory placements
635 <        Object p00, p01, p02, p03, p04, p05, p06, p07, p08, p09, p0a;
635 >        Object p00, p01, p02, p03, p04, p05, p06, p07;
636 >        Object p08, p09, p0a, p0b, p0c, p0d, p0e;
637  
638 <        WorkQueue(ForkJoinWorkerThread owner, int mode) {
726 <            this.owner = owner;
638 >        WorkQueue(ForkJoinPool pool, ForkJoinWorkerThread owner, int mode) {
639              this.mode = mode;
640 +            this.pool = pool;
641 +            this.owner = owner;
642              // Place indices in the center of array (that is not yet allocated)
643              base = top = INITIAL_QUEUE_CAPACITY >>> 1;
644          }
645  
646          /**
647 <         * Returns number of tasks in the queue
647 >         * Returns the approximate number of tasks in the queue.
648           */
649          final int queueSize() {
650 <            int n = base - top; // non-owner callers must read base first
651 <            return (n >= 0) ? 0 : -n;
650 >            int n = base - top;       // non-owner callers must read base first
651 >            return (n >= 0) ? 0 : -n; // ignore transient negative
652 >        }
653 >
654 >        /**
655 >         * Provides a more accurate estimate of whether this queue has
656 >         * any tasks than does queueSize, by checking whether a
657 >         * near-empty queue has at least one unclaimed task.
658 >         */
659 >        final boolean isEmpty() {
660 >            ForkJoinTask<?>[] a; int m, s;
661 >            int n = base - (s = top);
662 >            return (n >= 0 ||
663 >                    (n == -1 &&
664 >                     ((a = array) == null ||
665 >                      (m = a.length - 1) < 0 ||
666 >                      U.getObjectVolatile
667 >                      (a, ((m & (s - 1)) << ASHIFT) + ABASE) == null)));
668          }
669  
670          /**
671           * Pushes a task. Call only by owner in unshared queues.
672           *
673           * @param task the task. Caller must ensure non-null.
674 <         * @param p, if non-null, pool to signal if necessary
745 <         * @throw RejectedExecutionException if array cannot
746 <         * be resized
674 >         * @throw RejectedExecutionException if array cannot be resized
675           */
676 <        final void push(ForkJoinTask<?> task, ForkJoinPool p) {
677 <            ForkJoinTask<?>[] a;
676 >        final void push(ForkJoinTask<?> task) {
677 >            ForkJoinTask<?>[] a; ForkJoinPool p;
678              int s = top, m, n;
679              if ((a = array) != null) {    // ignore if queue removed
680                  U.putOrderedObject
681                      (a, (((m = a.length - 1) & s) << ASHIFT) + ABASE, task);
682                  if ((n = (top = s + 1) - base) <= 2) {
683 <                    if (p != null)
683 >                    if ((p = pool) != null)
684                          p.signalWork();
685                  }
686                  else if (n >= m)
# Line 771 | Line 699 | public class ForkJoinPool extends Abstra
699              boolean submitted = false;
700              if (runState == 0 && U.compareAndSwapInt(this, RUNSTATE, 0, 1)) {
701                  ForkJoinTask<?>[] a = array;
702 <                int s = top, n = s - base;
702 >                int s = top;
703                  try {
704 <                    if ((a != null && n < a.length - 1) ||
704 >                    if ((a != null && a.length > s + 1 - base) ||
705                          (a = growArray(false)) != null) { // must presize
706                          int j = (((a.length - 1) & s) << ASHIFT) + ABASE;
707                          U.putObject(a, (long)j, task);    // don't need "ordered"
# Line 788 | Line 716 | public class ForkJoinPool extends Abstra
716          }
717  
718          /**
719 <         * Takes next task, if one exists, in FIFO order.
719 >         * Takes next task, if one exists, in LIFO order.  Call only
720 >         * by owner in unshared queues. (We do not have a shared
721 >         * version of this method because it is never needed.)
722           */
723 <        final ForkJoinTask<?> poll() {
724 <            ForkJoinTask<?>[] a; int b, i;
725 <            while ((b = base) - top < 0 && (a = array) != null &&
726 <                   (i = (a.length - 1) & b) >= 0) {
727 <                int j = (i << ASHIFT) + ABASE;
728 <                ForkJoinTask<?> t = (ForkJoinTask<?>)U.getObjectVolatile(a, j);
729 <                if (t != null && base == b &&
723 >        final ForkJoinTask<?> pop() {
724 >            ForkJoinTask<?>[] a; ForkJoinTask<?> t; int m;
725 >            if ((a = array) != null && (m = a.length - 1) >= 0) {
726 >                for (int s; (s = top - 1) - base >= 0;) {
727 >                    long j = ((m & s) << ASHIFT) + ABASE;
728 >                    if ((t = (ForkJoinTask<?>)U.getObject(a, j)) == null)
729 >                        break;
730 >                    if (U.compareAndSwapObject(a, j, t, null)) {
731 >                        top = s;
732 >                        return t;
733 >                    }
734 >                }
735 >            }
736 >            return null;
737 >        }
738 >
739 >        /**
740 >         * Takes a task in FIFO order if b is base of queue and a task
741 >         * can be claimed without contention. Specialized versions
742 >         * appear in ForkJoinPool methods scan and tryHelpStealer.
743 >         */
744 >        final ForkJoinTask<?> pollAt(int b) {
745 >            ForkJoinTask<?> t; ForkJoinTask<?>[] a;
746 >            if ((a = array) != null) {
747 >                int j = (((a.length - 1) & b) << ASHIFT) + ABASE;
748 >                if ((t = (ForkJoinTask<?>)U.getObjectVolatile(a, j)) != null &&
749 >                    base == b &&
750                      U.compareAndSwapObject(a, j, t, null)) {
751                      base = b + 1;
752                      return t;
# Line 806 | Line 756 | public class ForkJoinPool extends Abstra
756          }
757  
758          /**
759 <         * Takes next task, if one exists, in LIFO order.
810 <         * Call only by owner in unshared queues.
759 >         * Takes next task, if one exists, in FIFO order.
760           */
761 <        final ForkJoinTask<?> pop() {
762 <            ForkJoinTask<?> t; int m;
763 <            ForkJoinTask<?>[] a = array;
764 <            if (a != null && (m = a.length - 1) >= 0) {
765 <                for (int s; (s = top - 1) - base >= 0;) {
766 <                    int j = ((m & s) << ASHIFT) + ABASE;
767 <                    if ((t = (ForkJoinTask<?>)U.getObjectVolatile(a, j)) == null)
768 <                        break;
769 <                    if (U.compareAndSwapObject(a, j, t, null)) {
821 <                        top = s;
761 >        final ForkJoinTask<?> poll() {
762 >            ForkJoinTask<?>[] a; int b; ForkJoinTask<?> t;
763 >            while ((b = base) - top < 0 && (a = array) != null) {
764 >                int j = (((a.length - 1) & b) << ASHIFT) + ABASE;
765 >                t = (ForkJoinTask<?>)U.getObjectVolatile(a, j);
766 >                if (t != null) {
767 >                    if (base == b &&
768 >                        U.compareAndSwapObject(a, j, t, null)) {
769 >                        base = b + 1;
770                          return t;
771                      }
772                  }
773 +                else if (base == b) {
774 +                    if (b + 1 == top)
775 +                        break;
776 +                    Thread.yield(); // wait for lagging update
777 +                }
778              }
779              return null;
780          }
# Line 846 | Line 799 | public class ForkJoinPool extends Abstra
799          }
800  
801          /**
849         * Returns task at index b if b is current base of queue.
850         */
851        final ForkJoinTask<?> pollAt(int b) {
852            ForkJoinTask<?>[] a; int i;
853            ForkJoinTask<?> task = null;
854            if ((a = array) != null && (i = ((a.length - 1) & b)) >= 0) {
855                int j = (i << ASHIFT) + ABASE;
856                ForkJoinTask<?> t = (ForkJoinTask<?>)U.getObjectVolatile(a, j);
857                if (t != null && base == b &&
858                    U.compareAndSwapObject(a, j, t, null)) {
859                    base = b + 1;
860                    task = t;
861                }
862            }
863            return task;
864        }
865
866        /**
802           * Pops the given task only if it is at the current top.
803           */
804          final boolean tryUnpush(ForkJoinTask<?> t) {
# Line 881 | Line 816 | public class ForkJoinPool extends Abstra
816           * Polls the given task only if it is at the current base.
817           */
818          final boolean pollFor(ForkJoinTask<?> task) {
819 <            ForkJoinTask<?>[] a; int b, i;
820 <            if ((b = base) - top < 0 && (a = array) != null &&
821 <                (i = (a.length - 1) & b) >= 0) {
887 <                int j = (i << ASHIFT) + ABASE;
819 >            ForkJoinTask<?>[] a; int b;
820 >            if ((b = base) - top < 0 && (a = array) != null) {
821 >                int j = (((a.length - 1) & b) << ASHIFT) + ABASE;
822                  if (U.getObjectVolatile(a, j) == task && base == b &&
823                      U.compareAndSwapObject(a, j, task, null)) {
824                      base = b + 1;
# Line 895 | Line 829 | public class ForkJoinPool extends Abstra
829          }
830  
831          /**
898         * If present, removes from queue and executes the given task, or
899         * any other cancelled task. Returns (true) immediately on any CAS
900         * or consistency check failure so caller can retry.
901         *
902         * @return false if no progress can be made
903         */
904        final boolean tryRemoveAndExec(ForkJoinTask<?> task) {
905            boolean removed = false, empty = true, progress = true;
906            ForkJoinTask<?>[] a; int m, s, b, n;
907            if ((a = array) != null && (m = a.length - 1) >= 0 &&
908                (n = (s = top) - (b = base)) > 0) {
909                for (ForkJoinTask<?> t;;) {           // traverse from s to b
910                    int j = ((--s & m) << ASHIFT) + ABASE;
911                    t = (ForkJoinTask<?>)U.getObjectVolatile(a, j);
912                    if (t == null)                    // inconsistent length
913                        break;
914                    else if (t == task) {
915                        if (s + 1 == top) {           // pop
916                            if (!U.compareAndSwapObject(a, j, task, null))
917                                break;
918                            top = s;
919                            removed = true;
920                        }
921                        else if (base == b)           // replace with proxy
922                            removed = U.compareAndSwapObject(a, j, task,
923                                                             new EmptyTask());
924                        break;
925                    }
926                    else if (t.status >= 0)
927                        empty = false;
928                    else if (s + 1 == top) {          // pop and throw away
929                        if (U.compareAndSwapObject(a, j, t, null))
930                            top = s;
931                        break;
932                    }
933                    if (--n == 0) {
934                        if (!empty && base == b)
935                            progress = false;
936                        break;
937                    }
938                }
939            }
940            if (removed)
941                task.doExec();
942            return progress;
943        }
944
945        /**
832           * Initializes or doubles the capacity of array. Call either
833           * by owner or with lock held -- it is OK for base, but not
834           * top, to move while resizings are in progress.
# Line 978 | Line 864 | public class ForkJoinPool extends Abstra
864          }
865  
866          /**
867 <         * Removes and cancels all known tasks, ignoring any exceptions
867 >         * Removes and cancels all known tasks, ignoring any exceptions.
868           */
869          final void cancelAll() {
870              ForkJoinTask.cancelIgnoringExceptions(currentJoin);
# Line 987 | Line 873 | public class ForkJoinPool extends Abstra
873                  ForkJoinTask.cancelIgnoringExceptions(t);
874          }
875  
876 +        /**
877 +         * Computes next value for random probes.  Scans don't require
878 +         * a very high quality generator, but also not a crummy one.
879 +         * Marsaglia xor-shift is cheap and works well enough.  Note:
880 +         * This is manually inlined in its usages in ForkJoinPool to
881 +         * avoid writes inside busy scan loops.
882 +         */
883 +        final int nextSeed() {
884 +            int r = seed;
885 +            r ^= r << 13;
886 +            r ^= r >>> 17;
887 +            return seed = r ^= r << 5;
888 +        }
889 +
890          // Execution methods
891  
892          /**
893 <         * Removes and runs tasks until empty, using local mode
994 <         * ordering.
893 >         * Pops and runs tasks until empty.
894           */
895 <        final void runLocalTasks() {
896 <            if (base - top < 0) {
897 <                for (ForkJoinTask<?> t; (t = nextLocalTask()) != null; )
895 >        private void popAndExecAll() {
896 >            // A bit faster than repeated pop calls
897 >            ForkJoinTask<?>[] a; int m, s; long j; ForkJoinTask<?> t;
898 >            while ((a = array) != null && (m = a.length - 1) >= 0 &&
899 >                   (s = top - 1) - base >= 0 &&
900 >                   (t = ((ForkJoinTask<?>)
901 >                         U.getObject(a, j = ((m & s) << ASHIFT) + ABASE)))
902 >                   != null) {
903 >                if (U.compareAndSwapObject(a, j, t, null)) {
904 >                    top = s;
905                      t.doExec();
906 +                }
907              }
908          }
909  
910          /**
911 +         * Polls and runs tasks until empty.
912 +         */
913 +        private void pollAndExecAll() {
914 +            for (ForkJoinTask<?> t; (t = poll()) != null;)
915 +                t.doExec();
916 +        }
917 +
918 +        /**
919 +         * If present, removes from queue and executes the given task, or
920 +         * any other cancelled task. Returns (true) immediately on any CAS
921 +         * or consistency check failure so caller can retry.
922 +         *
923 +         * @return false if no progress can be made
924 +         */
925 +        final boolean tryRemoveAndExec(ForkJoinTask<?> task) {
926 +            boolean removed = false, empty = true, progress = true;
927 +            ForkJoinTask<?>[] a; int m, s, b, n;
928 +            if ((a = array) != null && (m = a.length - 1) >= 0 &&
929 +                (n = (s = top) - (b = base)) > 0) {
930 +                for (ForkJoinTask<?> t;;) {           // traverse from s to b
931 +                    int j = ((--s & m) << ASHIFT) + ABASE;
932 +                    t = (ForkJoinTask<?>)U.getObjectVolatile(a, j);
933 +                    if (t == null)                    // inconsistent length
934 +                        break;
935 +                    else if (t == task) {
936 +                        if (s + 1 == top) {           // pop
937 +                            if (!U.compareAndSwapObject(a, j, task, null))
938 +                                break;
939 +                            top = s;
940 +                            removed = true;
941 +                        }
942 +                        else if (base == b)           // replace with proxy
943 +                            removed = U.compareAndSwapObject(a, j, task,
944 +                                                             new EmptyTask());
945 +                        break;
946 +                    }
947 +                    else if (t.status >= 0)
948 +                        empty = false;
949 +                    else if (s + 1 == top) {          // pop and throw away
950 +                        if (U.compareAndSwapObject(a, j, t, null))
951 +                            top = s;
952 +                        break;
953 +                    }
954 +                    if (--n == 0) {
955 +                        if (!empty && base == b)
956 +                            progress = false;
957 +                        break;
958 +                    }
959 +                }
960 +            }
961 +            if (removed)
962 +                task.doExec();
963 +            return progress;
964 +        }
965 +
966 +        /**
967           * Executes a top-level task and any local tasks remaining
968           * after execution.
1006         *
1007         * @return true unless terminating
969           */
970 <        final boolean runTask(ForkJoinTask<?> t) {
1010 <            boolean alive = true;
970 >        final void runTask(ForkJoinTask<?> t) {
971              if (t != null) {
972                  currentSteal = t;
973                  t.doExec();
974 <                runLocalTasks();
974 >                if (top != base) {       // process remaining local tasks
975 >                    if (mode == 0)
976 >                        popAndExecAll();
977 >                    else
978 >                        pollAndExecAll();
979 >                }
980                  ++nsteals;
981                  currentSteal = null;
982              }
1018            else if (runState < 0)            // terminating
1019                alive = false;
1020            return alive;
983          }
984  
985          /**
986 <         * Executes a non-top-level (stolen) task
986 >         * Executes a non-top-level (stolen) task.
987           */
988          final void runSubtask(ForkJoinTask<?> t) {
989              if (t != null) {
# Line 1033 | Line 995 | public class ForkJoinPool extends Abstra
995          }
996  
997          /**
998 <         * Computes next value for random probes.  Scans don't require
1037 <         * a very high quality generator, but also not a crummy one.
1038 <         * Marsaglia xor-shift is cheap and works well enough.  Note:
1039 <         * This is manually inlined in several usages in ForkJoinPool
1040 <         * to avoid writes inside busy scan loops.
998 >         * Returns true if owned and not known to be blocked.
999           */
1000 <        final int nextSeed() {
1001 <            int r = seed;
1002 <            r ^= r << 13;
1003 <            r ^= r >>> 17;
1004 <            r ^= r << 5;
1005 <            return seed = r;
1000 >        final boolean isApparentlyUnblocked() {
1001 >            Thread wt; Thread.State s;
1002 >            return (eventCount >= 0 &&
1003 >                    (wt = owner) != null &&
1004 >                    (s = wt.getState()) != Thread.State.BLOCKED &&
1005 >                    s != Thread.State.WAITING &&
1006 >                    s != Thread.State.TIMED_WAITING);
1007 >        }
1008 >
1009 >        /**
1010 >         * If this owned and is not already interrupted, try to
1011 >         * interrupt and/or unpark, ignoring exceptions.
1012 >         */
1013 >        final void interruptOwner() {
1014 >            Thread wt, p;
1015 >            if ((wt = owner) != null && !wt.isInterrupted()) {
1016 >                try {
1017 >                    wt.interrupt();
1018 >                } catch (SecurityException ignore) {
1019 >                }
1020 >            }
1021 >            if ((p = parker) != null)
1022 >                U.unpark(p);
1023          }
1024  
1025          // Unsafe mechanics
# Line 1072 | Line 1047 | public class ForkJoinPool extends Abstra
1047      }
1048  
1049      /**
1050 <     * Class for artificial tasks that are used to replace the target
1051 <     * of local joins if they are removed from an interior queue slot
1052 <     * in WorkQueue.tryRemoveAndExec. We don't need the proxy to
1053 <     * actually do anything beyond having a unique identity.
1054 <     */
1055 <    static final class EmptyTask extends ForkJoinTask<Void> {
1056 <        EmptyTask() { status = ForkJoinTask.NORMAL; } // force done
1057 <        public Void getRawResult() { return null; }
1058 <        public void setRawResult(Void x) {}
1059 <        public boolean exec() { return true; }
1050 >     * Per-thread records for threads that submit to pools. Currently
1051 >     * holds only pseudo-random seed / index that is used to choose
1052 >     * submission queues in method doSubmit. In the future, this may
1053 >     * also incorporate a means to implement different task rejection
1054 >     * and resubmission policies.
1055 >     *
1056 >     * Seeds for submitters and workers/workQueues work in basically
1057 >     * the same way but are initialized and updated using slightly
1058 >     * different mechanics. Both are initialized using the same
1059 >     * approach as in class ThreadLocal, where successive values are
1060 >     * unlikely to collide with previous values. This is done during
1061 >     * registration for workers, but requires a separate AtomicInteger
1062 >     * for submitters. Seeds are then randomly modified upon
1063 >     * collisions using xorshifts, which requires a non-zero seed.
1064 >     */
1065 >    static final class Submitter {
1066 >        int seed;
1067 >        Submitter() {
1068 >            int s = nextSubmitterSeed.getAndAdd(SEED_INCREMENT);
1069 >            seed = (s == 0) ? 1 : s; // ensure non-zero
1070 >        }
1071      }
1072  
1073 +    /** ThreadLocal class for Submitters */
1074 +    static final class ThreadSubmitter extends ThreadLocal<Submitter> {
1075 +        public Submitter initialValue() { return new Submitter(); }
1076 +    }
1077 +
1078 +    // static fields (initialized in static initializer below)
1079 +
1080      /**
1081 <     * Computes a hash code for the given thread. This method is
1082 <     * expected to provide higher-quality hash codes than those using
1090 <     * method hashCode().
1081 >     * Creates a new ForkJoinWorkerThread. This factory is used unless
1082 >     * overridden in ForkJoinPool constructors.
1083       */
1084 <    static final int hashThread(Thread t) {
1085 <        long id = (t == null) ? 0L : t.getId(); // Use MurmurHash of thread id
1094 <        int h = (int)id ^ (int)(id >>> 32);
1095 <        h ^= h >>> 16;
1096 <        h *= 0x85ebca6b;
1097 <        h ^= h >>> 13;
1098 <        h *= 0xc2b2ae35;
1099 <        return h ^ (h >>> 16);
1100 <    }
1084 >    public static final ForkJoinWorkerThreadFactory
1085 >        defaultForkJoinWorkerThreadFactory;
1086  
1087      /**
1088 <     * Top-level runloop for workers
1088 >     * Generator for assigning sequence numbers as pool names.
1089       */
1090 <    final void runWorker(ForkJoinWorkerThread wt) {
1106 <        WorkQueue w = wt.workQueue;
1107 <        w.growArray(false);     // Initialize queue array and seed in this thread
1108 <        w.seed = hashThread(Thread.currentThread()) | (1 << 31); // force < 0
1090 >    private static final AtomicInteger poolNumberGenerator;
1091  
1092 <        do {} while (w.runTask(scan(w)));
1093 <    }
1092 >    /**
1093 >     * Generator for initial hashes/seeds for submitters. Accessed by
1094 >     * Submitter class constructor.
1095 >     */
1096 >    static final AtomicInteger nextSubmitterSeed;
1097  
1098 <    // Creating, registering and deregistering workers
1098 >    /**
1099 >     * Permission required for callers of methods that may start or
1100 >     * kill threads.
1101 >     */
1102 >    private static final RuntimePermission modifyThreadPermission;
1103 >
1104 >    /**
1105 >     * Per-thread submission bookeeping. Shared across all pools
1106 >     * to reduce ThreadLocal pollution and because random motion
1107 >     * to avoid contention in one pool is likely to hold for others.
1108 >     */
1109 >    private static final ThreadSubmitter submitters;
1110 >
1111 >    // static constants
1112 >
1113 >    /**
1114 >     * The wakeup interval (in nanoseconds) for a worker waiting for a
1115 >     * task when the pool is quiescent to instead try to shrink the
1116 >     * number of workers.  The exact value does not matter too
1117 >     * much. It must be short enough to release resources during
1118 >     * sustained periods of idleness, but not so short that threads
1119 >     * are continually re-created.
1120 >     */
1121 >    private static final long SHRINK_RATE =
1122 >        4L * 1000L * 1000L * 1000L; // 4 seconds
1123 >
1124 >    /**
1125 >     * The timeout value for attempted shrinkage, includes
1126 >     * some slop to cope with system timer imprecision.
1127 >     */
1128 >    private static final long SHRINK_TIMEOUT = SHRINK_RATE - (SHRINK_RATE / 10);
1129 >
1130 >    /**
1131 >     * The maximum stolen->joining link depth allowed in method
1132 >     * tryHelpStealer.  Must be a power of two. This value also
1133 >     * controls the maximum number of times to try to help join a task
1134 >     * without any apparent progress or change in pool state before
1135 >     * giving up and blocking (see awaitJoin).  Depths for legitimate
1136 >     * chains are unbounded, but we use a fixed constant to avoid
1137 >     * (otherwise unchecked) cycles and to bound staleness of
1138 >     * traversal parameters at the expense of sometimes blocking when
1139 >     * we could be helping.
1140 >     */
1141 >    private static final int MAX_HELP = 32;
1142 >
1143 >    /**
1144 >     * Secondary time-based bound (in nanosecs) for helping attempts
1145 >     * before trying compensated blocking in awaitJoin. Used in
1146 >     * conjunction with MAX_HELP to reduce variance due to different
1147 >     * polling rates associated with different helping options. The
1148 >     * value should roughly approximate the time required to create
1149 >     * and/or activate a worker thread.
1150 >     */
1151 >    private static final long COMPENSATION_DELAY = 100L * 1000L; // 0.1 millisec
1152 >
1153 >    /**
1154 >     * Increment for seed generators. See class ThreadLocal for
1155 >     * explanation.
1156 >     */
1157 >    private static final int SEED_INCREMENT = 0x61c88647;
1158 >
1159 >    /**
1160 >     * Bits and masks for control variables
1161 >     *
1162 >     * Field ctl is a long packed with:
1163 >     * AC: Number of active running workers minus target parallelism (16 bits)
1164 >     * TC: Number of total workers minus target parallelism (16 bits)
1165 >     * ST: true if pool is terminating (1 bit)
1166 >     * EC: the wait count of top waiting thread (15 bits)
1167 >     * ID: poolIndex of top of Treiber stack of waiters (16 bits)
1168 >     *
1169 >     * When convenient, we can extract the upper 32 bits of counts and
1170 >     * the lower 32 bits of queue state, u = (int)(ctl >>> 32) and e =
1171 >     * (int)ctl.  The ec field is never accessed alone, but always
1172 >     * together with id and st. The offsets of counts by the target
1173 >     * parallelism and the positionings of fields makes it possible to
1174 >     * perform the most common checks via sign tests of fields: When
1175 >     * ac is negative, there are not enough active workers, when tc is
1176 >     * negative, there are not enough total workers, and when e is
1177 >     * negative, the pool is terminating.  To deal with these possibly
1178 >     * negative fields, we use casts in and out of "short" and/or
1179 >     * signed shifts to maintain signedness.
1180 >     *
1181 >     * When a thread is queued (inactivated), its eventCount field is
1182 >     * set negative, which is the only way to tell if a worker is
1183 >     * prevented from executing tasks, even though it must continue to
1184 >     * scan for them to avoid queuing races. Note however that
1185 >     * eventCount updates lag releases so usage requires care.
1186 >     *
1187 >     * Field runState is an int packed with:
1188 >     * SHUTDOWN: true if shutdown is enabled (1 bit)
1189 >     * SEQ:  a sequence number updated upon (de)registering workers (30 bits)
1190 >     * INIT: set true after workQueues array construction (1 bit)
1191 >     *
1192 >     * The sequence number enables simple consistency checks:
1193 >     * Staleness of read-only operations on the workQueues array can
1194 >     * be checked by comparing runState before vs after the reads.
1195 >     */
1196 >
1197 >    // bit positions/shifts for fields
1198 >    private static final int  AC_SHIFT   = 48;
1199 >    private static final int  TC_SHIFT   = 32;
1200 >    private static final int  ST_SHIFT   = 31;
1201 >    private static final int  EC_SHIFT   = 16;
1202 >
1203 >    // bounds
1204 >    private static final int  SMASK      = 0xffff;  // short bits
1205 >    private static final int  MAX_CAP    = 0x7fff;  // max #workers - 1
1206 >    private static final int  SQMASK     = 0xfffe;  // even short bits
1207 >    private static final int  SHORT_SIGN = 1 << 15;
1208 >    private static final int  INT_SIGN   = 1 << 31;
1209 >
1210 >    // masks
1211 >    private static final long STOP_BIT   = 0x0001L << ST_SHIFT;
1212 >    private static final long AC_MASK    = ((long)SMASK) << AC_SHIFT;
1213 >    private static final long TC_MASK    = ((long)SMASK) << TC_SHIFT;
1214 >
1215 >    // units for incrementing and decrementing
1216 >    private static final long TC_UNIT    = 1L << TC_SHIFT;
1217 >    private static final long AC_UNIT    = 1L << AC_SHIFT;
1218 >
1219 >    // masks and units for dealing with u = (int)(ctl >>> 32)
1220 >    private static final int  UAC_SHIFT  = AC_SHIFT - 32;
1221 >    private static final int  UTC_SHIFT  = TC_SHIFT - 32;
1222 >    private static final int  UAC_MASK   = SMASK << UAC_SHIFT;
1223 >    private static final int  UTC_MASK   = SMASK << UTC_SHIFT;
1224 >    private static final int  UAC_UNIT   = 1 << UAC_SHIFT;
1225 >    private static final int  UTC_UNIT   = 1 << UTC_SHIFT;
1226 >
1227 >    // masks and units for dealing with e = (int)ctl
1228 >    private static final int E_MASK      = 0x7fffffff; // no STOP_BIT
1229 >    private static final int E_SEQ       = 1 << EC_SHIFT;
1230 >
1231 >    // runState bits
1232 >    private static final int SHUTDOWN    = 1 << 31;
1233 >
1234 >    // access mode for WorkQueue
1235 >    static final int LIFO_QUEUE          =  0;
1236 >    static final int FIFO_QUEUE          =  1;
1237 >    static final int SHARED_QUEUE        = -1;
1238 >
1239 >    // Instance fields
1240 >
1241 >    /*
1242 >     * Field layout order in this class tends to matter more than one
1243 >     * would like. Runtime layout order is only loosely related to
1244 >     * declaration order and may differ across JVMs, but the following
1245 >     * empirically works OK on current JVMs.
1246 >     */
1247 >
1248 >    volatile long ctl;                         // main pool control
1249 >    final int parallelism;                     // parallelism level
1250 >    final int localMode;                       // per-worker scheduling mode
1251 >    final int submitMask;                      // submit queue index bound
1252 >    int nextSeed;                              // for initializing worker seeds
1253 >    volatile int runState;                     // shutdown status and seq
1254 >    WorkQueue[] workQueues;                    // main registry
1255 >    final Mutex lock;                          // for registration
1256 >    final Condition termination;               // for awaitTermination
1257 >    final ForkJoinWorkerThreadFactory factory; // factory for new workers
1258 >    final Thread.UncaughtExceptionHandler ueh; // per-worker UEH
1259 >    final AtomicLong stealCount;               // collect counts when terminated
1260 >    final AtomicInteger nextWorkerNumber;      // to create worker name string
1261 >    final String workerNamePrefix;             // to create worker name string
1262 >
1263 >    //  Creating, registering, and deregistering workers
1264  
1265      /**
1266       * Tries to create and start a worker
1267       */
1268      private void addWorker() {
1269          Throwable ex = null;
1270 <        ForkJoinWorkerThread w = null;
1270 >        ForkJoinWorkerThread wt = null;
1271          try {
1272 <            if ((w = factory.newThread(this)) != null) {
1273 <                w.start();
1272 >            if ((wt = factory.newThread(this)) != null) {
1273 >                wt.start();
1274                  return;
1275              }
1276          } catch (Throwable e) {
1277              ex = e;
1278          }
1279 <        deregisterWorker(w, ex);
1279 >        deregisterWorker(wt, ex); // adjust counts etc on failure
1280      }
1281  
1282      /**
# Line 1141 | Line 1291 | public class ForkJoinPool extends Abstra
1291      }
1292  
1293      /**
1294 <     * Callback from ForkJoinWorkerThread constructor to establish and
1295 <     * record its WorkQueue
1294 >     * Callback from ForkJoinWorkerThread constructor to establish its
1295 >     * poolIndex and record its WorkQueue. To avoid scanning bias due
1296 >     * to packing entries in front of the workQueues array, we treat
1297 >     * the array as a simple power-of-two hash table using per-thread
1298 >     * seed as hash, expanding as needed.
1299       *
1300 <     * @param wt the worker thread
1300 >     * @param w the worker's queue
1301       */
1302 <    final void registerWorker(ForkJoinWorkerThread wt) {
1303 <        WorkQueue w = wt.workQueue;
1304 <        ReentrantLock lock = this.lock;
1302 >
1303 >    final void registerWorker(WorkQueue w) {
1304 >        Mutex lock = this.lock;
1305          lock.lock();
1306          try {
1154            int k = nextPoolIndex;
1307              WorkQueue[] ws = workQueues;
1308 <            if (ws != null) {                       // ignore on shutdown
1309 <                int n = ws.length;
1310 <                if (k < 0 || (k & 1) == 0 || k >= n || ws[k] != null) {
1311 <                    for (k = 1; k < n && ws[k] != null; k += 2)
1312 <                        ;                           // workers are at odd indices
1313 <                    if (k >= n)                     // resize
1314 <                        workQueues = ws = Arrays.copyOf(ws, n << 1);
1315 <                }
1316 <                w.poolIndex = k;
1317 <                w.eventCount = ~(k >>> 1) & SMASK;  // Set up wait count
1318 <                ws[k] = w;                          // record worker
1319 <                nextPoolIndex = k + 2;
1320 <                int rs = runState;
1321 <                int m = rs & SMASK;                 // recalculate runState mask
1322 <                if (k > m)
1323 <                    m = (m << 1) + 1;
1324 <                runState = (rs & SHUTDOWN) | ((rs + RS_SEQ) & RS_SEQ_MASK) | m;
1308 >            if (w != null && ws != null) {          // skip on shutdown/failure
1309 >                int rs, n =  ws.length, m = n - 1;
1310 >                int s = nextSeed += SEED_INCREMENT; // rarely-colliding sequence
1311 >                w.seed = (s == 0) ? 1 : s;          // ensure non-zero seed
1312 >                int r = (s << 1) | 1;               // use odd-numbered indices
1313 >                if (ws[r &= m] != null) {           // collision
1314 >                    int probes = 0;                 // step by approx half size
1315 >                    int step = (n <= 4) ? 2 : ((n >>> 1) & SQMASK) + 2;
1316 >                    while (ws[r = (r + step) & m] != null) {
1317 >                        if (++probes >= n) {
1318 >                            workQueues = ws = Arrays.copyOf(ws, n <<= 1);
1319 >                            m = n - 1;
1320 >                            probes = 0;
1321 >                        }
1322 >                    }
1323 >                }
1324 >                w.eventCount = w.poolIndex = r;     // establish before recording
1325 >                ws[r] = w;                          // also update seq
1326 >                runState = ((rs = runState) & SHUTDOWN) | ((rs + 2) & ~SHUTDOWN);
1327              }
1328          } finally {
1329              lock.unlock();
# Line 1177 | Line 1331 | public class ForkJoinPool extends Abstra
1331      }
1332  
1333      /**
1334 <     * Final callback from terminating worker, as well as failure to
1335 <     * construct or start a worker in addWorker.  Removes record of
1334 >     * Final callback from terminating worker, as well as upon failure
1335 >     * to construct or start a worker in addWorker.  Removes record of
1336       * worker from array, and adjusts counts. If pool is shutting
1337       * down, tries to complete termination.
1338       *
# Line 1186 | Line 1340 | public class ForkJoinPool extends Abstra
1340       * @param ex the exception causing failure, or null if none
1341       */
1342      final void deregisterWorker(ForkJoinWorkerThread wt, Throwable ex) {
1343 +        Mutex lock = this.lock;
1344          WorkQueue w = null;
1345          if (wt != null && (w = wt.workQueue) != null) {
1346              w.runState = -1;                // ensure runState is set
1347              stealCount.getAndAdd(w.totalSteals + w.nsteals);
1348              int idx = w.poolIndex;
1194            ReentrantLock lock = this.lock;
1349              lock.lock();
1350              try {                           // remove record from array
1351                  WorkQueue[] ws = workQueues;
1352                  if (ws != null && idx >= 0 && idx < ws.length && ws[idx] == w)
1353 <                    ws[nextPoolIndex = idx] = null;
1353 >                    ws[idx] = null;
1354              } finally {
1355                  lock.unlock();
1356              }
# Line 1208 | Line 1362 | public class ForkJoinPool extends Abstra
1362                                             ((c - TC_UNIT) & TC_MASK) |
1363                                             (c & ~(AC_MASK|TC_MASK)))));
1364  
1365 <        if (!tryTerminate(false) && w != null) {
1365 >        if (!tryTerminate(false, false) && w != null) {
1366              w.cancelAll();                  // cancel remaining tasks
1367              if (w.array != null)            // suppress signal if never ran
1368                  signalWork();               // wake up or create replacement
1369 +            if (ex == null)                 // help clean refs on way out
1370 +                ForkJoinTask.helpExpungeStaleExceptions();
1371          }
1372  
1373          if (ex != null)                     // rethrow
# Line 1219 | Line 1375 | public class ForkJoinPool extends Abstra
1375      }
1376  
1377  
1378 <    // Maintaining ctl counts
1223 <
1224 <    /**
1225 <     * Increments active count; mainly called upon return from blocking
1226 <     */
1227 <    final void incrementActiveCount() {
1228 <        long c;
1229 <        do {} while (!U.compareAndSwapLong(this, CTL, c = ctl, c + AC_UNIT));
1230 <    }
1378 >    // Submissions
1379  
1380      /**
1381 <     * Activates or creates a worker
1381 >     * Unless shutting down, adds the given task to a submission queue
1382 >     * at submitter's current queue index (modulo submission
1383 >     * range). If no queue exists at the index, one is created.  If
1384 >     * the queue is busy, another index is randomly chosen. The
1385 >     * submitMask bounds the effective number of queues to the
1386 >     * (nearest power of two for) parallelism level.
1387 >     *
1388 >     * @param task the task. Caller must ensure non-null.
1389       */
1390 <    final void signalWork() {
1391 <        /*
1392 <         * The while condition is true if: (there is are too few total
1393 <         * workers OR there is at least one waiter) AND (there are too
1394 <         * few active workers OR the pool is terminating).  The value
1395 <         * of e distinguishes the remaining cases: zero (no waiters)
1396 <         * for create, negative if terminating (in which case do
1397 <         * nothing), else release a waiter. The secondary checks for
1398 <         * release (non-null array etc) can fail if the pool begins
1399 <         * terminating after the test, and don't impose any added cost
1400 <         * because JVMs must perform null and bounds checks anyway.
1401 <         */
1402 <        long c; int e, u;
1403 <        while ((((e = (int)(c = ctl)) | (u = (int)(c >>> 32))) &
1404 <                (INT_SIGN|SHORT_SIGN)) == (INT_SIGN|SHORT_SIGN)) {
1405 <            WorkQueue[] ws = workQueues; int i; WorkQueue w; Thread p;
1406 <            if (e == 0) {                    // add a new worker
1407 <                if (U.compareAndSwapLong
1408 <                    (this, CTL, c, (long)(((u + UTC_UNIT) & UTC_MASK) |
1254 <                                          ((u + UAC_UNIT) & UAC_MASK)) << 32)) {
1255 <                    addWorker();
1256 <                    break;
1390 >    private void doSubmit(ForkJoinTask<?> task) {
1391 >        Submitter s = submitters.get();
1392 >        for (int r = s.seed, m = submitMask;;) {
1393 >            WorkQueue[] ws; WorkQueue q;
1394 >            int k = r & m & SQMASK;          // use only even indices
1395 >            if (runState < 0 || (ws = workQueues) == null || ws.length <= k)
1396 >                throw new RejectedExecutionException(); // shutting down
1397 >            else if ((q = ws[k]) == null) {  // create new queue
1398 >                WorkQueue nq = new WorkQueue(this, null, SHARED_QUEUE);
1399 >                Mutex lock = this.lock;      // construct outside lock
1400 >                lock.lock();
1401 >                try {                        // recheck under lock
1402 >                    int rs = runState;       // to update seq
1403 >                    if (ws == workQueues && ws[k] == null) {
1404 >                        ws[k] = nq;
1405 >                        runState = ((rs & SHUTDOWN) | ((rs + 2) & ~SHUTDOWN));
1406 >                    }
1407 >                } finally {
1408 >                    lock.unlock();
1409                  }
1410              }
1411 <            else if (e > 0 && ws != null &&
1412 <                     (i = ((~e << 1) | 1) & SMASK) < ws.length &&
1413 <                     (w = ws[i]) != null &&
1414 <                     w.eventCount == (e | INT_SIGN)) {
1415 <                if (U.compareAndSwapLong
1416 <                    (this, CTL, c, (((long)(w.nextWait & E_MASK)) |
1417 <                                    ((long)(u + UAC_UNIT) << 32)))) {
1418 <                    w.eventCount = (e + E_SEQ) & E_MASK;
1267 <                    if ((p = w.parker) != null)
1268 <                        U.unpark(p);         // release a waiting worker
1269 <                    break;
1270 <                }
1411 >            else if (q.trySharedPush(task)) {
1412 >                signalWork();
1413 >                return;
1414 >            }
1415 >            else if (m > 1) {                // move to a different index
1416 >                r ^= r << 13;                // same xorshift as WorkQueues
1417 >                r ^= r >>> 17;
1418 >                s.seed = r ^= r << 5;
1419              }
1420              else
1421 <                break;
1421 >                Thread.yield();              // yield if no alternatives
1422          }
1423      }
1424  
1425 +    // Maintaining ctl counts
1426 +
1427      /**
1428 <     * Tries to decrement active count (sometimes implicitly) and
1279 <     * possibly release or create a compensating worker in preparation
1280 <     * for blocking. Fails on contention or termination.
1281 <     *
1282 <     * @return true if the caller can block, else should recheck and retry
1428 >     * Increments active count; mainly called upon return from blocking.
1429       */
1430 <    final boolean tryCompensate() {
1431 <        WorkQueue[] ws; WorkQueue w; Thread p;
1432 <        int pc = parallelism, e, u, ac, tc, i;
1287 <        long c = ctl;
1288 <
1289 <        if ((e = (int)c) >= 0) {
1290 <            if ((ac = ((u = (int)(c >>> 32)) >> UAC_SHIFT)) <= 0 &&
1291 <                e != 0 && (ws = workQueues) != null &&
1292 <                (i = ((~e << 1) | 1) & SMASK) < ws.length &&
1293 <                (w = ws[i]) != null) {
1294 <                if (w.eventCount == (e | INT_SIGN) &&
1295 <                    U.compareAndSwapLong
1296 <                    (this, CTL, c, ((long)(w.nextWait & E_MASK) |
1297 <                                    (c & (AC_MASK|TC_MASK))))) {
1298 <                    w.eventCount = (e + E_SEQ) & E_MASK;
1299 <                    if ((p = w.parker) != null)
1300 <                        U.unpark(p);
1301 <                    return true;             // release an idle worker
1302 <                }
1303 <            }
1304 <            else if ((tc = (short)(u >>> UTC_SHIFT)) >= 0 && ac + pc > 1) {
1305 <                long nc = ((c - AC_UNIT) & AC_MASK) | (c & ~AC_MASK);
1306 <                if (U.compareAndSwapLong(this, CTL, c, nc))
1307 <                    return true;             // no compensation needed
1308 <            }
1309 <            else if (tc + pc < MAX_ID) {
1310 <                long nc = ((c + TC_UNIT) & TC_MASK) | (c & ~TC_MASK);
1311 <                if (U.compareAndSwapLong(this, CTL, c, nc)) {
1312 <                    addWorker();
1313 <                    return true;             // create replacement
1314 <                }
1315 <            }
1316 <        }
1317 <        return false;
1430 >    final void incrementActiveCount() {
1431 >        long c;
1432 >        do {} while (!U.compareAndSwapLong(this, CTL, c = ctl, c + AC_UNIT));
1433      }
1434  
1320    // Submissions
1321
1435      /**
1436 <     * Unless shutting down, adds the given task to some submission
1324 <     * queue; using a randomly chosen queue index if the caller is a
1325 <     * ForkJoinWorkerThread, else one based on caller thread's hash
1326 <     * code. If no queue exists at the index, one is created.  If the
1327 <     * queue is busy, another is chosen by sweeping through the queues
1328 <     * array.
1436 >     * Tries to activate or create a worker if too few are active.
1437       */
1438 <    private void doSubmit(ForkJoinTask<?> task) {
1439 <        if (task == null)
1440 <            throw new NullPointerException();
1441 <        Thread t = Thread.currentThread();
1442 <        int r = ((t instanceof ForkJoinWorkerThread) ?
1443 <                 ((ForkJoinWorkerThread)t).workQueue.nextSeed() : hashThread(t));
1444 <        for (;;) {
1445 <            int rs = runState, m = rs & SMASK;
1446 <            int j = r &= (m & ~1);                      // even numbered queues
1447 <            WorkQueue[] ws = workQueues;
1448 <            if (rs < 0 || ws == null)
1449 <                throw new RejectedExecutionException(); // shutting down
1450 <            if (ws.length > m) {                        // consistency check
1343 <                for (WorkQueue q;;) {                   // circular sweep
1344 <                    if (((q = ws[j]) != null ||
1345 <                         (q = tryAddSharedQueue(j)) != null) &&
1346 <                        q.trySharedPush(task)) {
1347 <                        signalWork();
1348 <                        return;
1349 <                    }
1350 <                    if ((j = (j + 2) & m) == r) {
1351 <                        Thread.yield();                 // all queues busy
1438 >    final void signalWork() {
1439 >        long c; int u;
1440 >        while ((u = (int)((c = ctl) >>> 32)) < 0) {     // too few active
1441 >            WorkQueue[] ws = workQueues; int e, i; WorkQueue w; Thread p;
1442 >            if ((e = (int)c) > 0) {                     // at least one waiting
1443 >                if (ws != null && (i = e & SMASK) < ws.length &&
1444 >                    (w = ws[i]) != null && w.eventCount == (e | INT_SIGN)) {
1445 >                    long nc = (((long)(w.nextWait & E_MASK)) |
1446 >                               ((long)(u + UAC_UNIT) << 32));
1447 >                    if (U.compareAndSwapLong(this, CTL, c, nc)) {
1448 >                        w.eventCount = (e + E_SEQ) & E_MASK;
1449 >                        if ((p = w.parker) != null)
1450 >                            U.unpark(p);                // activate and release
1451                          break;
1452                      }
1453                  }
1454 +                else
1455 +                    break;
1456              }
1457 <        }
1458 <    }
1459 <
1460 <    /**
1461 <     * Tries to add and register a new queue at the given index.
1462 <     *
1362 <     * @param idx the workQueues array index to register the queue
1363 <     * @return the queue, or null if could not add because could
1364 <     * not acquire lock or idx is unusable
1365 <     */
1366 <    private WorkQueue tryAddSharedQueue(int idx) {
1367 <        WorkQueue q = null;
1368 <        ReentrantLock lock = this.lock;
1369 <        if (idx >= 0 && (idx & 1) == 0 && !lock.isLocked()) {
1370 <            // create queue outside of lock but only if apparently free
1371 <            WorkQueue nq = new WorkQueue(null, SHARED_QUEUE);
1372 <            if (lock.tryLock()) {
1373 <                try {
1374 <                    WorkQueue[] ws = workQueues;
1375 <                    if (ws != null && idx < ws.length) {
1376 <                        if ((q = ws[idx]) == null) {
1377 <                            int rs;         // update runState seq
1378 <                            ws[idx] = q = nq;
1379 <                            runState = (((rs = runState) & SHUTDOWN) |
1380 <                                        ((rs + RS_SEQ) & ~SHUTDOWN));
1381 <                        }
1382 <                    }
1383 <                } finally {
1384 <                    lock.unlock();
1457 >            else if (e == 0 && (u & SHORT_SIGN) != 0) { // too few total
1458 >                long nc = (long)(((u + UTC_UNIT) & UTC_MASK) |
1459 >                                 ((u + UAC_UNIT) & UAC_MASK)) << 32;
1460 >                if (U.compareAndSwapLong(this, CTL, c, nc)) {
1461 >                    addWorker();
1462 >                    break;
1463                  }
1464              }
1465 +            else
1466 +                break;
1467          }
1388        return q;
1468      }
1469  
1470      // Scanning for tasks
1471  
1472      /**
1473 +     * Top-level runloop for workers, called by ForkJoinWorkerThread.run.
1474 +     */
1475 +    final void runWorker(WorkQueue w) {
1476 +        w.growArray(false);         // initialize queue array in this thread
1477 +        do { w.runTask(scan(w)); } while (w.runState >= 0);
1478 +    }
1479 +
1480 +    /**
1481       * Scans for and, if found, returns one task, else possibly
1482       * inactivates the worker. This method operates on single reads of
1483 <     * volatile state and is designed to be re-invoked continuously in
1484 <     * part because it returns upon detecting inconsistencies,
1483 >     * volatile state and is designed to be re-invoked continuously,
1484 >     * in part because it returns upon detecting inconsistencies,
1485       * contention, or state changes that indicate possible success on
1486       * re-invocation.
1487       *
1488 <     * The scan searches for tasks across queues, randomly selecting
1489 <     * the first #queues probes, favoring steals 2:1 over submissions
1490 <     * (by exploiting even/odd indexing), and then performing a
1491 <     * circular sweep of all queues.  The scan terminates upon either
1492 <     * finding a non-empty queue, or completing a full sweep. If the
1493 <     * worker is not inactivated, it takes and returns a task from
1494 <     * this queue.  On failure to find a task, we take one of the
1495 <     * following actions, after which the caller will retry calling
1496 <     * this method unless terminated.
1488 >     * The scan searches for tasks across a random permutation of
1489 >     * queues (starting at a random index and stepping by a random
1490 >     * relative prime, checking each at least once).  The scan
1491 >     * terminates upon either finding a non-empty queue, or completing
1492 >     * the sweep. If the worker is not inactivated, it takes and
1493 >     * returns a task from this queue.  On failure to find a task, we
1494 >     * take one of the following actions, after which the caller will
1495 >     * retry calling this method unless terminated.
1496 >     *
1497 >     * * If pool is terminating, terminate the worker.
1498       *
1499       * * If not a complete sweep, try to release a waiting worker.  If
1500       * the scan terminated because the worker is inactivated, then the
# Line 1415 | Line 1503 | public class ForkJoinPool extends Abstra
1503       * another worker, but with same net effect. Releasing in other
1504       * cases as well ensures that we have enough workers running.
1505       *
1418     * * If the caller has run a task since the the last empty scan,
1419     * return (to allow rescan) if other workers are not also yet
1420     * enqueued.  Field WorkQueue.rescans counts down on each scan to
1421     * ensure eventual inactivation, and occasional calls to
1422     * Thread.yield to help avoid interference with more useful
1423     * activities on the system.
1424     *
1425     * * If pool is terminating, terminate the worker
1426     *
1506       * * If not already enqueued, try to inactivate and enqueue the
1507 <     * worker on wait queue.
1507 >     * worker on wait queue. Or, if inactivating has caused the pool
1508 >     * to be quiescent, relay to idleAwaitWork to check for
1509 >     * termination and possibly shrink pool.
1510 >     *
1511 >     * * If already inactive, and the caller has run a task since the
1512 >     * last empty scan, return (to allow rescan) unless others are
1513 >     * also inactivated.  Field WorkQueue.rescans counts down on each
1514 >     * scan to ensure eventual inactivation and blocking.
1515       *
1516 <     * * If already enqueued and none of the above apply, either park
1517 <     * awaiting signal, or if this is the most recent waiter and pool
1432 <     * is quiescent, relay to idleAwaitWork to check for termination
1433 <     * and possibly shrink pool.
1516 >     * * If already enqueued and none of the above apply, park
1517 >     * awaiting signal,
1518       *
1519       * @param w the worker (via its WorkQueue)
1520       * @return a task or null of none found
1521       */
1522      private final ForkJoinTask<?> scan(WorkQueue w) {
1523 <        boolean swept = false;                 // true after full empty scan
1524 <        WorkQueue[] ws;                        // volatile read order matters
1525 <        int r = w.seed, ec = w.eventCount;     // ec is negative if inactive
1526 <        int rs = runState, m = rs & SMASK;
1527 <        if ((ws = workQueues) != null && ws.length > m) {
1528 <            ForkJoinTask<?> task = null;
1529 <            for (int k = 0, j = -2 - m; ; ++j) {
1530 <                WorkQueue q; int b;
1531 <                if (j < 0) {                    // random probes while j negative
1532 <                    r ^= r << 13; r ^= r >>> 17; k = (r ^= r << 5) | (j & 1);
1533 <                }                               // worker (not submit) for odd j
1534 <                else                            // cyclic scan when j >= 0
1535 <                    k += (m >>> 1) | 1;         // step by half to reduce bias
1536 <
1537 <                if ((q = ws[k & m]) != null && (b = q.base) - q.top < 0) {
1538 <                    if (ec >= 0)
1539 <                        task = q.pollAt(b);     // steal
1540 <                    break;
1523 >        WorkQueue[] ws;                       // first update random seed
1524 >        int r = w.seed; r ^= r << 13; r ^= r >>> 17; w.seed = r ^= r << 5;
1525 >        int rs = runState, m;                 // volatile read order matters
1526 >        if ((ws = workQueues) != null && (m = ws.length - 1) > 0) {
1527 >            int ec = w.eventCount;            // ec is negative if inactive
1528 >            int step = (r >>> 16) | 1;        // relative prime
1529 >            for (int j = (m + 1) << 2; ; r += step) {
1530 >                WorkQueue q; ForkJoinTask<?> t; ForkJoinTask<?>[] a; int b;
1531 >                if ((q = ws[r & m]) != null && (b = q.base) - q.top < 0 &&
1532 >                    (a = q.array) != null) {  // probably nonempty
1533 >                    int i = (((a.length - 1) & b) << ASHIFT) + ABASE;
1534 >                    t = (ForkJoinTask<?>)U.getObjectVolatile(a, i);
1535 >                    if (q.base == b && ec >= 0 && t != null &&
1536 >                        U.compareAndSwapObject(a, i, t, null)) {
1537 >                        q.base = b + 1;       // specialization of pollAt
1538 >                        return t;
1539 >                    }
1540 >                    else if (ec < 0 || j <= m) {
1541 >                        rs = 0;               // mark scan as imcomplete
1542 >                        break;                // caller can retry after release
1543 >                    }
1544                  }
1545 <                else if (j > m) {
1459 <                    if (rs == runState)        // staleness check
1460 <                        swept = true;
1545 >                if (--j < 0)
1546                      break;
1547 +            }
1548 +            long c = ctl; int e = (int)c, a = (int)(c >> AC_SHIFT), nr, ns;
1549 +            if (e < 0)                        // decode ctl on empty scan
1550 +                w.runState = -1;              // pool is terminating
1551 +            else if (rs == 0 || rs != runState) { // incomplete scan
1552 +                WorkQueue v; Thread p;        // try to release a waiter
1553 +                if (e > 0 && a < 0 && w.eventCount == ec &&
1554 +                    (v = ws[e & m]) != null && v.eventCount == (e | INT_SIGN)) {
1555 +                    long nc = ((long)(v.nextWait & E_MASK) |
1556 +                               ((c + AC_UNIT) & (AC_MASK|TC_MASK)));
1557 +                    if (ctl == c && U.compareAndSwapLong(this, CTL, c, nc)) {
1558 +                        v.eventCount = (e + E_SEQ) & E_MASK;
1559 +                        if ((p = v.parker) != null)
1560 +                            U.unpark(p);
1561 +                    }
1562                  }
1563              }
1564 <            w.seed = r;                        // save seed for next scan
1565 <            if (task != null)
1566 <                return task;
1567 <        }
1568 <
1569 <        // Decode ctl on empty scan
1570 <        long c = ctl; int e = (int)c, a = (int)(c >> AC_SHIFT), nr, ns;
1571 <        if (!swept) {                          // try to release a waiter
1572 <            WorkQueue v; Thread p;
1573 <            if (e > 0 && a < 0 && ws != null &&
1574 <                (v = ws[((~e << 1) | 1) & m]) != null &&
1575 <                v.eventCount == (e | INT_SIGN) && U.compareAndSwapLong
1576 <                (this, CTL, c, ((long)(v.nextWait & E_MASK) |
1577 <                                ((c + AC_UNIT) & (AC_MASK|TC_MASK))))) {
1578 <                v.eventCount = (e + E_SEQ) & E_MASK;
1579 <                if ((p = v.parker) != null)
1580 <                    U.unpark(p);
1581 <            }
1582 <        }
1583 <        else if ((nr = w.rescans) > 0) {       // continue rescanning
1584 <            int ac = a + parallelism;
1585 <            if ((w.rescans = (ac < nr) ? ac : nr - 1) > 0 && w.seed < 0 &&
1586 <                w.eventCount == ec)
1587 <                Thread.yield();                // 1 bit randomness for yield call
1588 <        }
1589 <        else if (e < 0)                        // pool is terminating
1590 <            w.runState = -1;
1591 <        else if (ec >= 0) {                    // try to enqueue
1592 <            long nc = (long)ec | ((c - AC_UNIT) & (AC_MASK|TC_MASK));
1593 <            w.nextWait = e;
1594 <            w.eventCount = ec | INT_SIGN;      // mark as inactive
1595 <            if (!U.compareAndSwapLong(this, CTL, c, nc))
1496 <                w.eventCount = ec;             // back out on CAS failure
1497 <            else if ((ns = w.nsteals) != 0) {  // set rescans if ran task
1498 <                if (a <= 0)                    // ... unless too many active
1499 <                    w.rescans = a + parallelism;
1500 <                w.nsteals = 0;
1501 <                w.totalSteals += ns;
1502 <            }
1503 <        }
1504 <        else{                                  // already queued
1505 <            if (parallelism == -a)
1506 <                idleAwaitWork(w);              // quiescent
1507 <            if (w.eventCount == ec) {
1508 <                Thread.interrupted();          // clear status
1509 <                ForkJoinWorkerThread wt = w.owner;
1510 <                U.putObject(wt, PARKBLOCKER, this);
1511 <                w.parker = wt;                 // emulate LockSupport.park
1512 <                if (w.eventCount == ec)        // recheck
1513 <                    U.park(false, 0L);         // block
1514 <                w.parker = null;
1515 <                U.putObject(wt, PARKBLOCKER, null);
1564 >            else if (ec >= 0) {               // try to enqueue/inactivate
1565 >                long nc = (long)ec | ((c - AC_UNIT) & (AC_MASK|TC_MASK));
1566 >                w.nextWait = e;
1567 >                w.eventCount = ec | INT_SIGN; // mark as inactive
1568 >                if (ctl != c || !U.compareAndSwapLong(this, CTL, c, nc))
1569 >                    w.eventCount = ec;        // unmark on CAS failure
1570 >                else {
1571 >                    if ((ns = w.nsteals) != 0) {
1572 >                        w.nsteals = 0;        // set rescans if ran task
1573 >                        w.rescans = (a > 0) ? 0 : a + parallelism;
1574 >                        w.totalSteals += ns;
1575 >                    }
1576 >                    if (a == 1 - parallelism) // quiescent
1577 >                        idleAwaitWork(w, nc, c);
1578 >                }
1579 >            }
1580 >            else if (w.eventCount < 0) {      // already queued
1581 >                if ((nr = w.rescans) > 0) {   // continue rescanning
1582 >                    int ac = a + parallelism;
1583 >                    if (((w.rescans = (ac < nr) ? ac : nr - 1) & 3) == 0)
1584 >                        Thread.yield();       // yield before block
1585 >                }
1586 >                else {
1587 >                    Thread.interrupted();     // clear status
1588 >                    Thread wt = Thread.currentThread();
1589 >                    U.putObject(wt, PARKBLOCKER, this);
1590 >                    w.parker = wt;            // emulate LockSupport.park
1591 >                    if (w.eventCount < 0)     // recheck
1592 >                        U.park(false, 0L);
1593 >                    w.parker = null;
1594 >                    U.putObject(wt, PARKBLOCKER, null);
1595 >                }
1596              }
1597          }
1598          return null;
1599      }
1600  
1601      /**
1602 <     * If inactivating worker w has caused pool to become quiescent,
1603 <     * check for pool termination, and, so long as this is not the
1604 <     * only worker, wait for event for up to SHRINK_RATE nanosecs On
1605 <     * timeout, if ctl has not changed, terminate the worker, which
1606 <     * will in turn wake up another worker to possibly repeat this
1607 <     * process.
1602 >     * If inactivating worker w has caused the pool to become
1603 >     * quiescent, checks for pool termination, and, so long as this is
1604 >     * not the only worker, waits for event for up to SHRINK_RATE
1605 >     * nanosecs.  On timeout, if ctl has not changed, terminates the
1606 >     * worker, which will in turn wake up another worker to possibly
1607 >     * repeat this process.
1608       *
1609       * @param w the calling worker
1610 +     * @param currentCtl the ctl value triggering possible quiescence
1611 +     * @param prevCtl the ctl value to restore if thread is terminated
1612       */
1613 <    private void idleAwaitWork(WorkQueue w) {
1614 <        long c; int nw, ec;
1615 <        if (!tryTerminate(false) &&
1616 <            (int)((c = ctl) >> AC_SHIFT) + parallelism == 0 &&
1617 <            (ec = w.eventCount) == ((int)c | INT_SIGN) &&
1618 <            (nw = w.nextWait) != 0) {
1537 <            long nc = ((long)(nw & E_MASK) | // ctl to restore on timeout
1538 <                       ((c + AC_UNIT) & AC_MASK) | (c & TC_MASK));
1539 <            ForkJoinTask.helpExpungeStaleExceptions(); // help clean
1540 <            ForkJoinWorkerThread wt = w.owner;
1541 <            while (ctl == c) {
1613 >    private void idleAwaitWork(WorkQueue w, long currentCtl, long prevCtl) {
1614 >        if (w.eventCount < 0 && !tryTerminate(false, false) &&
1615 >            (int)prevCtl != 0 && !hasQueuedSubmissions() && ctl == currentCtl) {
1616 >            Thread wt = Thread.currentThread();
1617 >            Thread.yield();            // yield before block
1618 >            while (ctl == currentCtl) {
1619                  long startTime = System.nanoTime();
1620                  Thread.interrupted();  // timed variant of version in scan()
1621                  U.putObject(wt, PARKBLOCKER, this);
1622                  w.parker = wt;
1623 <                if (ctl == c)
1623 >                if (ctl == currentCtl)
1624                      U.park(false, SHRINK_RATE);
1625                  w.parker = null;
1626                  U.putObject(wt, PARKBLOCKER, null);
1627 <                if (ctl != c)
1627 >                if (ctl != currentCtl)
1628                      break;
1629                  if (System.nanoTime() - startTime >= SHRINK_TIMEOUT &&
1630 <                    U.compareAndSwapLong(this, CTL, c, nc)) {
1631 <                    w.runState = -1;          // shrink
1632 <                    w.eventCount = (ec + E_SEQ) | E_MASK;
1630 >                    U.compareAndSwapLong(this, CTL, currentCtl, prevCtl)) {
1631 >                    w.eventCount = (w.eventCount + E_SEQ) | E_MASK;
1632 >                    w.runState = -1;   // shrink
1633                      break;
1634                  }
1635              }
# Line 1570 | Line 1647 | public class ForkJoinPool extends Abstra
1647       * leaves hints in workers to speed up subsequent calls. The
1648       * implementation is very branchy to cope with potential
1649       * inconsistencies or loops encountering chains that are stale,
1650 <     * unknown, or of length greater than MAX_HELP_DEPTH links.  All
1651 <     * of these cases are dealt with by just retrying by caller.
1650 >     * unknown, or so long that they are likely cyclic.  All of these
1651 >     * cases are dealt with by just retrying by caller.
1652       *
1653       * @param joiner the joining worker
1654       * @param task the task to join
1655       * @return true if found or ran a task (and so is immediately retryable)
1656       */
1657 <    final boolean tryHelpStealer(WorkQueue joiner, ForkJoinTask<?> task) {
1658 <        ForkJoinTask<?> subtask;    // current target
1657 >    private boolean tryHelpStealer(WorkQueue joiner, ForkJoinTask<?> task) {
1658 >        WorkQueue[] ws;
1659 >        int m, depth = MAX_HELP;                // remaining chain depth
1660          boolean progress = false;
1661 <        int depth = 0;              // current chain depth
1662 <        int m = runState & SMASK;
1663 <        WorkQueue[] ws = workQueues;
1664 <
1665 <        if (ws != null && ws.length > m && (subtask = task).status >= 0) {
1666 <            outer:for (WorkQueue j = joiner;;) {
1589 <                // Try to find the stealer of subtask, by first using hint
1590 <                WorkQueue stealer = null;
1591 <                WorkQueue v = ws[j.stealHint & m];
1661 >        if ((ws = workQueues) != null && (m = ws.length - 1) > 0 &&
1662 >            task.status >= 0) {
1663 >            ForkJoinTask<?> subtask = task;     // current target
1664 >            outer: for (WorkQueue j = joiner;;) {
1665 >                WorkQueue stealer = null;       // find stealer of subtask
1666 >                WorkQueue v = ws[j.stealHint & m]; // try hint
1667                  if (v != null && v.currentSteal == subtask)
1668                      stealer = v;
1669 <                else {
1669 >                else {                          // scan
1670                      for (int i = 1; i <= m; i += 2) {
1671 <                        if ((v = ws[i]) != null && v.currentSteal == subtask) {
1671 >                        if ((v = ws[i]) != null && v.currentSteal == subtask &&
1672 >                            v != joiner) {
1673                              stealer = v;
1674 <                            j.stealHint = i; // save hint
1674 >                            j.stealHint = i;    // save hint
1675                              break;
1676                          }
1677                      }
# Line 1603 | Line 1679 | public class ForkJoinPool extends Abstra
1679                          break;
1680                  }
1681  
1682 <                for (WorkQueue q = stealer;;) { // Try to help stealer
1683 <                    ForkJoinTask<?> t; int b;
1682 >                for (WorkQueue q = stealer;;) { // try to help stealer
1683 >                    ForkJoinTask[] a; ForkJoinTask<?> t; int b;
1684                      if (task.status < 0)
1685                          break outer;
1686 <                    if ((b = q.base) - q.top < 0) {
1686 >                    if ((b = q.base) - q.top < 0 && (a = q.array) != null) {
1687                          progress = true;
1688 <                        if (subtask.status < 0)
1689 <                            break outer;               // stale
1690 <                        if ((t = q.pollAt(b)) != null) {
1691 <                            stealer.stealHint = joiner.poolIndex;
1688 >                        int i = (((a.length - 1) & b) << ASHIFT) + ABASE;
1689 >                        t = (ForkJoinTask<?>)U.getObjectVolatile(a, i);
1690 >                        if (subtask.status < 0) // must recheck before taking
1691 >                            break outer;
1692 >                        if (t != null &&
1693 >                            q.base == b &&
1694 >                            U.compareAndSwapObject(a, i, t, null)) {
1695 >                            q.base = b + 1;
1696                              joiner.runSubtask(t);
1697                          }
1698 +                        else if (q.base == b)
1699 +                            break outer;        // possibly stalled
1700                      }
1701 <                    else { // empty - try to descend to find stealer's stealer
1701 >                    else {                      // descend
1702                          ForkJoinTask<?> next = stealer.currentJoin;
1703 <                        if (++depth == MAX_HELP_DEPTH || subtask.status < 0 ||
1703 >                        if (--depth <= 0 || subtask.status < 0 ||
1704                              next == null || next == subtask)
1705 <                            break outer;  // max depth, stale, dead-end, cyclic
1705 >                            break outer;        // stale, dead-end, or cyclic
1706                          subtask = next;
1707                          j = stealer;
1708                          break;
# Line 1637 | Line 1719 | public class ForkJoinPool extends Abstra
1719       * @param joiner the joining worker
1720       * @param task the task
1721       */
1722 <    final void tryPollForAndExec(WorkQueue joiner, ForkJoinTask<?> task) {
1722 >    private void tryPollForAndExec(WorkQueue joiner, ForkJoinTask<?> task) {
1723          WorkQueue[] ws;
1724 <        int m = runState & SMASK;
1725 <        if ((ws = workQueues) != null && ws.length > m) {
1644 <            for (int j = 1; j <= m && task.status >= 0; j += 2) {
1724 >        if ((ws = workQueues) != null) {
1725 >            for (int j = 1; j < ws.length && task.status >= 0; j += 2) {
1726                  WorkQueue q = ws[j];
1727                  if (q != null && q.pollFor(task)) {
1728                      joiner.runSubtask(task);
# Line 1652 | Line 1733 | public class ForkJoinPool extends Abstra
1733      }
1734  
1735      /**
1736 <     * Returns a non-empty steal queue, if one is found during a random,
1737 <     * then cyclic scan, else null.  This method must be retried by
1738 <     * caller if, by the time it tries to use the queue, it is empty.
1736 >     * Tries to decrement active count (sometimes implicitly) and
1737 >     * possibly release or create a compensating worker in preparation
1738 >     * for blocking. Fails on contention or termination. Otherwise,
1739 >     * adds a new thread if no idle workers are available and either
1740 >     * pool would become completely starved or: (at least half
1741 >     * starved, and fewer than 50% spares exist, and there is at least
1742 >     * one task apparently available). Even though the availability
1743 >     * check requires a full scan, it is worthwhile in reducing false
1744 >     * alarms.
1745 >     *
1746 >     * @param task if non-null, a task being waited for
1747 >     * @param blocker if non-null, a blocker being waited for
1748 >     * @return true if the caller can block, else should recheck and retry
1749 >     */
1750 >    final boolean tryCompensate(ForkJoinTask<?> task, ManagedBlocker blocker) {
1751 >        int pc = parallelism, e;
1752 >        long c = ctl;
1753 >        WorkQueue[] ws = workQueues;
1754 >        if ((e = (int)c) >= 0 && ws != null) {
1755 >            int u, a, ac, hc;
1756 >            int tc = (short)((u = (int)(c >>> 32)) >>> UTC_SHIFT) + pc;
1757 >            boolean replace = false;
1758 >            if ((a = u >> UAC_SHIFT) <= 0) {
1759 >                if ((ac = a + pc) <= 1)
1760 >                    replace = true;
1761 >                else if ((e > 0 || (task != null &&
1762 >                                    ac <= (hc = pc >>> 1) && tc < pc + hc))) {
1763 >                    WorkQueue w;
1764 >                    for (int j = 0; j < ws.length; ++j) {
1765 >                        if ((w = ws[j]) != null && !w.isEmpty()) {
1766 >                            replace = true;
1767 >                            break;   // in compensation range and tasks available
1768 >                        }
1769 >                    }
1770 >                }
1771 >            }
1772 >            if ((task == null || task.status >= 0) && // recheck need to block
1773 >                (blocker == null || !blocker.isReleasable()) && ctl == c) {
1774 >                if (!replace) {          // no compensation
1775 >                    long nc = ((c - AC_UNIT) & AC_MASK) | (c & ~AC_MASK);
1776 >                    if (U.compareAndSwapLong(this, CTL, c, nc))
1777 >                        return true;
1778 >                }
1779 >                else if (e != 0) {       // release an idle worker
1780 >                    WorkQueue w; Thread p; int i;
1781 >                    if ((i = e & SMASK) < ws.length && (w = ws[i]) != null) {
1782 >                        long nc = ((long)(w.nextWait & E_MASK) |
1783 >                                   (c & (AC_MASK|TC_MASK)));
1784 >                        if (w.eventCount == (e | INT_SIGN) &&
1785 >                            U.compareAndSwapLong(this, CTL, c, nc)) {
1786 >                            w.eventCount = (e + E_SEQ) & E_MASK;
1787 >                            if ((p = w.parker) != null)
1788 >                                U.unpark(p);
1789 >                            return true;
1790 >                        }
1791 >                    }
1792 >                }
1793 >                else if (tc < MAX_CAP) { // create replacement
1794 >                    long nc = ((c + TC_UNIT) & TC_MASK) | (c & ~TC_MASK);
1795 >                    if (U.compareAndSwapLong(this, CTL, c, nc)) {
1796 >                        addWorker();
1797 >                        return true;
1798 >                    }
1799 >                }
1800 >            }
1801 >        }
1802 >        return false;
1803 >    }
1804 >
1805 >    /**
1806 >     * Helps and/or blocks until the given task is done.
1807 >     *
1808 >     * @param joiner the joining worker
1809 >     * @param task the task
1810 >     * @return task status on exit
1811 >     */
1812 >    final int awaitJoin(WorkQueue joiner, ForkJoinTask<?> task) {
1813 >        int s;
1814 >        ForkJoinTask<?> prevJoin = joiner.currentJoin;
1815 >        if ((s = task.status) >= 0) {
1816 >            joiner.currentJoin = task;
1817 >            long startTime = 0L;
1818 >            for (int k = 0;;) {
1819 >                if ((joiner.isEmpty() ?                  // try to help
1820 >                     !tryHelpStealer(joiner, task) :
1821 >                     !joiner.tryRemoveAndExec(task))) {
1822 >                    if (k == 0) {
1823 >                        startTime = System.nanoTime();
1824 >                        tryPollForAndExec(joiner, task); // check uncommon case
1825 >                    }
1826 >                    else if ((k & (MAX_HELP - 1)) == 0 &&
1827 >                             System.nanoTime() - startTime >=
1828 >                             COMPENSATION_DELAY &&
1829 >                             tryCompensate(task, null)) {
1830 >                        if (task.trySetSignal() && task.status >= 0) {
1831 >                            synchronized (task) {
1832 >                                if (task.status >= 0) {
1833 >                                    try {                // see ForkJoinTask
1834 >                                        task.wait();     //  for explanation
1835 >                                    } catch (InterruptedException ie) {
1836 >                                    }
1837 >                                }
1838 >                                else
1839 >                                    task.notifyAll();
1840 >                            }
1841 >                        }
1842 >                        long c;                          // re-activate
1843 >                        do {} while (!U.compareAndSwapLong
1844 >                                     (this, CTL, c = ctl, c + AC_UNIT));
1845 >                    }
1846 >                }
1847 >                if ((s = task.status) < 0) {
1848 >                    joiner.currentJoin = prevJoin;
1849 >                    break;
1850 >                }
1851 >                else if ((k++ & (MAX_HELP - 1)) == MAX_HELP >>> 1)
1852 >                    Thread.yield();                     // for politeness
1853 >            }
1854 >        }
1855 >        return s;
1856 >    }
1857 >
1858 >    /**
1859 >     * Stripped-down variant of awaitJoin used by timed joins. Tries
1860 >     * to help join only while there is continuous progress. (Caller
1861 >     * will then enter a timed wait.)
1862 >     *
1863 >     * @param joiner the joining worker
1864 >     * @param task the task
1865 >     * @return task status on exit
1866 >     */
1867 >    final int helpJoinOnce(WorkQueue joiner, ForkJoinTask<?> task) {
1868 >        int s;
1869 >        while ((s = task.status) >= 0 &&
1870 >               (joiner.isEmpty() ?
1871 >                tryHelpStealer(joiner, task) :
1872 >                joiner.tryRemoveAndExec(task)))
1873 >            ;
1874 >        return s;
1875 >    }
1876 >
1877 >    /**
1878 >     * Returns a (probably) non-empty steal queue, if one is found
1879 >     * during a random, then cyclic scan, else null.  This method must
1880 >     * be retried by caller if, by the time it tries to use the queue,
1881 >     * it is empty.
1882       */
1883      private WorkQueue findNonEmptyStealQueue(WorkQueue w) {
1884 <        int r = w.seed;    // Same idea as scan(), but ignoring submissions
1884 >        // Similar to loop in scan(), but ignoring submissions
1885 >        int r = w.seed; r ^= r << 13; r ^= r >>> 17; w.seed = r ^= r << 5;
1886 >        int step = (r >>> 16) | 1;
1887          for (WorkQueue[] ws;;) {
1888 <            int m = runState & SMASK;
1889 <            if ((ws = workQueues) == null)
1888 >            int rs = runState, m;
1889 >            if ((ws = workQueues) == null || (m = ws.length - 1) < 1)
1890                  return null;
1891 <            if (ws.length > m) {
1892 <                WorkQueue q;
1893 <                for (int n = m << 2, k = r, j = -n;;) {
1894 <                    r ^= r << 13; r ^= r >>> 17; r ^= r << 5;
1895 <                    if ((q = ws[(k | 1) & m]) != null && q.base - q.top < 0) {
1896 <                        w.seed = r;
1671 <                        return q;
1672 <                    }
1673 <                    else if (j > n)
1891 >            for (int j = (m + 1) << 2; ; r += step) {
1892 >                WorkQueue q = ws[((r << 1) | 1) & m];
1893 >                if (q != null && !q.isEmpty())
1894 >                    return q;
1895 >                else if (--j < 0) {
1896 >                    if (runState == rs)
1897                          return null;
1898 <                    else
1676 <                        k = (j++ < 0) ? r : k + ((m >>> 1) | 1);
1677 <
1898 >                    break;
1899                  }
1900              }
1901          }
# Line 1688 | Line 1909 | public class ForkJoinPool extends Abstra
1909       */
1910      final void helpQuiescePool(WorkQueue w) {
1911          for (boolean active = true;;) {
1912 <            w.runLocalTasks();      // exhaust local queue
1912 >            ForkJoinTask<?> localTask; // exhaust local queue
1913 >            while ((localTask = w.nextLocalTask()) != null)
1914 >                localTask.doExec();
1915              WorkQueue q = findNonEmptyStealQueue(w);
1916              if (q != null) {
1917 <                ForkJoinTask<?> t;
1917 >                ForkJoinTask<?> t; int b;
1918                  if (!active) {      // re-establish active count
1919                      long c;
1920                      active = true;
1921                      do {} while (!U.compareAndSwapLong
1922                                   (this, CTL, c = ctl, c + AC_UNIT));
1923                  }
1924 <                if ((t = q.poll()) != null)
1924 >                if ((b = q.base) - q.top < 0 && (t = q.pollAt(b)) != null)
1925                      w.runSubtask(t);
1926              }
1927              else {
# Line 1720 | Line 1943 | public class ForkJoinPool extends Abstra
1943      }
1944  
1945      /**
1946 <     * Gets and removes a local or stolen task for the given worker
1946 >     * Gets and removes a local or stolen task for the given worker.
1947       *
1948       * @return a task, if available
1949       */
1950      final ForkJoinTask<?> nextTaskFor(WorkQueue w) {
1951          for (ForkJoinTask<?> t;;) {
1952 <            WorkQueue q;
1952 >            WorkQueue q; int b;
1953              if ((t = w.nextLocalTask()) != null)
1954                  return t;
1955              if ((q = findNonEmptyStealQueue(w)) == null)
1956                  return null;
1957 <            if ((t = q.poll()) != null)
1957 >            if ((b = q.base) - q.top < 0 && (t = q.pollAt(b)) != null)
1958                  return t;
1959          }
1960      }
# Line 1752 | Line 1975 | public class ForkJoinPool extends Abstra
1975                  8);
1976      }
1977  
1978 <    // Termination
1978 >    //  Termination
1979  
1980      /**
1981 <     * Sets SHUTDOWN bit of runState under lock
1982 <     */
1983 <    private void enableShutdown() {
1984 <        ReentrantLock lock = this.lock;
1985 <        if (runState >= 0) {
1986 <            lock.lock();                       // don't need try/finally
1987 <            runState |= SHUTDOWN;
1765 <            lock.unlock();
1766 <        }
1767 <    }
1768 <
1769 <    /**
1770 <     * Possibly initiates and/or completes termination.  Upon
1771 <     * termination, cancels all queued tasks and then
1981 >     * Possibly initiates and/or completes termination.  The caller
1982 >     * triggering termination runs three passes through workQueues:
1983 >     * (0) Setting termination status, followed by wakeups of queued
1984 >     * workers; (1) cancelling all tasks; (2) interrupting lagging
1985 >     * threads (likely in external tasks, but possibly also blocked in
1986 >     * joins).  Each pass repeats previous steps because of potential
1987 >     * lagging thread creation.
1988       *
1989       * @param now if true, unconditionally terminate, else only
1990       * if no work and no active workers
1991 +     * @param enable if true, enable shutdown when next possible
1992       * @return true if now terminating or terminated
1993       */
1994 <    private boolean tryTerminate(boolean now) {
1994 >    private boolean tryTerminate(boolean now, boolean enable) {
1995 >        Mutex lock = this.lock;
1996          for (long c;;) {
1997              if (((c = ctl) & STOP_BIT) != 0) {      // already terminating
1998                  if ((short)(c >>> TC_SHIFT) == -parallelism) {
1781                    ReentrantLock lock = this.lock; // signal when no workers
1999                      lock.lock();                    // don't need try/finally
2000                      termination.signalAll();        // signal when 0 workers
2001                      lock.unlock();
2002                  }
2003                  return true;
2004              }
2005 <            if (!now) {
2006 <                if ((int)(c >> AC_SHIFT) != -parallelism || runState >= 0 ||
2005 >            if (runState >= 0) {                    // not yet enabled
2006 >                if (!enable)
2007 >                    return false;
2008 >                lock.lock();
2009 >                runState |= SHUTDOWN;
2010 >                lock.unlock();
2011 >            }
2012 >            if (!now) {                             // check if idle & no tasks
2013 >                if ((int)(c >> AC_SHIFT) != -parallelism ||
2014                      hasQueuedSubmissions())
2015                      return false;
2016                  // Check for unqueued inactive workers. One pass suffices.
2017                  WorkQueue[] ws = workQueues; WorkQueue w;
2018                  if (ws != null) {
2019 <                    int n = ws.length;
1796 <                    for (int i = 1; i < n; i += 2) {
2019 >                    for (int i = 1; i < ws.length; i += 2) {
2020                          if ((w = ws[i]) != null && w.eventCount >= 0)
2021                              return false;
2022                      }
2023                  }
2024              }
2025 <            if (U.compareAndSwapLong(this, CTL, c, c | STOP_BIT))
2026 <                startTerminating();
2027 <        }
2028 <    }
2029 <
2030 <    /**
2031 <     * Initiates termination: Runs three passes through workQueues:
2032 <     * (0) Setting termination status, followed by wakeups of queued
2033 <     * workers; (1) cancelling all tasks; (2) interrupting lagging
2034 <     * threads (likely in external tasks, but possibly also blocked in
2035 <     * joins).  Each pass repeats previous steps because of potential
2036 <     * lagging thread creation.
2037 <     */
1815 <    private void startTerminating() {
1816 <        for (int pass = 0; pass < 3; ++pass) {
1817 <            WorkQueue[] ws = workQueues;
1818 <            if (ws != null) {
1819 <                WorkQueue w; Thread wt;
1820 <                int n = ws.length;
1821 <                for (int j = 0; j < n; ++j) {
1822 <                    if ((w = ws[j]) != null) {
1823 <                        w.runState = -1;
1824 <                        if (pass > 0) {
1825 <                            w.cancelAll();
1826 <                            if (pass > 1 && (wt = w.owner) != null &&
1827 <                                !wt.isInterrupted()) {
1828 <                                try {
1829 <                                    wt.interrupt();
1830 <                                } catch (SecurityException ignore) {
2025 >            if (U.compareAndSwapLong(this, CTL, c, c | STOP_BIT)) {
2026 >                for (int pass = 0; pass < 3; ++pass) {
2027 >                    WorkQueue[] ws = workQueues;
2028 >                    if (ws != null) {
2029 >                        WorkQueue w;
2030 >                        int n = ws.length;
2031 >                        for (int i = 0; i < n; ++i) {
2032 >                            if ((w = ws[i]) != null) {
2033 >                                w.runState = -1;
2034 >                                if (pass > 0) {
2035 >                                    w.cancelAll();
2036 >                                    if (pass > 1)
2037 >                                        w.interruptOwner();
2038                                  }
2039                              }
2040                          }
2041 <                    }
2042 <                }
2043 <                // Wake up workers parked on event queue
2044 <                int i, e; long c; Thread p;
2045 <                while ((i = ((~(e = (int)(c = ctl)) << 1) | 1) & SMASK) < n &&
2046 <                       (w = ws[i]) != null &&
2047 <                       w.eventCount == (e | INT_SIGN)) {
2048 <                    long nc = ((long)(w.nextWait & E_MASK) |
2049 <                               ((c + AC_UNIT) & AC_MASK) |
2050 <                               (c & (TC_MASK|STOP_BIT)));
2051 <                    if (U.compareAndSwapLong(this, CTL, c, nc)) {
2052 <                        w.eventCount = (e + E_SEQ) & E_MASK;
2053 <                        if ((p = w.parker) != null)
2054 <                            U.unpark(p);
2041 >                        // Wake up workers parked on event queue
2042 >                        int i, e; long cc; Thread p;
2043 >                        while ((e = (int)(cc = ctl) & E_MASK) != 0 &&
2044 >                               (i = e & SMASK) < n &&
2045 >                               (w = ws[i]) != null) {
2046 >                            long nc = ((long)(w.nextWait & E_MASK) |
2047 >                                       ((cc + AC_UNIT) & AC_MASK) |
2048 >                                       (cc & (TC_MASK|STOP_BIT)));
2049 >                            if (w.eventCount == (e | INT_SIGN) &&
2050 >                                U.compareAndSwapLong(this, CTL, cc, nc)) {
2051 >                                w.eventCount = (e + E_SEQ) & E_MASK;
2052 >                                w.runState = -1;
2053 >                                if ((p = w.parker) != null)
2054 >                                    U.unpark(p);
2055 >                            }
2056 >                        }
2057                      }
2058                  }
2059              }
# Line 1920 | Line 2129 | public class ForkJoinPool extends Abstra
2129          checkPermission();
2130          if (factory == null)
2131              throw new NullPointerException();
2132 <        if (parallelism <= 0 || parallelism > MAX_ID)
2132 >        if (parallelism <= 0 || parallelism > MAX_CAP)
2133              throw new IllegalArgumentException();
2134          this.parallelism = parallelism;
2135          this.factory = factory;
2136          this.ueh = handler;
2137          this.localMode = asyncMode ? FIFO_QUEUE : LIFO_QUEUE;
1929        this.nextPoolIndex = 1;
2138          long np = (long)(-parallelism); // offset ctl counts
2139          this.ctl = ((np << AC_SHIFT) & AC_MASK) | ((np << TC_SHIFT) & TC_MASK);
2140 <        // initialize workQueues array with room for 2*parallelism if possible
2141 <        int n = parallelism << 1;
2142 <        if (n >= MAX_ID)
2143 <            n = MAX_ID;
2144 <        else { // See Hackers Delight, sec 3.2, where n < (1 << 16)
2145 <            n |= n >>> 1; n |= n >>> 2; n |= n >>> 4; n |= n >>> 8;
2146 <        }
1939 <        this.workQueues = new WorkQueue[(n + 1) << 1];
1940 <        ReentrantLock lck = this.lock = new ReentrantLock();
1941 <        this.termination = lck.newCondition();
2140 >        // Use nearest power 2 for workQueues size. See Hackers Delight sec 3.2.
2141 >        int n = parallelism - 1;
2142 >        n |= n >>> 1; n |= n >>> 2; n |= n >>> 4; n |= n >>> 8; n |= n >>> 16;
2143 >        int size = (n + 1) << 1;        // #slots = 2*#workers
2144 >        this.submitMask = size - 1;     // room for max # of submit queues
2145 >        this.workQueues = new WorkQueue[size];
2146 >        this.termination = (this.lock = new Mutex()).newCondition();
2147          this.stealCount = new AtomicLong();
2148          this.nextWorkerNumber = new AtomicInteger();
2149 +        int pn = poolNumberGenerator.incrementAndGet();
2150          StringBuilder sb = new StringBuilder("ForkJoinPool-");
2151 <        sb.append(poolNumberGenerator.incrementAndGet());
2151 >        sb.append(Integer.toString(pn));
2152          sb.append("-worker-");
2153          this.workerNamePrefix = sb.toString();
2154 <        // Create initial submission queue
2155 <        WorkQueue sq = tryAddSharedQueue(0);
2156 <        if (sq != null)
1951 <            sq.growArray(false);
2154 >        lock.lock();
2155 >        this.runState = 1;              // set init flag
2156 >        lock.unlock();
2157      }
2158  
2159      // Execution methods
# Line 1970 | Line 2175 | public class ForkJoinPool extends Abstra
2175       *         scheduled for execution
2176       */
2177      public <T> T invoke(ForkJoinTask<T> task) {
2178 +        if (task == null)
2179 +            throw new NullPointerException();
2180          doSubmit(task);
2181          return task.join();
2182      }
# Line 1983 | Line 2190 | public class ForkJoinPool extends Abstra
2190       *         scheduled for execution
2191       */
2192      public void execute(ForkJoinTask<?> task) {
2193 +        if (task == null)
2194 +            throw new NullPointerException();
2195          doSubmit(task);
2196      }
2197  
# Line 2000 | Line 2209 | public class ForkJoinPool extends Abstra
2209          if (task instanceof ForkJoinTask<?>) // avoid re-wrap
2210              job = (ForkJoinTask<?>) task;
2211          else
2212 <            job = ForkJoinTask.adapt(task, null);
2212 >            job = new ForkJoinTask.AdaptedRunnableAction(task);
2213          doSubmit(job);
2214      }
2215  
# Line 2014 | Line 2223 | public class ForkJoinPool extends Abstra
2223       *         scheduled for execution
2224       */
2225      public <T> ForkJoinTask<T> submit(ForkJoinTask<T> task) {
2226 +        if (task == null)
2227 +            throw new NullPointerException();
2228          doSubmit(task);
2229          return task;
2230      }
# Line 2024 | Line 2235 | public class ForkJoinPool extends Abstra
2235       *         scheduled for execution
2236       */
2237      public <T> ForkJoinTask<T> submit(Callable<T> task) {
2238 <        if (task == null)
2028 <            throw new NullPointerException();
2029 <        ForkJoinTask<T> job = ForkJoinTask.adapt(task);
2238 >        ForkJoinTask<T> job = new ForkJoinTask.AdaptedCallable<T>(task);
2239          doSubmit(job);
2240          return job;
2241      }
# Line 2037 | Line 2246 | public class ForkJoinPool extends Abstra
2246       *         scheduled for execution
2247       */
2248      public <T> ForkJoinTask<T> submit(Runnable task, T result) {
2249 <        if (task == null)
2041 <            throw new NullPointerException();
2042 <        ForkJoinTask<T> job = ForkJoinTask.adapt(task, result);
2249 >        ForkJoinTask<T> job = new ForkJoinTask.AdaptedRunnable<T>(task, result);
2250          doSubmit(job);
2251          return job;
2252      }
# Line 2056 | Line 2263 | public class ForkJoinPool extends Abstra
2263          if (task instanceof ForkJoinTask<?>) // avoid re-wrap
2264              job = (ForkJoinTask<?>) task;
2265          else
2266 <            job = ForkJoinTask.adapt(task, null);
2266 >            job = new ForkJoinTask.AdaptedRunnableAction(task);
2267          doSubmit(job);
2268          return job;
2269      }
# Line 2066 | Line 2273 | public class ForkJoinPool extends Abstra
2273       * @throws RejectedExecutionException {@inheritDoc}
2274       */
2275      public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) {
2276 <        ArrayList<ForkJoinTask<T>> forkJoinTasks =
2277 <            new ArrayList<ForkJoinTask<T>>(tasks.size());
2278 <        for (Callable<T> task : tasks)
2279 <            forkJoinTasks.add(ForkJoinTask.adapt(task));
2280 <        invoke(new InvokeAll<T>(forkJoinTasks));
2281 <
2276 >        // In previous versions of this class, this method constructed
2277 >        // a task to run ForkJoinTask.invokeAll, but now external
2278 >        // invocation of multiple tasks is at least as efficient.
2279 >        List<ForkJoinTask<T>> fs = new ArrayList<ForkJoinTask<T>>(tasks.size());
2280 >        // Workaround needed because method wasn't declared with
2281 >        // wildcards in return type but should have been.
2282          @SuppressWarnings({"unchecked", "rawtypes"})
2283 <            List<Future<T>> futures = (List<Future<T>>) (List) forkJoinTasks;
2077 <        return futures;
2078 <    }
2283 >            List<Future<T>> futures = (List<Future<T>>) (List) fs;
2284  
2285 <    static final class InvokeAll<T> extends RecursiveAction {
2286 <        final ArrayList<ForkJoinTask<T>> tasks;
2287 <        InvokeAll(ArrayList<ForkJoinTask<T>> tasks) { this.tasks = tasks; }
2288 <        public void compute() {
2289 <            try { invokeAll(tasks); }
2290 <            catch (Exception ignore) {}
2285 >        boolean done = false;
2286 >        try {
2287 >            for (Callable<T> t : tasks) {
2288 >                ForkJoinTask<T> f = new ForkJoinTask.AdaptedCallable<T>(t);
2289 >                doSubmit(f);
2290 >                fs.add(f);
2291 >            }
2292 >            for (ForkJoinTask<T> f : fs)
2293 >                f.quietlyJoin();
2294 >            done = true;
2295 >            return futures;
2296 >        } finally {
2297 >            if (!done)
2298 >                for (ForkJoinTask<T> f : fs)
2299 >                    f.cancel(false);
2300          }
2087        private static final long serialVersionUID = -7914297376763021607L;
2301      }
2302  
2303      /**
# Line 2149 | Line 2362 | public class ForkJoinPool extends Abstra
2362          int rc = 0;
2363          WorkQueue[] ws; WorkQueue w;
2364          if ((ws = workQueues) != null) {
2365 <            int n = ws.length;
2366 <            for (int i = 1; i < n; i += 2) {
2154 <                Thread.State s; ForkJoinWorkerThread wt;
2155 <                if ((w = ws[i]) != null && (wt = w.owner) != null &&
2156 <                    w.eventCount >= 0 &&
2157 <                    (s = wt.getState()) != Thread.State.BLOCKED &&
2158 <                    s != Thread.State.WAITING &&
2159 <                    s != Thread.State.TIMED_WAITING)
2365 >            for (int i = 1; i < ws.length; i += 2) {
2366 >                if ((w = ws[i]) != null && w.isApparentlyUnblocked())
2367                      ++rc;
2368              }
2369          }
# Line 2205 | Line 2412 | public class ForkJoinPool extends Abstra
2412          long count = stealCount.get();
2413          WorkQueue[] ws; WorkQueue w;
2414          if ((ws = workQueues) != null) {
2415 <            int n = ws.length;
2209 <            for (int i = 1; i < n; i += 2) {
2415 >            for (int i = 1; i < ws.length; i += 2) {
2416                  if ((w = ws[i]) != null)
2417                      count += w.totalSteals;
2418              }
# Line 2228 | Line 2434 | public class ForkJoinPool extends Abstra
2434          long count = 0;
2435          WorkQueue[] ws; WorkQueue w;
2436          if ((ws = workQueues) != null) {
2437 <            int n = ws.length;
2232 <            for (int i = 1; i < n; i += 2) {
2437 >            for (int i = 1; i < ws.length; i += 2) {
2438                  if ((w = ws[i]) != null)
2439                      count += w.queueSize();
2440              }
# Line 2248 | Line 2453 | public class ForkJoinPool extends Abstra
2453          int count = 0;
2454          WorkQueue[] ws; WorkQueue w;
2455          if ((ws = workQueues) != null) {
2456 <            int n = ws.length;
2252 <            for (int i = 0; i < n; i += 2) {
2456 >            for (int i = 0; i < ws.length; i += 2) {
2457                  if ((w = ws[i]) != null)
2458                      count += w.queueSize();
2459              }
# Line 2266 | Line 2470 | public class ForkJoinPool extends Abstra
2470      public boolean hasQueuedSubmissions() {
2471          WorkQueue[] ws; WorkQueue w;
2472          if ((ws = workQueues) != null) {
2473 <            int n = ws.length;
2474 <            for (int i = 0; i < n; i += 2) {
2271 <                if ((w = ws[i]) != null && w.queueSize() != 0)
2473 >            for (int i = 0; i < ws.length; i += 2) {
2474 >                if ((w = ws[i]) != null && !w.isEmpty())
2475                      return true;
2476              }
2477          }
# Line 2285 | Line 2488 | public class ForkJoinPool extends Abstra
2488      protected ForkJoinTask<?> pollSubmission() {
2489          WorkQueue[] ws; WorkQueue w; ForkJoinTask<?> t;
2490          if ((ws = workQueues) != null) {
2491 <            int n = ws.length;
2289 <            for (int i = 0; i < n; i += 2) {
2491 >            for (int i = 0; i < ws.length; i += 2) {
2492                  if ((w = ws[i]) != null && (t = w.poll()) != null)
2493                      return t;
2494              }
# Line 2315 | Line 2517 | public class ForkJoinPool extends Abstra
2517          int count = 0;
2518          WorkQueue[] ws; WorkQueue w; ForkJoinTask<?> t;
2519          if ((ws = workQueues) != null) {
2520 <            int n = ws.length;
2319 <            for (int i = 0; i < n; ++i) {
2520 >            for (int i = 0; i < ws.length; ++i) {
2521                  if ((w = ws[i]) != null) {
2522                      while ((t = w.poll()) != null) {
2523                          c.add(t);
# Line 2336 | Line 2537 | public class ForkJoinPool extends Abstra
2537       * @return a string identifying this pool, as well as its state
2538       */
2539      public String toString() {
2540 <        long st = getStealCount();
2541 <        long qt = getQueuedTaskCount();
2542 <        long qs = getQueuedSubmissionCount();
2342 <        int rc = getRunningThreadCount();
2343 <        int pc = parallelism;
2540 >        // Use a single pass through workQueues to collect counts
2541 >        long qt = 0L, qs = 0L; int rc = 0;
2542 >        long st = stealCount.get();
2543          long c = ctl;
2544 +        WorkQueue[] ws; WorkQueue w;
2545 +        if ((ws = workQueues) != null) {
2546 +            for (int i = 0; i < ws.length; ++i) {
2547 +                if ((w = ws[i]) != null) {
2548 +                    int size = w.queueSize();
2549 +                    if ((i & 1) == 0)
2550 +                        qs += size;
2551 +                    else {
2552 +                        qt += size;
2553 +                        st += w.totalSteals;
2554 +                        if (w.isApparentlyUnblocked())
2555 +                            ++rc;
2556 +                    }
2557 +                }
2558 +            }
2559 +        }
2560 +        int pc = parallelism;
2561          int tc = pc + (short)(c >>> TC_SHIFT);
2562          int ac = pc + (int)(c >> AC_SHIFT);
2563          if (ac < 0) // ignore transient negative
# Line 2377 | Line 2593 | public class ForkJoinPool extends Abstra
2593       */
2594      public void shutdown() {
2595          checkPermission();
2596 <        enableShutdown();
2381 <        tryTerminate(false);
2596 >        tryTerminate(false, true);
2597      }
2598  
2599      /**
# Line 2399 | Line 2614 | public class ForkJoinPool extends Abstra
2614       */
2615      public List<Runnable> shutdownNow() {
2616          checkPermission();
2617 <        enableShutdown();
2403 <        tryTerminate(true);
2617 >        tryTerminate(true, true);
2618          return Collections.emptyList();
2619      }
2620  
# Line 2457 | Line 2671 | public class ForkJoinPool extends Abstra
2671      public boolean awaitTermination(long timeout, TimeUnit unit)
2672          throws InterruptedException {
2673          long nanos = unit.toNanos(timeout);
2674 <        final ReentrantLock lock = this.lock;
2674 >        final Mutex lock = this.lock;
2675          lock.lock();
2676          try {
2677              for (;;) {
# Line 2571 | Line 2785 | public class ForkJoinPool extends Abstra
2785          ForkJoinPool p = ((t instanceof ForkJoinWorkerThread) ?
2786                            ((ForkJoinWorkerThread)t).pool : null);
2787          while (!blocker.isReleasable()) {
2788 <            if (p == null || p.tryCompensate()) {
2788 >            if (p == null || p.tryCompensate(null, blocker)) {
2789                  try {
2790                      do {} while (!blocker.isReleasable() && !blocker.block());
2791                  } finally {
# Line 2588 | Line 2802 | public class ForkJoinPool extends Abstra
2802      // implement RunnableFuture.
2803  
2804      protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
2805 <        return (RunnableFuture<T>) ForkJoinTask.adapt(runnable, value);
2805 >        return new ForkJoinTask.AdaptedRunnable<T>(runnable, value);
2806      }
2807  
2808      protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
2809 <        return (RunnableFuture<T>) ForkJoinTask.adapt(callable);
2809 >        return new ForkJoinTask.AdaptedCallable<T>(callable);
2810      }
2811  
2812      // Unsafe mechanics
2813      private static final sun.misc.Unsafe U;
2814      private static final long CTL;
2601    private static final long RUNSTATE;
2815      private static final long PARKBLOCKER;
2816 +    private static final int ABASE;
2817 +    private static final int ASHIFT;
2818  
2819      static {
2820          poolNumberGenerator = new AtomicInteger();
2821 +        nextSubmitterSeed = new AtomicInteger(0x55555555);
2822          modifyThreadPermission = new RuntimePermission("modifyThread");
2823          defaultForkJoinWorkerThreadFactory =
2824              new DefaultForkJoinWorkerThreadFactory();
2825 +        submitters = new ThreadSubmitter();
2826          int s;
2827          try {
2828              U = getUnsafe();
2829              Class<?> k = ForkJoinPool.class;
2830 <            Class<?> tk = Thread.class;
2830 >            Class<?> ak = ForkJoinTask[].class;
2831              CTL = U.objectFieldOffset
2832                  (k.getDeclaredField("ctl"));
2833 <            RUNSTATE = U.objectFieldOffset
2617 <                (k.getDeclaredField("runState"));
2833 >            Class<?> tk = Thread.class;
2834              PARKBLOCKER = U.objectFieldOffset
2835                  (tk.getDeclaredField("parkBlocker"));
2836 +            ABASE = U.arrayBaseOffset(ak);
2837 +            s = U.arrayIndexScale(ak);
2838          } catch (Exception e) {
2839              throw new Error(e);
2840          }
2841 +        if ((s & (s-1)) != 0)
2842 +            throw new Error("data type scale not a power of two");
2843 +        ASHIFT = 31 - Integer.numberOfLeadingZeros(s);
2844      }
2845  
2846      /**

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines