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.116 by dl, Fri Jan 27 17:27:28 2012 UTC vs.
Revision 1.128 by dl, Mon Apr 9 13:11:44 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
# Line 204 | Line 205 | public class ForkJoinPool extends Abstra
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. Pool submissions from internal workers are also
209 <     * allowed, but use randomized rather than thread-hashed queue
210 <     * indices to avoid imbalance.  Insertion of tasks in shared mode
211 <     * requires a lock (mainly to protect in the case of resizing) but
212 <     * we use only a simple spinlock (using bits in field runState),
213 <     * because submitters encountering a busy queue try or create
213 <     * others so never block.
208 >     * tasks as well. Insertion of tasks in shared mode requires a
209 >     * lock (mainly to protect in the case of resizing) but we use
210 >     * only a simple spinlock (using bits in field runState), because
211 >     * submitters encountering a busy queue move on to try or create
212 >     * other queues -- they block only when creating and registering
213 >     * new queues.
214       *
215 <     * Management.
215 >     * Management
216       * ==========
217       *
218       * The main throughput advantages of work-stealing stem from
# Line 222 | 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 248 | 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
255 <     * mask for the nearest power of two that contains all current
256 <     * workers.  All worker thread creation is on-demand, triggered by
257 <     * 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 267 | 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
276 <     * 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 301 | 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 329 | 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 338 | 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 384 | 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 396 | 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 419 | 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
446 <     * few little helpers); (7) static block initializing all statics
447 <     * 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 475 | 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 <
505 <    /**
506 <     * Bits and masks for control variables
507 <     *
508 <     * Field ctl is a long packed with:
509 <     * AC: Number of active running workers minus target parallelism (16 bits)
510 <     * TC: Number of total workers minus target parallelism (16 bits)
511 <     * ST: true if pool is terminating (1 bit)
512 <     * EC: the wait count of top waiting thread (15 bits)
513 <     * ID: ~(poolIndex >>> 1) of top of Treiber stack of waiters (16 bits)
514 <     *
515 <     * When convenient, we can extract the upper 32 bits of counts and
516 <     * the lower 32 bits of queue state, u = (int)(ctl >>> 32) and e =
517 <     * (int)ctl.  The ec field is never accessed alone, but always
518 <     * together with id and st. The offsets of counts by the target
519 <     * parallelism and the positionings of fields makes it possible to
520 <     * perform the most common checks via sign tests of fields: When
521 <     * ac is negative, there are not enough active workers, when tc is
522 <     * negative, there are not enough total workers, when id is
523 <     * negative, there is at least one waiting worker, and when e is
524 <     * negative, the pool is terminating.  To deal with these possibly
525 <     * negative fields, we use casts in and out of "short" and/or
526 <     * signed shifts to maintain signedness.
527 <     *
528 <     * When a thread is queued (inactivated), its eventCount field is
529 <     * negative, which is the only way to tell if a worker is
530 <     * prevented from executing tasks, even though it must continue to
531 <     * scan for them to avoid queuing races.
532 <     *
533 <     * Field runState is an int packed with:
534 <     * SHUTDOWN: true if shutdown is enabled (1 bit)
535 <     * SEQ:  a sequence number updated upon (de)registering workers (15 bits)
536 <     * MASK: mask (power of 2 - 1) covering all registered poolIndexes (16 bits)
537 <     *
538 <     * The combination of mask and sequence number enables simple
539 <     * consistency checks: Staleness of read-only operations on the
540 <     * workers and queues arrays can be checked by comparing runState
541 <     * before vs after the reads. The low 16 bits (i.e, anding with
542 <     * SMASK) hold (the smallest power of two covering all worker
543 <     * indices, minus one.  The mask for queues (vs workers) is twice
544 <     * this value plus 1.
545 <     */
546 <
547 <    // bit positions/shifts for fields
548 <    private static final int  AC_SHIFT   = 48;
549 <    private static final int  TC_SHIFT   = 32;
550 <    private static final int  ST_SHIFT   = 31;
551 <    private static final int  EC_SHIFT   = 16;
552 <
553 <    // bounds
554 <    private static final int  MAX_ID     = 0x7fff;  // max poolIndex
555 <    private static final int  SMASK      = 0xffff;  // mask short bits
556 <    private static final int  SHORT_SIGN = 1 << 15;
557 <    private static final int  INT_SIGN   = 1 << 31;
558 <
559 <    // masks
560 <    private static final long STOP_BIT   = 0x0001L << ST_SHIFT;
561 <    private static final long AC_MASK    = ((long)SMASK) << AC_SHIFT;
562 <    private static final long TC_MASK    = ((long)SMASK) << TC_SHIFT;
563 <
564 <    // units for incrementing and decrementing
565 <    private static final long TC_UNIT    = 1L << TC_SHIFT;
566 <    private static final long AC_UNIT    = 1L << AC_SHIFT;
567 <
568 <    // masks and units for dealing with u = (int)(ctl >>> 32)
569 <    private static final int  UAC_SHIFT  = AC_SHIFT - 32;
570 <    private static final int  UTC_SHIFT  = TC_SHIFT - 32;
571 <    private static final int  UAC_MASK   = SMASK << UAC_SHIFT;
572 <    private static final int  UTC_MASK   = SMASK << UTC_SHIFT;
573 <    private static final int  UAC_UNIT   = 1 << UAC_SHIFT;
574 <    private static final int  UTC_UNIT   = 1 << UTC_SHIFT;
575 <
576 <    // masks and units for dealing with e = (int)ctl
577 <    private static final int E_MASK      = 0x7fffffff; // no STOP_BIT
578 <    private static final int E_SEQ       = 1 << EC_SHIFT;
579 <
580 <    // runState bits
581 <    private static final int SHUTDOWN    = 1 << 31;
582 <    private static final int RS_SEQ      = 1 << 16;
583 <    private static final int RS_SEQ_MASK = 0x7fff0000;
584 <
585 <    // access mode for WorkQueue
586 <    static final int LIFO_QUEUE          =  0;
587 <    static final int FIFO_QUEUE          =  1;
588 <    static final int SHARED_QUEUE        = -1;
589 <
590 <    /**
591 <     * The wakeup interval (in nanoseconds) for a worker waiting for a
592 <     * task when the pool is quiescent to instead try to shrink the
593 <     * number of workers.  The exact value does not matter too
594 <     * much. It must be short enough to release resources during
595 <     * sustained periods of idleness, but not so short that threads
596 <     * are continually re-created.
597 <     */
598 <    private static final long SHRINK_RATE =
599 <        4L * 1000L * 1000L * 1000L; // 4 seconds
600 <
601 <    /**
602 <     * The timeout value for attempted shrinkage, includes
603 <     * some slop to cope with system timer imprecision.
604 <     */
605 <    private static final long SHRINK_TIMEOUT = SHRINK_RATE - (SHRINK_RATE / 10);
606 <
607 <    /**
608 <     * The maximum stolen->joining link depth allowed in tryHelpStealer.
609 <     * Depths for legitimate chains are unbounded, but we use a fixed
610 <     * constant to avoid (otherwise unchecked) cycles and to bound
611 <     * staleness of traversal parameters at the expense of sometimes
612 <     * blocking when we could be helping.
613 <     */
614 <    private static final int MAX_HELP_DEPTH = 16;
615 <
616 <    /*
617 <     * Field layout order in this class tends to matter more than one
618 <     * would like. Runtime layout order is only loosely related to
619 <     * declaration order and may differ across JVMs, but the following
620 <     * 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
628 <    WorkQueue[] workQueues;                  // main registry
629 <    final ReentrantLock lock;                // for registration
630 <    final Condition termination;             // for awaitTermination
631 <    final ForkJoinWorkerThreadFactory factory; // factory for new workers
632 <    final Thread.UncaughtExceptionHandler ueh; // per-worker UEH
633 <    final AtomicLong stealCount;             // collect counts when terminated
634 <    final AtomicInteger nextWorkerNumber;    // to create worker name string
635 <    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 683 | 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 717 | 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
632 >        volatile ForkJoinTask<?> currentJoin;  // task being joined in awaitJoin
633          ForkJoinTask<?> currentSteal; // current non-local task being executed
634          // Heuristic padding to ameliorate unfortunate memory placements
635 <        Object p00, p01, p02, p03, p04, p05, p06, p07, 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) {
728 <            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
747 <         * @throw RejectedExecutionException if array cannot
748 <         * 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 773 | 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 790 | 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 808 | Line 756 | public class ForkJoinPool extends Abstra
756          }
757  
758          /**
759 <         * Takes next task, if one exists, in LIFO order.
812 <         * 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)) {
823 <                        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 848 | Line 799 | public class ForkJoinPool extends Abstra
799          }
800  
801          /**
851         * Returns task at index b if b is current base of queue.
852         */
853        final ForkJoinTask<?> pollAt(int b) {
854            ForkJoinTask<?>[] a; int i;
855            ForkJoinTask<?> task = null;
856            if ((a = array) != null && (i = ((a.length - 1) & b)) >= 0) {
857                int j = (i << ASHIFT) + ABASE;
858                ForkJoinTask<?> t = (ForkJoinTask<?>)U.getObjectVolatile(a, j);
859                if (t != null && base == b &&
860                    U.compareAndSwapObject(a, j, t, null)) {
861                    base = b + 1;
862                    task = t;
863                }
864            }
865            return task;
866        }
867
868        /**
802           * Pops the given task only if it is at the current top.
803           */
804          final boolean tryUnpush(ForkJoinTask<?> t) {
# Line 883 | 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) {
889 <                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 897 | Line 829 | public class ForkJoinPool extends Abstra
829          }
830  
831          /**
900         * If present, removes from queue and executes the given task, or
901         * any other cancelled task. Returns (true) immediately on any CAS
902         * or consistency check failure so caller can retry.
903         *
904         * @return false if no progress can be made
905         */
906        final boolean tryRemoveAndExec(ForkJoinTask<?> task) {
907            boolean removed = false, empty = true, progress = true;
908            ForkJoinTask<?>[] a; int m, s, b, n;
909            if ((a = array) != null && (m = a.length - 1) >= 0 &&
910                (n = (s = top) - (b = base)) > 0) {
911                for (ForkJoinTask<?> t;;) {           // traverse from s to b
912                    int j = ((--s & m) << ASHIFT) + ABASE;
913                    t = (ForkJoinTask<?>)U.getObjectVolatile(a, j);
914                    if (t == null)                    // inconsistent length
915                        break;
916                    else if (t == task) {
917                        if (s + 1 == top) {           // pop
918                            if (!U.compareAndSwapObject(a, j, task, null))
919                                break;
920                            top = s;
921                            removed = true;
922                        }
923                        else if (base == b)           // replace with proxy
924                            removed = U.compareAndSwapObject(a, j, task,
925                                                             new EmptyTask());
926                        break;
927                    }
928                    else if (t.status >= 0)
929                        empty = false;
930                    else if (s + 1 == top) {          // pop and throw away
931                        if (U.compareAndSwapObject(a, j, t, null))
932                            top = s;
933                        break;
934                    }
935                    if (--n == 0) {
936                        if (!empty && base == b)
937                            progress = false;
938                        break;
939                    }
940                }
941            }
942            if (removed)
943                task.doExec();
944            return progress;
945        }
946
947        /**
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 980 | 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 989 | 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
996 <         * 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 0 if no progress can be made, else positive
924 +         * (this unusual convention simplifies use with tryHelpStealer.)
925 +         */
926 +        final int tryRemoveAndExec(ForkJoinTask<?> task) {
927 +            int stat = 1;
928 +            boolean removed = false, empty = true;
929 +            ForkJoinTask<?>[] a; int m, s, b, n;
930 +            if ((a = array) != null && (m = a.length - 1) >= 0 &&
931 +                (n = (s = top) - (b = base)) > 0) {
932 +                for (ForkJoinTask<?> t;;) {           // traverse from s to b
933 +                    int j = ((--s & m) << ASHIFT) + ABASE;
934 +                    t = (ForkJoinTask<?>)U.getObjectVolatile(a, j);
935 +                    if (t == null)                    // inconsistent length
936 +                        break;
937 +                    else if (t == task) {
938 +                        if (s + 1 == top) {           // pop
939 +                            if (!U.compareAndSwapObject(a, j, task, null))
940 +                                break;
941 +                            top = s;
942 +                            removed = true;
943 +                        }
944 +                        else if (base == b)           // replace with proxy
945 +                            removed = U.compareAndSwapObject(a, j, task,
946 +                                                             new EmptyTask());
947 +                        break;
948 +                    }
949 +                    else if (t.status >= 0)
950 +                        empty = false;
951 +                    else if (s + 1 == top) {          // pop and throw away
952 +                        if (U.compareAndSwapObject(a, j, t, null))
953 +                            top = s;
954 +                        break;
955 +                    }
956 +                    if (--n == 0) {
957 +                        if (!empty && base == b)
958 +                            stat = 0;
959 +                        break;
960 +                    }
961 +                }
962 +            }
963 +            if (removed)
964 +                task.doExec();
965 +            return stat;
966 +        }
967 +
968 +        /**
969           * Executes a top-level task and any local tasks remaining
970           * after execution.
1008         *
1009         * @return true unless terminating
971           */
972 <        final boolean runTask(ForkJoinTask<?> t) {
1012 <            boolean alive = true;
972 >        final void runTask(ForkJoinTask<?> t) {
973              if (t != null) {
974                  currentSteal = t;
975                  t.doExec();
976 <                runLocalTasks();
976 >                if (top != base) {       // process remaining local tasks
977 >                    if (mode == 0)
978 >                        popAndExecAll();
979 >                    else
980 >                        pollAndExecAll();
981 >                }
982                  ++nsteals;
983                  currentSteal = null;
984              }
1020            else if (runState < 0)            // terminating
1021                alive = false;
1022            return alive;
985          }
986  
987          /**
988 <         * Executes a non-top-level (stolen) task
988 >         * Executes a non-top-level (stolen) task.
989           */
990          final void runSubtask(ForkJoinTask<?> t) {
991              if (t != null) {
# Line 1035 | Line 997 | public class ForkJoinPool extends Abstra
997          }
998  
999          /**
1000 <         * Computes next value for random probes.  Scans don't require
1039 <         * a very high quality generator, but also not a crummy one.
1040 <         * Marsaglia xor-shift is cheap and works well enough.  Note:
1041 <         * This is manually inlined in several usages in ForkJoinPool
1042 <         * to avoid writes inside busy scan loops.
1000 >         * Returns true if owned and not known to be blocked.
1001           */
1002 <        final int nextSeed() {
1003 <            int r = seed;
1004 <            r ^= r << 13;
1005 <            r ^= r >>> 17;
1006 <            r ^= r << 5;
1007 <            return seed = r;
1002 >        final boolean isApparentlyUnblocked() {
1003 >            Thread wt; Thread.State s;
1004 >            return (eventCount >= 0 &&
1005 >                    (wt = owner) != null &&
1006 >                    (s = wt.getState()) != Thread.State.BLOCKED &&
1007 >                    s != Thread.State.WAITING &&
1008 >                    s != Thread.State.TIMED_WAITING);
1009 >        }
1010 >
1011 >        /**
1012 >         * If this owned and is not already interrupted, try to
1013 >         * interrupt and/or unpark, ignoring exceptions.
1014 >         */
1015 >        final void interruptOwner() {
1016 >            Thread wt, p;
1017 >            if ((wt = owner) != null && !wt.isInterrupted()) {
1018 >                try {
1019 >                    wt.interrupt();
1020 >                } catch (SecurityException ignore) {
1021 >                }
1022 >            }
1023 >            if ((p = parker) != null)
1024 >                U.unpark(p);
1025          }
1026  
1027          // Unsafe mechanics
# Line 1072 | Line 1047 | public class ForkJoinPool extends Abstra
1047              ASHIFT = 31 - Integer.numberOfLeadingZeros(s);
1048          }
1049      }
1075
1050      /**
1051 <     * Class for artificial tasks that are used to replace the target
1052 <     * of local joins if they are removed from an interior queue slot
1053 <     * in WorkQueue.tryRemoveAndExec. We don't need the proxy to
1054 <     * actually do anything beyond having a unique identity.
1055 <     */
1056 <    static final class EmptyTask extends ForkJoinTask<Void> {
1057 <        EmptyTask() { status = ForkJoinTask.NORMAL; } // force done
1058 <        public Void getRawResult() { return null; }
1059 <        public void setRawResult(Void x) {}
1060 <        public boolean exec() { return true; }
1061 <    }
1062 <
1063 <    /**
1064 < <<<<<<< ForkJoinPool.java
1091 <     * Per-thread records for (typically non-FJ) threads that submit
1092 <     * to pools. Cureently holds only psuedo-random seed / index that
1093 <     * is used to chose submission queues in method doSubmit. In the
1094 <     * future, this may incorporate a means to implement different
1095 <     * task rejection and resubmission policies.
1051 >     * Per-thread records for threads that submit to pools. Currently
1052 >     * holds only pseudo-random seed / index that is used to choose
1053 >     * submission queues in method doSubmit. In the future, this may
1054 >     * also incorporate a means to implement different task rejection
1055 >     * and resubmission policies.
1056 >     *
1057 >     * Seeds for submitters and workers/workQueues work in basically
1058 >     * the same way but are initialized and updated using slightly
1059 >     * different mechanics. Both are initialized using the same
1060 >     * approach as in class ThreadLocal, where successive values are
1061 >     * unlikely to collide with previous values. This is done during
1062 >     * registration for workers, but requires a separate AtomicInteger
1063 >     * for submitters. Seeds are then randomly modified upon
1064 >     * collisions using xorshifts, which requires a non-zero seed.
1065       */
1066      static final class Submitter {
1067 <        int seed; // seed for random submission queue selection
1099 <
1100 <        // Heuristic padding to ameliorate unfortunate memory placements
1101 <        int p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, pa, pb, pc, pd, pe;
1102 <
1067 >        int seed;
1068          Submitter() {
1069 <            // Use identityHashCode, forced negative, for seed
1070 <            seed = System.identityHashCode(Thread.currentThread()) | (1 << 31);
1106 <        }
1107 <
1108 <        /**
1109 <         * Computes next value for random probes.  Like method
1110 <         * WorkQueue.nextSeed, this is manually inlined in several
1111 <         * usages to avoid writes inside busy loops.
1112 <         */
1113 <        final int nextSeed() {
1114 <            int r = seed;
1115 <            r ^= r << 13;
1116 <            r ^= r >>> 17;
1117 <            return seed = r ^= r << 5;
1069 >            int s = nextSubmitterSeed.getAndAdd(SEED_INCREMENT);
1070 >            seed = (s == 0) ? 1 : s; // ensure non-zero
1071          }
1072      }
1073  
# Line 1123 | Line 1076 | public class ForkJoinPool extends Abstra
1076          public Submitter initialValue() { return new Submitter(); }
1077      }
1078  
1079 +    // static fields (initialized in static initializer below)
1080 +
1081 +    /**
1082 +     * Creates a new ForkJoinWorkerThread. This factory is used unless
1083 +     * overridden in ForkJoinPool constructors.
1084 +     */
1085 +    public static final ForkJoinWorkerThreadFactory
1086 +        defaultForkJoinWorkerThreadFactory;
1087 +
1088 +    /**
1089 +     * Generator for assigning sequence numbers as pool names.
1090 +     */
1091 +    private static final AtomicInteger poolNumberGenerator;
1092 +
1093 +    /**
1094 +     * Generator for initial hashes/seeds for submitters. Accessed by
1095 +     * Submitter class constructor.
1096 +     */
1097 +    static final AtomicInteger nextSubmitterSeed;
1098 +
1099 +    /**
1100 +     * Permission required for callers of methods that may start or
1101 +     * kill threads.
1102 +     */
1103 +    private static final RuntimePermission modifyThreadPermission;
1104 +
1105      /**
1106       * Per-thread submission bookeeping. Shared across all pools
1107       * to reduce ThreadLocal pollution and because random motion
1108       * to avoid contention in one pool is likely to hold for others.
1109       */
1110 <    static final ThreadSubmitter submitters = new ThreadSubmitter();
1110 >    private static final ThreadSubmitter submitters;
1111 >
1112 >    // static constants
1113 >
1114 >    /**
1115 >     * The wakeup interval (in nanoseconds) for a worker waiting for a
1116 >     * task when the pool is quiescent to instead try to shrink the
1117 >     * number of workers.  The exact value does not matter too
1118 >     * much. It must be short enough to release resources during
1119 >     * sustained periods of idleness, but not so short that threads
1120 >     * are continually re-created.
1121 >     */
1122 >    private static final long SHRINK_RATE =
1123 >        4L * 1000L * 1000L * 1000L; // 4 seconds
1124  
1125      /**
1126 <     * Top-level runloop for workers
1126 >     * The timeout value for attempted shrinkage, includes
1127 >     * some slop to cope with system timer imprecision.
1128       */
1129 <    final void runWorker(ForkJoinWorkerThread wt) {
1137 <        // Initialize queue array and seed in this thread
1138 <        WorkQueue w = wt.workQueue;
1139 <        w.growArray(false);
1140 <        // Same initial hash as Submitters
1141 <        w.seed = System.identityHashCode(Thread.currentThread()) | (1 << 31);
1129 >    private static final long SHRINK_TIMEOUT = SHRINK_RATE - (SHRINK_RATE / 10);
1130  
1131 <        do {} while (w.runTask(scan(w)));
1132 <    }
1131 >    /**
1132 >     * The maximum stolen->joining link depth allowed in method
1133 >     * tryHelpStealer.  Must be a power of two. This value also
1134 >     * controls the maximum number of times to try to help join a task
1135 >     * without any apparent progress or change in pool state before
1136 >     * giving up and blocking (see awaitJoin).  Depths for legitimate
1137 >     * chains are unbounded, but we use a fixed constant to avoid
1138 >     * (otherwise unchecked) cycles and to bound staleness of
1139 >     * traversal parameters at the expense of sometimes blocking when
1140 >     * we could be helping.
1141 >     */
1142 >    private static final int MAX_HELP = 64;
1143 >
1144 >    /**
1145 >     * Secondary time-based bound (in nanosecs) for helping attempts
1146 >     * before trying compensated blocking in awaitJoin. Used in
1147 >     * conjunction with MAX_HELP to reduce variance due to different
1148 >     * polling rates associated with different helping options. The
1149 >     * value should roughly approximate the time required to create
1150 >     * and/or activate a worker thread.
1151 >     */
1152 >    private static final long COMPENSATION_DELAY = 1L << 18; // ~0.25 millisec
1153  
1154 <    // Creating, registering and deregistering workers
1154 >    /**
1155 >     * Increment for seed generators. See class ThreadLocal for
1156 >     * explanation.
1157 >     */
1158 >    private static final int SEED_INCREMENT = 0x61c88647;
1159 >
1160 >    /**
1161 >     * Bits and masks for control variables
1162 >     *
1163 >     * Field ctl is a long packed with:
1164 >     * AC: Number of active running workers minus target parallelism (16 bits)
1165 >     * TC: Number of total workers minus target parallelism (16 bits)
1166 >     * ST: true if pool is terminating (1 bit)
1167 >     * EC: the wait count of top waiting thread (15 bits)
1168 >     * ID: poolIndex of top of Treiber stack of waiters (16 bits)
1169 >     *
1170 >     * When convenient, we can extract the upper 32 bits of counts and
1171 >     * the lower 32 bits of queue state, u = (int)(ctl >>> 32) and e =
1172 >     * (int)ctl.  The ec field is never accessed alone, but always
1173 >     * together with id and st. The offsets of counts by the target
1174 >     * parallelism and the positionings of fields makes it possible to
1175 >     * perform the most common checks via sign tests of fields: When
1176 >     * ac is negative, there are not enough active workers, when tc is
1177 >     * negative, there are not enough total workers, and when e is
1178 >     * negative, the pool is terminating.  To deal with these possibly
1179 >     * negative fields, we use casts in and out of "short" and/or
1180 >     * signed shifts to maintain signedness.
1181 >     *
1182 >     * When a thread is queued (inactivated), its eventCount field is
1183 >     * set negative, which is the only way to tell if a worker is
1184 >     * prevented from executing tasks, even though it must continue to
1185 >     * scan for them to avoid queuing races. Note however that
1186 >     * eventCount updates lag releases so usage requires care.
1187 >     *
1188 >     * Field runState is an int packed with:
1189 >     * SHUTDOWN: true if shutdown is enabled (1 bit)
1190 >     * SEQ:  a sequence number updated upon (de)registering workers (30 bits)
1191 >     * INIT: set true after workQueues array construction (1 bit)
1192 >     *
1193 >     * The sequence number enables simple consistency checks:
1194 >     * Staleness of read-only operations on the workQueues array can
1195 >     * be checked by comparing runState before vs after the reads.
1196 >     */
1197 >
1198 >    // bit positions/shifts for fields
1199 >    private static final int  AC_SHIFT   = 48;
1200 >    private static final int  TC_SHIFT   = 32;
1201 >    private static final int  ST_SHIFT   = 31;
1202 >    private static final int  EC_SHIFT   = 16;
1203 >
1204 >    // bounds
1205 >    private static final int  SMASK      = 0xffff;  // short bits
1206 >    private static final int  MAX_CAP    = 0x7fff;  // max #workers - 1
1207 >    private static final int  SQMASK     = 0xfffe;  // even short bits
1208 >    private static final int  SHORT_SIGN = 1 << 15;
1209 >    private static final int  INT_SIGN   = 1 << 31;
1210 >
1211 >    // masks
1212 >    private static final long STOP_BIT   = 0x0001L << ST_SHIFT;
1213 >    private static final long AC_MASK    = ((long)SMASK) << AC_SHIFT;
1214 >    private static final long TC_MASK    = ((long)SMASK) << TC_SHIFT;
1215 >
1216 >    // units for incrementing and decrementing
1217 >    private static final long TC_UNIT    = 1L << TC_SHIFT;
1218 >    private static final long AC_UNIT    = 1L << AC_SHIFT;
1219 >
1220 >    // masks and units for dealing with u = (int)(ctl >>> 32)
1221 >    private static final int  UAC_SHIFT  = AC_SHIFT - 32;
1222 >    private static final int  UTC_SHIFT  = TC_SHIFT - 32;
1223 >    private static final int  UAC_MASK   = SMASK << UAC_SHIFT;
1224 >    private static final int  UTC_MASK   = SMASK << UTC_SHIFT;
1225 >    private static final int  UAC_UNIT   = 1 << UAC_SHIFT;
1226 >    private static final int  UTC_UNIT   = 1 << UTC_SHIFT;
1227 >
1228 >    // masks and units for dealing with e = (int)ctl
1229 >    private static final int E_MASK      = 0x7fffffff; // no STOP_BIT
1230 >    private static final int E_SEQ       = 1 << EC_SHIFT;
1231 >
1232 >    // runState bits
1233 >    private static final int SHUTDOWN    = 1 << 31;
1234 >
1235 >    // access mode for WorkQueue
1236 >    static final int LIFO_QUEUE          =  0;
1237 >    static final int FIFO_QUEUE          =  1;
1238 >    static final int SHARED_QUEUE        = -1;
1239 >
1240 >    // Instance fields
1241 >
1242 >    /*
1243 >     * Field layout order in this class tends to matter more than one
1244 >     * would like. Runtime layout order is only loosely related to
1245 >     * declaration order and may differ across JVMs, but the following
1246 >     * empirically works OK on current JVMs.
1247 >     */
1248 >
1249 >    volatile long ctl;                         // main pool control
1250 >    final int parallelism;                     // parallelism level
1251 >    final int localMode;                       // per-worker scheduling mode
1252 >    final int submitMask;                      // submit queue index bound
1253 >    int nextSeed;                              // for initializing worker seeds
1254 >    volatile int runState;                     // shutdown status and seq
1255 >    WorkQueue[] workQueues;                    // main registry
1256 >    final Mutex lock;                          // for registration
1257 >    final Condition termination;               // for awaitTermination
1258 >    final ForkJoinWorkerThreadFactory factory; // factory for new workers
1259 >    final Thread.UncaughtExceptionHandler ueh; // per-worker UEH
1260 >    final AtomicLong stealCount;               // collect counts when terminated
1261 >    final AtomicInteger nextWorkerNumber;      // to create worker name string
1262 >    final String workerNamePrefix;             // to create worker name string
1263 >
1264 >    //  Creating, registering, and deregistering workers
1265  
1266      /**
1267       * Tries to create and start a worker
1268       */
1269      private void addWorker() {
1270          Throwable ex = null;
1271 <        ForkJoinWorkerThread w = null;
1271 >        ForkJoinWorkerThread wt = null;
1272          try {
1273 <            if ((w = factory.newThread(this)) != null) {
1274 <                w.start();
1273 >            if ((wt = factory.newThread(this)) != null) {
1274 >                wt.start();
1275                  return;
1276              }
1277          } catch (Throwable e) {
1278              ex = e;
1279          }
1280 <        deregisterWorker(w, ex);
1280 >        deregisterWorker(wt, ex); // adjust counts etc on failure
1281      }
1282  
1283      /**
# Line 1174 | Line 1292 | public class ForkJoinPool extends Abstra
1292      }
1293  
1294      /**
1295 <     * Callback from ForkJoinWorkerThread constructor to establish and
1296 <     * record its WorkQueue
1295 >     * Callback from ForkJoinWorkerThread constructor to establish its
1296 >     * poolIndex and record its WorkQueue. To avoid scanning bias due
1297 >     * to packing entries in front of the workQueues array, we treat
1298 >     * the array as a simple power-of-two hash table using per-thread
1299 >     * seed as hash, expanding as needed.
1300       *
1301 <     * @param wt the worker thread
1301 >     * @param w the worker's queue
1302       */
1303 <    final void registerWorker(ForkJoinWorkerThread wt) {
1304 <        WorkQueue w = wt.workQueue;
1305 <        ReentrantLock lock = this.lock;
1303 >
1304 >    final void registerWorker(WorkQueue w) {
1305 >        Mutex lock = this.lock;
1306          lock.lock();
1307          try {
1187            int k = nextPoolIndex;
1308              WorkQueue[] ws = workQueues;
1309 <            if (ws != null) {                       // ignore on shutdown
1310 <                int n = ws.length;
1311 <                if (k < 0 || (k & 1) == 0 || k >= n || ws[k] != null) {
1312 <                    for (k = 1; k < n && ws[k] != null; k += 2)
1313 <                        ;                           // workers are at odd indices
1314 <                    if (k >= n)                     // resize
1315 <                        workQueues = ws = Arrays.copyOf(ws, n << 1);
1316 <                }
1317 <                w.poolIndex = k;
1318 <                w.eventCount = ~(k >>> 1) & SMASK;  // Set up wait count
1319 <                ws[k] = w;                          // record worker
1320 <                nextPoolIndex = k + 2;
1321 <                int rs = runState;
1322 <                int m = rs & SMASK;                 // recalculate runState mask
1323 <                if (k > m)
1324 <                    m = (m << 1) + 1;
1325 <                runState = (rs & SHUTDOWN) | ((rs + RS_SEQ) & RS_SEQ_MASK) | m;
1309 >            if (w != null && ws != null) {          // skip on shutdown/failure
1310 >                int rs, n =  ws.length, m = n - 1;
1311 >                int s = nextSeed += SEED_INCREMENT; // rarely-colliding sequence
1312 >                w.seed = (s == 0) ? 1 : s;          // ensure non-zero seed
1313 >                int r = (s << 1) | 1;               // use odd-numbered indices
1314 >                if (ws[r &= m] != null) {           // collision
1315 >                    int probes = 0;                 // step by approx half size
1316 >                    int step = (n <= 4) ? 2 : ((n >>> 1) & SQMASK) + 2;
1317 >                    while (ws[r = (r + step) & m] != null) {
1318 >                        if (++probes >= n) {
1319 >                            workQueues = ws = Arrays.copyOf(ws, n <<= 1);
1320 >                            m = n - 1;
1321 >                            probes = 0;
1322 >                        }
1323 >                    }
1324 >                }
1325 >                w.eventCount = w.poolIndex = r;     // establish before recording
1326 >                ws[r] = w;                          // also update seq
1327 >                runState = ((rs = runState) & SHUTDOWN) | ((rs + 2) & ~SHUTDOWN);
1328              }
1329          } finally {
1330              lock.unlock();
# Line 1210 | Line 1332 | public class ForkJoinPool extends Abstra
1332      }
1333  
1334      /**
1335 <     * Final callback from terminating worker, as well as failure to
1336 <     * construct or start a worker in addWorker.  Removes record of
1335 >     * Final callback from terminating worker, as well as upon failure
1336 >     * to construct or start a worker in addWorker.  Removes record of
1337       * worker from array, and adjusts counts. If pool is shutting
1338       * down, tries to complete termination.
1339       *
# Line 1219 | Line 1341 | public class ForkJoinPool extends Abstra
1341       * @param ex the exception causing failure, or null if none
1342       */
1343      final void deregisterWorker(ForkJoinWorkerThread wt, Throwable ex) {
1344 +        Mutex lock = this.lock;
1345          WorkQueue w = null;
1346          if (wt != null && (w = wt.workQueue) != null) {
1347              w.runState = -1;                // ensure runState is set
1348              stealCount.getAndAdd(w.totalSteals + w.nsteals);
1349              int idx = w.poolIndex;
1227            ReentrantLock lock = this.lock;
1350              lock.lock();
1351              try {                           // remove record from array
1352                  WorkQueue[] ws = workQueues;
1353                  if (ws != null && idx >= 0 && idx < ws.length && ws[idx] == w)
1354 <                    ws[nextPoolIndex = idx] = null;
1354 >                    ws[idx] = null;
1355              } finally {
1356                  lock.unlock();
1357              }
# Line 1241 | Line 1363 | public class ForkJoinPool extends Abstra
1363                                             ((c - TC_UNIT) & TC_MASK) |
1364                                             (c & ~(AC_MASK|TC_MASK)))));
1365  
1366 <        if (!tryTerminate(false) && w != null) {
1366 >        if (!tryTerminate(false, false) && w != null) {
1367              w.cancelAll();                  // cancel remaining tasks
1368              if (w.array != null)            // suppress signal if never ran
1369                  signalWork();               // wake up or create replacement
1370 +            if (ex == null)                 // help clean refs on way out
1371 +                ForkJoinTask.helpExpungeStaleExceptions();
1372          }
1373  
1374          if (ex != null)                     // rethrow
1375              U.throwException(ex);
1376      }
1377  
1378 +
1379 +    // Submissions
1380 +
1381      /**
1382 <     * Tries to add and register a new queue at the given index.
1382 >     * Unless shutting down, adds the given task to a submission queue
1383 >     * at submitter's current queue index (modulo submission
1384 >     * range). If no queue exists at the index, one is created.  If
1385 >     * the queue is busy, another index is randomly chosen. The
1386 >     * submitMask bounds the effective number of queues to the
1387 >     * (nearest power of two for) parallelism level.
1388       *
1389 <     * @param idx the workQueues array index to register the queue
1390 <     * @return the queue, or null if could not add because could
1391 <     * not acquire lock or idx is unusable
1392 <     */
1393 <    private WorkQueue tryAddSharedQueue(int idx) {
1394 <        WorkQueue q = null;
1395 <        ReentrantLock lock = this.lock;
1396 <        if (idx >= 0 && (idx & 1) == 0 && !lock.isLocked()) {
1397 <            // create queue outside of lock but only if apparently free
1398 <            WorkQueue nq = new WorkQueue(null, SHARED_QUEUE);
1399 <            if (lock.tryLock()) {
1400 <                try {
1401 <                    WorkQueue[] ws = workQueues;
1402 <                    if (ws != null && idx < ws.length) {
1403 <                        if ((q = ws[idx]) == null) {
1404 <                            int rs;         // update runState seq
1405 <                            ws[idx] = q = nq;
1406 <                            runState = (((rs = runState) & SHUTDOWN) |
1275 <                                        ((rs + RS_SEQ) & ~SHUTDOWN));
1276 <                        }
1389 >     * @param task the task. Caller must ensure non-null.
1390 >     */
1391 >    private void doSubmit(ForkJoinTask<?> task) {
1392 >        Submitter s = submitters.get();
1393 >        for (int r = s.seed, m = submitMask;;) {
1394 >            WorkQueue[] ws; WorkQueue q;
1395 >            int k = r & m & SQMASK;          // use only even indices
1396 >            if (runState < 0 || (ws = workQueues) == null || ws.length <= k)
1397 >                throw new RejectedExecutionException(); // shutting down
1398 >            else if ((q = ws[k]) == null) {  // create new queue
1399 >                WorkQueue nq = new WorkQueue(this, null, SHARED_QUEUE);
1400 >                Mutex lock = this.lock;      // construct outside lock
1401 >                lock.lock();
1402 >                try {                        // recheck under lock
1403 >                    int rs = runState;       // to update seq
1404 >                    if (ws == workQueues && ws[k] == null) {
1405 >                        ws[k] = nq;
1406 >                        runState = ((rs & SHUTDOWN) | ((rs + 2) & ~SHUTDOWN));
1407                      }
1408                  } finally {
1409                      lock.unlock();
1410                  }
1411              }
1412 +            else if (q.trySharedPush(task)) {
1413 +                signalWork();
1414 +                return;
1415 +            }
1416 +            else if (m > 1) {                // move to a different index
1417 +                r ^= r << 13;                // same xorshift as WorkQueues
1418 +                r ^= r >>> 17;
1419 +                s.seed = r ^= r << 5;
1420 +            }
1421 +            else
1422 +                Thread.yield();              // yield if no alternatives
1423          }
1283        return q;
1424      }
1425  
1426      // Maintaining ctl counts
1427  
1428      /**
1429 <     * Increments active count; mainly called upon return from blocking
1429 >     * Increments active count; mainly called upon return from blocking.
1430       */
1431      final void incrementActiveCount() {
1432          long c;
# Line 1294 | Line 1434 | public class ForkJoinPool extends Abstra
1434      }
1435  
1436      /**
1437 <     * Activates or creates a worker
1437 >     * Tries to activate or create a worker if too few are active.
1438       */
1439      final void signalWork() {
1440 <        /*
1441 <         * The while condition is true if: (there is are too few total
1442 <         * workers OR there is at least one waiter) AND (there are too
1443 <         * few active workers OR the pool is terminating).  The value
1444 <         * of e distinguishes the remaining cases: zero (no waiters)
1445 <         * for create, negative if terminating (in which case do
1446 <         * nothing), else release a waiter. The secondary checks for
1447 <         * release (non-null array etc) can fail if the pool begins
1448 <         * terminating after the test, and don't impose any added cost
1449 <         * because JVMs must perform null and bounds checks anyway.
1450 <         */
1451 <        long c; int e, u;
1452 <        while ((((e = (int)(c = ctl)) | (u = (int)(c >>> 32))) &
1453 <                (INT_SIGN|SHORT_SIGN)) == (INT_SIGN|SHORT_SIGN)) {
1314 <            WorkQueue[] ws = workQueues; int i; WorkQueue w; Thread p;
1315 <            if (e == 0) {                    // add a new worker
1316 <                if (U.compareAndSwapLong
1317 <                    (this, CTL, c, (long)(((u + UTC_UNIT) & UTC_MASK) |
1318 <                                          ((u + UAC_UNIT) & UAC_MASK)) << 32)) {
1319 <                    addWorker();
1320 <                    break;
1440 >        long c; int u;
1441 >        while ((u = (int)((c = ctl) >>> 32)) < 0) {     // too few active
1442 >            WorkQueue[] ws = workQueues; int e, i; WorkQueue w; Thread p;
1443 >            if ((e = (int)c) > 0) {                     // at least one waiting
1444 >                if (ws != null && (i = e & SMASK) < ws.length &&
1445 >                    (w = ws[i]) != null && w.eventCount == (e | INT_SIGN)) {
1446 >                    long nc = (((long)(w.nextWait & E_MASK)) |
1447 >                               ((long)(u + UAC_UNIT) << 32));
1448 >                    if (U.compareAndSwapLong(this, CTL, c, nc)) {
1449 >                        w.eventCount = (e + E_SEQ) & E_MASK;
1450 >                        if ((p = w.parker) != null)
1451 >                            U.unpark(p);                // activate and release
1452 >                        break;
1453 >                    }
1454                  }
1455 <            }
1323 <            else if (e > 0 && ws != null &&
1324 <                     (i = ((~e << 1) | 1) & SMASK) < ws.length &&
1325 <                     (w = ws[i]) != null &&
1326 <                     w.eventCount == (e | INT_SIGN)) {
1327 <                if (U.compareAndSwapLong
1328 <                    (this, CTL, c, (((long)(w.nextWait & E_MASK)) |
1329 <                                    ((long)(u + UAC_UNIT) << 32)))) {
1330 <                    w.eventCount = (e + E_SEQ) & E_MASK;
1331 <                    if ((p = w.parker) != null)
1332 <                        U.unpark(p);         // release a waiting worker
1455 >                else
1456                      break;
1334                }
1457              }
1458 <            else
1459 <                break;
1460 <        }
1339 <    }
1340 <
1341 <    /**
1342 <     * Tries to decrement active count (sometimes implicitly) and
1343 <     * possibly release or create a compensating worker in preparation
1344 <     * for blocking. Fails on contention or termination.
1345 <     *
1346 <     * @return true if the caller can block, else should recheck and retry
1347 <     */
1348 <    final boolean tryCompensate() {
1349 <        WorkQueue[] ws; WorkQueue w; Thread p;
1350 <        int pc = parallelism, e, u, ac, tc, i;
1351 <        long c = ctl;
1352 <
1353 <        if ((e = (int)c) >= 0) {
1354 <            if ((ac = ((u = (int)(c >>> 32)) >> UAC_SHIFT)) <= 0 &&
1355 <                e != 0 && (ws = workQueues) != null &&
1356 <                (i = ((~e << 1) | 1) & SMASK) < ws.length &&
1357 <                (w = ws[i]) != null) {
1358 <                if (w.eventCount == (e | INT_SIGN) &&
1359 <                    U.compareAndSwapLong
1360 <                    (this, CTL, c, ((long)(w.nextWait & E_MASK) |
1361 <                                    (c & (AC_MASK|TC_MASK))))) {
1362 <                    w.eventCount = (e + E_SEQ) & E_MASK;
1363 <                    if ((p = w.parker) != null)
1364 <                        U.unpark(p);
1365 <                    return true;             // release an idle worker
1366 <                }
1367 <            }
1368 <            else if ((tc = (short)(u >>> UTC_SHIFT)) >= 0 && ac + pc > 1) {
1369 <                long nc = ((c - AC_UNIT) & AC_MASK) | (c & ~AC_MASK);
1370 <                if (U.compareAndSwapLong(this, CTL, c, nc))
1371 <                    return true;             // no compensation needed
1372 <            }
1373 <            else if (tc + pc < MAX_ID) {
1374 <                long nc = ((c + TC_UNIT) & TC_MASK) | (c & ~TC_MASK);
1458 >            else if (e == 0 && (u & SHORT_SIGN) != 0) { // too few total
1459 >                long nc = (long)(((u + UTC_UNIT) & UTC_MASK) |
1460 >                                 ((u + UAC_UNIT) & UAC_MASK)) << 32;
1461                  if (U.compareAndSwapLong(this, CTL, c, nc)) {
1462                      addWorker();
1463 <                    return true;             // create replacement
1463 >                    break;
1464                  }
1465              }
1466 +            else
1467 +                break;
1468          }
1381        return false;
1469      }
1470  
1471 <    // Submissions
1471 >    // Scanning for tasks
1472  
1473      /**
1474 <     * Unless shutting down, adds the given task to a submission queue
1388 <     * at submitter's current queue index. If no queue exists at the
1389 <     * index, one is created unless pool lock is busy.  If the queue
1390 <     * and/or lock are busy, another index is randomly chosen.
1474 >     * Top-level runloop for workers, called by ForkJoinWorkerThread.run.
1475       */
1476 <    private void doSubmit(ForkJoinTask<?> task) {
1477 <        if (task == null)
1478 <            throw new NullPointerException();
1395 <        Submitter s = submitters.get();
1396 <        for (int r = s.seed;;) {
1397 <            WorkQueue q; int k;
1398 <            int rs = runState, m = rs & SMASK;
1399 <            WorkQueue[] ws = workQueues;
1400 <            if (rs < 0 || ws == null)   // shutting down
1401 <                throw new RejectedExecutionException();
1402 <            if (ws.length > m &&        // k must be at index
1403 <                ((q = ws[k = (r << 1) & m]) != null ||
1404 <                 (q = tryAddSharedQueue(k)) != null) &&
1405 <                q.trySharedPush(task)) {
1406 <                signalWork();
1407 <                return;
1408 <            }
1409 <            r ^= r << 13;               // xorshift seed to new position
1410 <            r ^= r >>> 17;
1411 <            if (((s.seed = r ^= r << 5) & m) == 0)
1412 <                Thread.yield();         // occasionally yield if busy
1413 <        }
1476 >    final void runWorker(WorkQueue w) {
1477 >        w.growArray(false);         // initialize queue array in this thread
1478 >        do { w.runTask(scan(w)); } while (w.runState >= 0);
1479      }
1480  
1416
1417    // Scanning for tasks
1418
1481      /**
1482       * Scans for and, if found, returns one task, else possibly
1483       * inactivates the worker. This method operates on single reads of
1484 <     * volatile state and is designed to be re-invoked continuously in
1485 <     * part because it returns upon detecting inconsistencies,
1484 >     * volatile state and is designed to be re-invoked continuously,
1485 >     * in part because it returns upon detecting inconsistencies,
1486       * contention, or state changes that indicate possible success on
1487       * re-invocation.
1488       *
1489 <     * The scan searches for tasks across queues, randomly selecting
1490 <     * the first #queues probes, favoring steals 2:1 over submissions
1491 <     * (by exploiting even/odd indexing), and then performing a
1492 <     * circular sweep of all queues.  The scan terminates upon either
1493 <     * finding a non-empty queue, or completing a full sweep. If the
1494 <     * worker is not inactivated, it takes and returns a task from
1495 <     * this queue.  On failure to find a task, we take one of the
1496 <     * following actions, after which the caller will retry calling
1497 <     * this method unless terminated.
1489 >     * The scan searches for tasks across a random permutation of
1490 >     * queues (starting at a random index and stepping by a random
1491 >     * relative prime, checking each at least once).  The scan
1492 >     * terminates upon either finding a non-empty queue, or completing
1493 >     * the sweep. If the worker is not inactivated, it takes and
1494 >     * returns a task from this queue.  On failure to find a task, we
1495 >     * take one of the following actions, after which the caller will
1496 >     * retry calling this method unless terminated.
1497 >     *
1498 >     * * If pool is terminating, terminate the worker.
1499       *
1500       * * If not a complete sweep, try to release a waiting worker.  If
1501       * the scan terminated because the worker is inactivated, then the
# Line 1441 | Line 1504 | public class ForkJoinPool extends Abstra
1504       * another worker, but with same net effect. Releasing in other
1505       * cases as well ensures that we have enough workers running.
1506       *
1444     * * If the caller has run a task since the the last empty scan,
1445     * return (to allow rescan) if other workers are not also yet
1446     * enqueued.  Field WorkQueue.rescans counts down on each scan to
1447     * ensure eventual inactivation, and occasional calls to
1448     * Thread.yield to help avoid interference with more useful
1449     * activities on the system.
1450     *
1451     * * If pool is terminating, terminate the worker
1452     *
1507       * * If not already enqueued, try to inactivate and enqueue the
1508 <     * worker on wait queue.
1508 >     * worker on wait queue. Or, if inactivating has caused the pool
1509 >     * to be quiescent, relay to idleAwaitWork to check for
1510 >     * termination and possibly shrink pool.
1511 >     *
1512 >     * * If already inactive, and the caller has run a task since the
1513 >     * last empty scan, return (to allow rescan) unless others are
1514 >     * also inactivated.  Field WorkQueue.rescans counts down on each
1515 >     * scan to ensure eventual inactivation and blocking.
1516       *
1517 <     * * If already enqueued and none of the above apply, either park
1518 <     * awaiting signal, or if this is the most recent waiter and pool
1458 <     * is quiescent, relay to idleAwaitWork to check for termination
1459 <     * and possibly shrink pool.
1517 >     * * If already enqueued and none of the above apply, park
1518 >     * awaiting signal,
1519       *
1520       * @param w the worker (via its WorkQueue)
1521       * @return a task or null of none found
1522       */
1523      private final ForkJoinTask<?> scan(WorkQueue w) {
1524 <        boolean swept = false;                 // true after full empty scan
1525 <        WorkQueue[] ws;                        // volatile read order matters
1526 <        int r = w.seed, ec = w.eventCount;     // ec is negative if inactive
1527 <        int rs = runState, m = rs & SMASK;
1528 <        if ((ws = workQueues) != null && ws.length > m) {
1529 <            ForkJoinTask<?> task = null;
1530 <            for (int k = 0, j = -2 - m; ; ++j) {
1531 <                WorkQueue q; int b;
1532 <                if (j < 0) {                    // random probes while j negative
1533 <                    r ^= r << 13; r ^= r >>> 17; k = (r ^= r << 5) | (j & 1);
1534 <                }                               // worker (not submit) for odd j
1535 <                else                            // cyclic scan when j >= 0
1536 <                    k += (m >>> 1) | 1;         // step by half to reduce bias
1537 <
1538 <                if ((q = ws[k & m]) != null && (b = q.base) - q.top < 0) {
1539 <                    if (ec >= 0)
1540 <                        task = q.pollAt(b);     // steal
1541 <                    break;
1524 >        WorkQueue[] ws;                       // first update random seed
1525 >        int r = w.seed; r ^= r << 13; r ^= r >>> 17; w.seed = r ^= r << 5;
1526 >        int rs = runState, m;                 // volatile read order matters
1527 >        if ((ws = workQueues) != null && (m = ws.length - 1) > 0) {
1528 >            int ec = w.eventCount;            // ec is negative if inactive
1529 >            int step = (r >>> 16) | 1;        // relative prime
1530 >            for (int j = (m + 1) << 2; ; r += step) {
1531 >                WorkQueue q; ForkJoinTask<?> t; ForkJoinTask<?>[] a; int b;
1532 >                if ((q = ws[r & m]) != null && (b = q.base) - q.top < 0 &&
1533 >                    (a = q.array) != null) {  // probably nonempty
1534 >                    int i = (((a.length - 1) & b) << ASHIFT) + ABASE;
1535 >                    t = (ForkJoinTask<?>)U.getObjectVolatile(a, i);
1536 >                    if (q.base == b && ec >= 0 && t != null &&
1537 >                        U.compareAndSwapObject(a, i, t, null)) {
1538 >                        q.base = b + 1;       // specialization of pollAt
1539 >                        return t;
1540 >                    }
1541 >                    else if (ec < 0 || j <= m) {
1542 >                        rs = 0;               // mark scan as imcomplete
1543 >                        break;                // caller can retry after release
1544 >                    }
1545                  }
1546 <                else if (j > m) {
1485 <                    if (rs == runState)        // staleness check
1486 <                        swept = true;
1546 >                if (--j < 0)
1547                      break;
1548 +            }
1549 +
1550 +            long c = ctl; int e = (int)c, a = (int)(c >> AC_SHIFT), nr, ns;
1551 +            if (e < 0)                        // decode ctl on empty scan
1552 +                w.runState = -1;              // pool is terminating
1553 +            else if (rs == 0 || rs != runState) { // incomplete scan
1554 +                WorkQueue v; Thread p;        // try to release a waiter
1555 +                if (e > 0 && a < 0 && w.eventCount == ec &&
1556 +                    (v = ws[e & m]) != null && v.eventCount == (e | INT_SIGN)) {
1557 +                    long nc = ((long)(v.nextWait & E_MASK) |
1558 +                               ((c + AC_UNIT) & (AC_MASK|TC_MASK)));
1559 +                    if (ctl == c && U.compareAndSwapLong(this, CTL, c, nc)) {
1560 +                        v.eventCount = (e + E_SEQ) & E_MASK;
1561 +                        if ((p = v.parker) != null)
1562 +                            U.unpark(p);
1563 +                    }
1564                  }
1565              }
1566 <            w.seed = r;                        // save seed for next scan
1567 <            if (task != null)
1568 <                return task;
1569 <        }
1570 <
1571 <        // Decode ctl on empty scan
1572 <        long c = ctl; int e = (int)c, a = (int)(c >> AC_SHIFT), nr, ns;
1573 <        if (!swept) {                          // try to release a waiter
1574 <            WorkQueue v; Thread p;
1575 <            if (e > 0 && a < 0 && ws != null &&
1576 <                (v = ws[((~e << 1) | 1) & m]) != null &&
1577 <                v.eventCount == (e | INT_SIGN) && U.compareAndSwapLong
1578 <                (this, CTL, c, ((long)(v.nextWait & E_MASK) |
1579 <                                ((c + AC_UNIT) & (AC_MASK|TC_MASK))))) {
1580 <                v.eventCount = (e + E_SEQ) & E_MASK;
1581 <                if ((p = v.parker) != null)
1582 <                    U.unpark(p);
1583 <            }
1584 <        }
1585 <        else if ((nr = w.rescans) > 0) {       // continue rescanning
1586 <            int ac = a + parallelism;
1587 <            if ((w.rescans = (ac < nr) ? ac : nr - 1) > 0 && w.seed < 0 &&
1588 <                w.eventCount == ec)
1589 <                Thread.yield();                // 1 bit randomness for yield call
1590 <        }
1591 <        else if (e < 0)                        // pool is terminating
1592 <            w.runState = -1;
1593 <        else if (ec >= 0) {                    // try to enqueue
1594 <            long nc = (long)ec | ((c - AC_UNIT) & (AC_MASK|TC_MASK));
1595 <            w.nextWait = e;
1596 <            w.eventCount = ec | INT_SIGN;      // mark as inactive
1597 <            if (!U.compareAndSwapLong(this, CTL, c, nc))
1522 <                w.eventCount = ec;             // back out on CAS failure
1523 <            else if ((ns = w.nsteals) != 0) {  // set rescans if ran task
1524 <                if (a <= 0)                    // ... unless too many active
1525 <                    w.rescans = a + parallelism;
1526 <                w.nsteals = 0;
1527 <                w.totalSteals += ns;
1528 <            }
1529 <        }
1530 <        else{                                  // already queued
1531 <            if (parallelism == -a)
1532 <                idleAwaitWork(w);              // quiescent
1533 <            if (w.eventCount == ec) {
1534 <                Thread.interrupted();          // clear status
1535 <                ForkJoinWorkerThread wt = w.owner;
1536 <                U.putObject(wt, PARKBLOCKER, this);
1537 <                w.parker = wt;                 // emulate LockSupport.park
1538 <                if (w.eventCount == ec)        // recheck
1539 <                    U.park(false, 0L);         // block
1540 <                w.parker = null;
1541 <                U.putObject(wt, PARKBLOCKER, null);
1566 >            else if (ec >= 0) {               // try to enqueue/inactivate
1567 >                long nc = (long)ec | ((c - AC_UNIT) & (AC_MASK|TC_MASK));
1568 >                w.nextWait = e;
1569 >                w.eventCount = ec | INT_SIGN; // mark as inactive
1570 >                if (ctl != c || !U.compareAndSwapLong(this, CTL, c, nc))
1571 >                    w.eventCount = ec;        // unmark on CAS failure
1572 >                else {
1573 >                    if ((ns = w.nsteals) != 0) {
1574 >                        w.nsteals = 0;        // set rescans if ran task
1575 >                        w.rescans = (a > 0) ? 0 : a + parallelism;
1576 >                        w.totalSteals += ns;
1577 >                    }
1578 >                    if (a == 1 - parallelism) // quiescent
1579 >                        idleAwaitWork(w, nc, c);
1580 >                }
1581 >            }
1582 >            else if (w.eventCount < 0) {      // already queued
1583 >                if ((nr = w.rescans) > 0) {   // continue rescanning
1584 >                    int ac = a + parallelism;
1585 >                    if (((w.rescans = (ac < nr) ? ac : nr - 1) & 3) == 0)
1586 >                        Thread.yield();       // yield before block
1587 >                }
1588 >                else {
1589 >                    Thread.interrupted();     // clear status
1590 >                    Thread wt = Thread.currentThread();
1591 >                    U.putObject(wt, PARKBLOCKER, this);
1592 >                    w.parker = wt;            // emulate LockSupport.park
1593 >                    if (w.eventCount < 0)     // recheck
1594 >                        U.park(false, 0L);
1595 >                    w.parker = null;
1596 >                    U.putObject(wt, PARKBLOCKER, null);
1597 >                }
1598              }
1599          }
1600          return null;
1601      }
1602  
1603      /**
1604 <     * If inactivating worker w has caused pool to become quiescent,
1605 <     * check for pool termination, and, so long as this is not the
1606 <     * only worker, wait for event for up to SHRINK_RATE nanosecs On
1607 <     * timeout, if ctl has not changed, terminate the worker, which
1608 <     * will in turn wake up another worker to possibly repeat this
1609 <     * process.
1604 >     * If inactivating worker w has caused the pool to become
1605 >     * quiescent, checks for pool termination, and, so long as this is
1606 >     * not the only worker, waits for event for up to SHRINK_RATE
1607 >     * nanosecs.  On timeout, if ctl has not changed, terminates the
1608 >     * worker, which will in turn wake up another worker to possibly
1609 >     * repeat this process.
1610       *
1611       * @param w the calling worker
1612 +     * @param currentCtl the ctl value triggering possible quiescence
1613 +     * @param prevCtl the ctl value to restore if thread is terminated
1614       */
1615 <    private void idleAwaitWork(WorkQueue w) {
1616 <        long c; int nw, ec;
1617 <        if (!tryTerminate(false) &&
1618 <            (int)((c = ctl) >> AC_SHIFT) + parallelism == 0 &&
1619 <            (ec = w.eventCount) == ((int)c | INT_SIGN) &&
1620 <            (nw = w.nextWait) != 0) {
1563 <            long nc = ((long)(nw & E_MASK) | // ctl to restore on timeout
1564 <                       ((c + AC_UNIT) & AC_MASK) | (c & TC_MASK));
1565 <            ForkJoinTask.helpExpungeStaleExceptions(); // help clean
1566 <            ForkJoinWorkerThread wt = w.owner;
1567 <            while (ctl == c) {
1615 >    private void idleAwaitWork(WorkQueue w, long currentCtl, long prevCtl) {
1616 >        if (w.eventCount < 0 && !tryTerminate(false, false) &&
1617 >            (int)prevCtl != 0 && !hasQueuedSubmissions() && ctl == currentCtl) {
1618 >            Thread wt = Thread.currentThread();
1619 >            Thread.yield();            // yield before block
1620 >            while (ctl == currentCtl) {
1621                  long startTime = System.nanoTime();
1622                  Thread.interrupted();  // timed variant of version in scan()
1623                  U.putObject(wt, PARKBLOCKER, this);
1624                  w.parker = wt;
1625 <                if (ctl == c)
1625 >                if (ctl == currentCtl)
1626                      U.park(false, SHRINK_RATE);
1627                  w.parker = null;
1628                  U.putObject(wt, PARKBLOCKER, null);
1629 <                if (ctl != c)
1629 >                if (ctl != currentCtl)
1630                      break;
1631                  if (System.nanoTime() - startTime >= SHRINK_TIMEOUT &&
1632 <                    U.compareAndSwapLong(this, CTL, c, nc)) {
1633 <                    w.runState = -1;          // shrink
1634 <                    w.eventCount = (ec + E_SEQ) | E_MASK;
1632 >                    U.compareAndSwapLong(this, CTL, currentCtl, prevCtl)) {
1633 >                    w.eventCount = (w.eventCount + E_SEQ) | E_MASK;
1634 >                    w.runState = -1;   // shrink
1635                      break;
1636                  }
1637              }
# Line 1596 | Line 1649 | public class ForkJoinPool extends Abstra
1649       * leaves hints in workers to speed up subsequent calls. The
1650       * implementation is very branchy to cope with potential
1651       * inconsistencies or loops encountering chains that are stale,
1652 <     * unknown, or of length greater than MAX_HELP_DEPTH links.  All
1600 <     * of these cases are dealt with by just retrying by caller.
1652 >     * unknown, or so long that they are likely cyclic.
1653       *
1654       * @param joiner the joining worker
1655       * @param task the task to join
1656 <     * @return true if found or ran a task (and so is immediately retryable)
1656 >     * @return 0 if no progress can be made, negative if task
1657 >     * known complete, else positive
1658       */
1659 <    final boolean tryHelpStealer(WorkQueue joiner, ForkJoinTask<?> task) {
1660 <        ForkJoinTask<?> subtask;    // current target
1661 <        boolean progress = false;
1662 <        int depth = 0;              // current chain depth
1663 <        int m = runState & SMASK;
1664 <        WorkQueue[] ws = workQueues;
1665 <
1666 <        if (ws != null && ws.length > m && (subtask = task).status >= 0) {
1667 <            outer:for (WorkQueue j = joiner;;) {
1668 <                // Try to find the stealer of subtask, by first using hint
1616 <                WorkQueue stealer = null;
1617 <                WorkQueue v = ws[j.stealHint & m];
1618 <                if (v != null && v.currentSteal == subtask)
1619 <                    stealer = v;
1620 <                else {
1621 <                    for (int i = 1; i <= m; i += 2) {
1622 <                        if ((v = ws[i]) != null && v.currentSteal == subtask) {
1623 <                            stealer = v;
1624 <                            j.stealHint = i; // save hint
1625 <                            break;
1626 <                        }
1659 >    private int tryHelpStealer(WorkQueue joiner, ForkJoinTask<?> task) {
1660 >        int stat = 0, steps = 0;                    // bound to avoid cycles
1661 >        if (joiner != null && task != null) {       // hoist null checks
1662 >            restart: for (;;) {
1663 >                ForkJoinTask<?> subtask = task;     // current target
1664 >                for (WorkQueue j = joiner, v;;) {   // v is stealer of subtask
1665 >                    WorkQueue[] ws; int m, s, h;
1666 >                    if ((s = task.status) < 0) {
1667 >                        stat = s;
1668 >                        break restart;
1669                      }
1670 <                    if (stealer == null)
1671 <                        break;
1672 <                }
1673 <
1674 <                for (WorkQueue q = stealer;;) { // Try to help stealer
1675 <                    ForkJoinTask<?> t; int b;
1676 <                    if (task.status < 0)
1677 <                        break outer;
1678 <                    if ((b = q.base) - q.top < 0) {
1679 <                        progress = true;
1680 <                        if (subtask.status < 0)
1681 <                            break outer;               // stale
1682 <                        if ((t = q.pollAt(b)) != null) {
1683 <                            stealer.stealHint = joiner.poolIndex;
1684 <                            joiner.runSubtask(t);
1670 >                    if ((ws = workQueues) == null || (m = ws.length - 1) <= 0)
1671 >                        break restart;              // shutting down
1672 >                    if ((v = ws[h = (j.stealHint | 1) & m]) == null ||
1673 >                        v.currentSteal != subtask) {
1674 >                        for (int origin = h;;) {    // find stealer
1675 >                            if (((h = (h + 2) & m) & 15) == 1 &&
1676 >                                (subtask.status < 0 || j.currentJoin != subtask))
1677 >                                continue restart;   // occasional staleness check
1678 >                            if ((v = ws[h]) != null &&
1679 >                                v.currentSteal == subtask) {
1680 >                                j.stealHint = h;    // save hint
1681 >                                break;
1682 >                            }
1683 >                            if (h == origin)
1684 >                                break restart;      // cannot find stealer
1685                          }
1686                      }
1687 <                    else { // empty - try to descend to find stealer's stealer
1688 <                        ForkJoinTask<?> next = stealer.currentJoin;
1689 <                        if (++depth == MAX_HELP_DEPTH || subtask.status < 0 ||
1690 <                            next == null || next == subtask)
1691 <                            break outer;  // max depth, stale, dead-end, cyclic
1692 <                        subtask = next;
1693 <                        j = stealer;
1694 <                        break;
1687 >                    for (;;) { // help stealer or descend to its stealer
1688 >                        ForkJoinTask[] a;  int b;
1689 >                        if (subtask.status < 0)     // surround probes with
1690 >                            continue restart;       //   consistency checks
1691 >                        if ((b = v.base) - v.top < 0 && (a = v.array) != null) {
1692 >                            int i = (((a.length - 1) & b) << ASHIFT) + ABASE;
1693 >                            ForkJoinTask<?> t =
1694 >                                (ForkJoinTask<?>)U.getObjectVolatile(a, i);
1695 >                            if (subtask.status < 0 || j.currentJoin != subtask ||
1696 >                                v.currentSteal != subtask)
1697 >                                continue restart;   // stale
1698 >                            stat = 1;               // apparent progress
1699 >                            if (t != null && v.base == b &&
1700 >                                U.compareAndSwapObject(a, i, t, null)) {
1701 >                                v.base = b + 1;     // help stealer
1702 >                                joiner.runSubtask(t);
1703 >                            }
1704 >                            else if (v.base == b && ++steps == MAX_HELP)
1705 >                                break restart;      // v apparently stalled
1706 >                        }
1707 >                        else {                      // empty -- try to descend
1708 >                            ForkJoinTask<?> next = v.currentJoin;
1709 >                            if (subtask.status < 0 || j.currentJoin != subtask ||
1710 >                                v.currentSteal != subtask)
1711 >                                continue restart;   // stale
1712 >                            else if (next == null || ++steps == MAX_HELP)
1713 >                                break restart;      // dead-end or maybe cyclic
1714 >                            else {
1715 >                                subtask = next;
1716 >                                j = v;
1717 >                                break;
1718 >                            }
1719 >                        }
1720                      }
1721                  }
1722              }
1723          }
1724 <        return progress;
1724 >        return stat;
1725      }
1726  
1727      /**
# Line 1663 | Line 1730 | public class ForkJoinPool extends Abstra
1730       * @param joiner the joining worker
1731       * @param task the task
1732       */
1733 <    final void tryPollForAndExec(WorkQueue joiner, ForkJoinTask<?> task) {
1733 >    private void tryPollForAndExec(WorkQueue joiner, ForkJoinTask<?> task) {
1734          WorkQueue[] ws;
1735 <        int m = runState & SMASK;
1736 <        if ((ws = workQueues) != null && ws.length > m) {
1670 <            for (int j = 1; j <= m && task.status >= 0; j += 2) {
1735 >        if ((ws = workQueues) != null) {
1736 >            for (int j = 1; j < ws.length && task.status >= 0; j += 2) {
1737                  WorkQueue q = ws[j];
1738                  if (q != null && q.pollFor(task)) {
1739                      joiner.runSubtask(task);
# Line 1678 | Line 1744 | public class ForkJoinPool extends Abstra
1744      }
1745  
1746      /**
1747 <     * Returns a non-empty steal queue, if one is found during a random,
1748 <     * then cyclic scan, else null.  This method must be retried by
1749 <     * caller if, by the time it tries to use the queue, it is empty.
1747 >     * Tries to decrement active count (sometimes implicitly) and
1748 >     * possibly release or create a compensating worker in preparation
1749 >     * for blocking. Fails on contention or termination. Otherwise,
1750 >     * adds a new thread if no idle workers are available and either
1751 >     * pool would become completely starved or: (at least half
1752 >     * starved, and fewer than 50% spares exist, and there is at least
1753 >     * one task apparently available). Even though the availability
1754 >     * check requires a full scan, it is worthwhile in reducing false
1755 >     * alarms.
1756 >     *
1757 >     * @param task if non-null, a task being waited for
1758 >     * @param blocker if non-null, a blocker being waited for
1759 >     * @return true if the caller can block, else should recheck and retry
1760 >     */
1761 >    final boolean tryCompensate(ForkJoinTask<?> task, ManagedBlocker blocker) {
1762 >        int pc = parallelism, e;
1763 >        long c = ctl;
1764 >        WorkQueue[] ws = workQueues;
1765 >        if ((e = (int)c) >= 0 && ws != null) {
1766 >            int u, a, ac, hc;
1767 >            int tc = (short)((u = (int)(c >>> 32)) >>> UTC_SHIFT) + pc;
1768 >            boolean replace = false;
1769 >            if ((a = u >> UAC_SHIFT) <= 0) {
1770 >                if ((ac = a + pc) <= 1)
1771 >                    replace = true;
1772 >                else if ((e > 0 || (task != null &&
1773 >                                    ac <= (hc = pc >>> 1) && tc < pc + hc))) {
1774 >                    WorkQueue w;
1775 >                    for (int j = 0; j < ws.length; ++j) {
1776 >                        if ((w = ws[j]) != null && !w.isEmpty()) {
1777 >                            replace = true;
1778 >                            break;   // in compensation range and tasks available
1779 >                        }
1780 >                    }
1781 >                }
1782 >            }
1783 >            if ((task == null || task.status >= 0) && // recheck need to block
1784 >                (blocker == null || !blocker.isReleasable()) && ctl == c) {
1785 >                if (!replace) {          // no compensation
1786 >                    long nc = ((c - AC_UNIT) & AC_MASK) | (c & ~AC_MASK);
1787 >                    if (U.compareAndSwapLong(this, CTL, c, nc))
1788 >                        return true;
1789 >                }
1790 >                else if (e != 0) {       // release an idle worker
1791 >                    WorkQueue w; Thread p; int i;
1792 >                    if ((i = e & SMASK) < ws.length && (w = ws[i]) != null) {
1793 >                        long nc = ((long)(w.nextWait & E_MASK) |
1794 >                                   (c & (AC_MASK|TC_MASK)));
1795 >                        if (w.eventCount == (e | INT_SIGN) &&
1796 >                            U.compareAndSwapLong(this, CTL, c, nc)) {
1797 >                            w.eventCount = (e + E_SEQ) & E_MASK;
1798 >                            if ((p = w.parker) != null)
1799 >                                U.unpark(p);
1800 >                            return true;
1801 >                        }
1802 >                    }
1803 >                }
1804 >                else if (tc < MAX_CAP) { // create replacement
1805 >                    long nc = ((c + TC_UNIT) & TC_MASK) | (c & ~TC_MASK);
1806 >                    if (U.compareAndSwapLong(this, CTL, c, nc)) {
1807 >                        addWorker();
1808 >                        return true;
1809 >                    }
1810 >                }
1811 >            }
1812 >        }
1813 >        return false;
1814 >    }
1815 >
1816 >    /**
1817 >     * Helps and/or blocks until the given task is done.
1818 >     *
1819 >     * @param joiner the joining worker
1820 >     * @param task the task
1821 >     * @return task status on exit
1822 >     */
1823 >    final int awaitJoin(WorkQueue joiner, ForkJoinTask<?> task) {
1824 >        int s;
1825 >        if ((s = task.status) >= 0) {
1826 >            ForkJoinTask<?> prevJoin = joiner.currentJoin;
1827 >            joiner.currentJoin = task;
1828 >            long startTime = 0L;
1829 >            for (int k = 0;;) {
1830 >                if ((s = (joiner.isEmpty() ?           // try to help
1831 >                          tryHelpStealer(joiner, task) :
1832 >                          joiner.tryRemoveAndExec(task))) == 0 &&
1833 >                    (s = task.status) >= 0) {
1834 >                    if (k == 0) {
1835 >                        startTime = System.nanoTime();
1836 >                        tryPollForAndExec(joiner, task); // check uncommon case
1837 >                    }
1838 >                    else if ((k & (MAX_HELP - 1)) == 0 &&
1839 >                             System.nanoTime() - startTime >=
1840 >                             COMPENSATION_DELAY &&
1841 >                             tryCompensate(task, null)) {
1842 >                        if (task.trySetSignal()) {
1843 >                            synchronized (task) {
1844 >                                if (task.status >= 0) {
1845 >                                    try {                // see ForkJoinTask
1846 >                                        task.wait();     //  for explanation
1847 >                                    } catch (InterruptedException ie) {
1848 >                                    }
1849 >                                }
1850 >                                else
1851 >                                    task.notifyAll();
1852 >                            }
1853 >                        }
1854 >                        long c;                          // re-activate
1855 >                        do {} while (!U.compareAndSwapLong
1856 >                                     (this, CTL, c = ctl, c + AC_UNIT));
1857 >                    }
1858 >                }
1859 >                if (s < 0 || (s = task.status) < 0) {
1860 >                    joiner.currentJoin = prevJoin;
1861 >                    break;
1862 >                }
1863 >                else if ((k++ & (MAX_HELP - 1)) == MAX_HELP >>> 1)
1864 >                    Thread.yield();                     // for politeness
1865 >            }
1866 >        }
1867 >        return s;
1868 >    }
1869 >
1870 >    /**
1871 >     * Stripped-down variant of awaitJoin used by timed joins. Tries
1872 >     * to help join only while there is continuous progress. (Caller
1873 >     * will then enter a timed wait.)
1874 >     *
1875 >     * @param joiner the joining worker
1876 >     * @param task the task
1877 >     * @return task status on exit
1878 >     */
1879 >    final int helpJoinOnce(WorkQueue joiner, ForkJoinTask<?> task) {
1880 >        int s;
1881 >        while ((s = task.status) >= 0 &&
1882 >               (joiner.isEmpty() ?
1883 >                tryHelpStealer(joiner, task) :
1884 >                joiner.tryRemoveAndExec(task)) != 0)
1885 >            ;
1886 >        return s;
1887 >    }
1888 >
1889 >    /**
1890 >     * Returns a (probably) non-empty steal queue, if one is found
1891 >     * during a random, then cyclic scan, else null.  This method must
1892 >     * be retried by caller if, by the time it tries to use the queue,
1893 >     * it is empty.
1894       */
1895      private WorkQueue findNonEmptyStealQueue(WorkQueue w) {
1896 <        int r = w.seed;    // Same idea as scan(), but ignoring submissions
1896 >        // Similar to loop in scan(), but ignoring submissions
1897 >        int r = w.seed; r ^= r << 13; r ^= r >>> 17; w.seed = r ^= r << 5;
1898 >        int step = (r >>> 16) | 1;
1899          for (WorkQueue[] ws;;) {
1900 <            int m = runState & SMASK;
1901 <            if ((ws = workQueues) == null)
1900 >            int rs = runState, m;
1901 >            if ((ws = workQueues) == null || (m = ws.length - 1) < 1)
1902                  return null;
1903 <            if (ws.length > m) {
1904 <                WorkQueue q;
1905 <                for (int n = m << 2, k = r, j = -n;;) {
1906 <                    r ^= r << 13; r ^= r >>> 17; r ^= r << 5;
1907 <                    if ((q = ws[(k | 1) & m]) != null && q.base - q.top < 0) {
1908 <                        w.seed = r;
1697 <                        return q;
1698 <                    }
1699 <                    else if (j > n)
1903 >            for (int j = (m + 1) << 2; ; r += step) {
1904 >                WorkQueue q = ws[((r << 1) | 1) & m];
1905 >                if (q != null && !q.isEmpty())
1906 >                    return q;
1907 >                else if (--j < 0) {
1908 >                    if (runState == rs)
1909                          return null;
1910 <                    else
1702 <                        k = (j++ < 0) ? r : k + ((m >>> 1) | 1);
1703 <
1910 >                    break;
1911                  }
1912              }
1913          }
1914      }
1915  
1916 +
1917      /**
1918       * Runs tasks until {@code isQuiescent()}. We piggyback on
1919       * active count ctl maintenance, but rather than blocking
# Line 1714 | Line 1922 | public class ForkJoinPool extends Abstra
1922       */
1923      final void helpQuiescePool(WorkQueue w) {
1924          for (boolean active = true;;) {
1925 <            w.runLocalTasks();      // exhaust local queue
1925 >            ForkJoinTask<?> localTask; // exhaust local queue
1926 >            while ((localTask = w.nextLocalTask()) != null)
1927 >                localTask.doExec();
1928              WorkQueue q = findNonEmptyStealQueue(w);
1929              if (q != null) {
1930 <                ForkJoinTask<?> t;
1930 >                ForkJoinTask<?> t; int b;
1931                  if (!active) {      // re-establish active count
1932                      long c;
1933                      active = true;
1934                      do {} while (!U.compareAndSwapLong
1935                                   (this, CTL, c = ctl, c + AC_UNIT));
1936                  }
1937 <                if ((t = q.poll()) != null)
1937 >                if ((b = q.base) - q.top < 0 && (t = q.pollAt(b)) != null)
1938                      w.runSubtask(t);
1939              }
1940              else {
# Line 1746 | Line 1956 | public class ForkJoinPool extends Abstra
1956      }
1957  
1958      /**
1959 <     * Gets and removes a local or stolen task for the given worker
1959 >     * Gets and removes a local or stolen task for the given worker.
1960       *
1961       * @return a task, if available
1962       */
1963      final ForkJoinTask<?> nextTaskFor(WorkQueue w) {
1964          for (ForkJoinTask<?> t;;) {
1965 <            WorkQueue q;
1965 >            WorkQueue q; int b;
1966              if ((t = w.nextLocalTask()) != null)
1967                  return t;
1968              if ((q = findNonEmptyStealQueue(w)) == null)
1969                  return null;
1970 <            if ((t = q.poll()) != null)
1970 >            if ((b = q.base) - q.top < 0 && (t = q.pollAt(b)) != null)
1971                  return t;
1972          }
1973      }
# Line 1778 | Line 1988 | public class ForkJoinPool extends Abstra
1988                  8);
1989      }
1990  
1991 <    // Termination
1991 >    //  Termination
1992  
1993      /**
1994 <     * Sets SHUTDOWN bit of runState under lock
1995 <     */
1996 <    private void enableShutdown() {
1997 <        ReentrantLock lock = this.lock;
1998 <        if (runState >= 0) {
1999 <            lock.lock();                       // don't need try/finally
2000 <            runState |= SHUTDOWN;
1791 <            lock.unlock();
1792 <        }
1793 <    }
1794 <
1795 <    /**
1796 <     * Possibly initiates and/or completes termination.  Upon
1797 <     * termination, cancels all queued tasks and then
1994 >     * Possibly initiates and/or completes termination.  The caller
1995 >     * triggering termination runs three passes through workQueues:
1996 >     * (0) Setting termination status, followed by wakeups of queued
1997 >     * workers; (1) cancelling all tasks; (2) interrupting lagging
1998 >     * threads (likely in external tasks, but possibly also blocked in
1999 >     * joins).  Each pass repeats previous steps because of potential
2000 >     * lagging thread creation.
2001       *
2002       * @param now if true, unconditionally terminate, else only
2003       * if no work and no active workers
2004 +     * @param enable if true, enable shutdown when next possible
2005       * @return true if now terminating or terminated
2006       */
2007 <    private boolean tryTerminate(boolean now) {
2007 >    private boolean tryTerminate(boolean now, boolean enable) {
2008 >        Mutex lock = this.lock;
2009          for (long c;;) {
2010              if (((c = ctl) & STOP_BIT) != 0) {      // already terminating
2011                  if ((short)(c >>> TC_SHIFT) == -parallelism) {
1807                    ReentrantLock lock = this.lock; // signal when no workers
2012                      lock.lock();                    // don't need try/finally
2013                      termination.signalAll();        // signal when 0 workers
2014                      lock.unlock();
2015                  }
2016                  return true;
2017              }
2018 <            if (!now) {
2019 <                if ((int)(c >> AC_SHIFT) != -parallelism || runState >= 0 ||
2018 >            if (runState >= 0) {                    // not yet enabled
2019 >                if (!enable)
2020 >                    return false;
2021 >                lock.lock();
2022 >                runState |= SHUTDOWN;
2023 >                lock.unlock();
2024 >            }
2025 >            if (!now) {                             // check if idle & no tasks
2026 >                if ((int)(c >> AC_SHIFT) != -parallelism ||
2027                      hasQueuedSubmissions())
2028                      return false;
2029                  // Check for unqueued inactive workers. One pass suffices.
2030                  WorkQueue[] ws = workQueues; WorkQueue w;
2031                  if (ws != null) {
2032 <                    int n = ws.length;
1822 <                    for (int i = 1; i < n; i += 2) {
2032 >                    for (int i = 1; i < ws.length; i += 2) {
2033                          if ((w = ws[i]) != null && w.eventCount >= 0)
2034                              return false;
2035                      }
2036                  }
2037              }
2038 <            if (U.compareAndSwapLong(this, CTL, c, c | STOP_BIT))
2039 <                startTerminating();
2040 <        }
2041 <    }
2042 <
2043 <    /**
2044 <     * Initiates termination: Runs three passes through workQueues:
2045 <     * (0) Setting termination status, followed by wakeups of queued
2046 <     * workers; (1) cancelling all tasks; (2) interrupting lagging
2047 <     * threads (likely in external tasks, but possibly also blocked in
2048 <     * joins).  Each pass repeats previous steps because of potential
2049 <     * lagging thread creation.
2050 <     */
1841 <    private void startTerminating() {
1842 <        for (int pass = 0; pass < 3; ++pass) {
1843 <            WorkQueue[] ws = workQueues;
1844 <            if (ws != null) {
1845 <                WorkQueue w; Thread wt;
1846 <                int n = ws.length;
1847 <                for (int j = 0; j < n; ++j) {
1848 <                    if ((w = ws[j]) != null) {
1849 <                        w.runState = -1;
1850 <                        if (pass > 0) {
1851 <                            w.cancelAll();
1852 <                            if (pass > 1 && (wt = w.owner) != null &&
1853 <                                !wt.isInterrupted()) {
1854 <                                try {
1855 <                                    wt.interrupt();
1856 <                                } catch (SecurityException ignore) {
2038 >            if (U.compareAndSwapLong(this, CTL, c, c | STOP_BIT)) {
2039 >                for (int pass = 0; pass < 3; ++pass) {
2040 >                    WorkQueue[] ws = workQueues;
2041 >                    if (ws != null) {
2042 >                        WorkQueue w;
2043 >                        int n = ws.length;
2044 >                        for (int i = 0; i < n; ++i) {
2045 >                            if ((w = ws[i]) != null) {
2046 >                                w.runState = -1;
2047 >                                if (pass > 0) {
2048 >                                    w.cancelAll();
2049 >                                    if (pass > 1)
2050 >                                        w.interruptOwner();
2051                                  }
2052                              }
2053                          }
2054 <                    }
2055 <                }
2056 <                // Wake up workers parked on event queue
2057 <                int i, e; long c; Thread p;
2058 <                while ((i = ((~(e = (int)(c = ctl)) << 1) | 1) & SMASK) < n &&
2059 <                       (w = ws[i]) != null &&
2060 <                       w.eventCount == (e | INT_SIGN)) {
2061 <                    long nc = ((long)(w.nextWait & E_MASK) |
2062 <                               ((c + AC_UNIT) & AC_MASK) |
2063 <                               (c & (TC_MASK|STOP_BIT)));
2064 <                    if (U.compareAndSwapLong(this, CTL, c, nc)) {
2065 <                        w.eventCount = (e + E_SEQ) & E_MASK;
2066 <                        if ((p = w.parker) != null)
2067 <                            U.unpark(p);
2054 >                        // Wake up workers parked on event queue
2055 >                        int i, e; long cc; Thread p;
2056 >                        while ((e = (int)(cc = ctl) & E_MASK) != 0 &&
2057 >                               (i = e & SMASK) < n &&
2058 >                               (w = ws[i]) != null) {
2059 >                            long nc = ((long)(w.nextWait & E_MASK) |
2060 >                                       ((cc + AC_UNIT) & AC_MASK) |
2061 >                                       (cc & (TC_MASK|STOP_BIT)));
2062 >                            if (w.eventCount == (e | INT_SIGN) &&
2063 >                                U.compareAndSwapLong(this, CTL, cc, nc)) {
2064 >                                w.eventCount = (e + E_SEQ) & E_MASK;
2065 >                                w.runState = -1;
2066 >                                if ((p = w.parker) != null)
2067 >                                    U.unpark(p);
2068 >                            }
2069 >                        }
2070                      }
2071                  }
2072              }
# Line 1946 | Line 2142 | public class ForkJoinPool extends Abstra
2142          checkPermission();
2143          if (factory == null)
2144              throw new NullPointerException();
2145 <        if (parallelism <= 0 || parallelism > MAX_ID)
2145 >        if (parallelism <= 0 || parallelism > MAX_CAP)
2146              throw new IllegalArgumentException();
2147          this.parallelism = parallelism;
2148          this.factory = factory;
2149          this.ueh = handler;
2150          this.localMode = asyncMode ? FIFO_QUEUE : LIFO_QUEUE;
1955        this.nextPoolIndex = 1;
2151          long np = (long)(-parallelism); // offset ctl counts
2152          this.ctl = ((np << AC_SHIFT) & AC_MASK) | ((np << TC_SHIFT) & TC_MASK);
2153 <        // initialize workQueues array with room for 2*parallelism if possible
2154 <        int n = parallelism << 1;
2155 <        if (n >= MAX_ID)
2156 <            n = MAX_ID;
2157 <        else { // See Hackers Delight, sec 3.2, where n < (1 << 16)
2158 <            n |= n >>> 1; n |= n >>> 2; n |= n >>> 4; n |= n >>> 8;
2159 <        }
1965 <        this.workQueues = new WorkQueue[(n + 1) << 1];
1966 <        ReentrantLock lck = this.lock = new ReentrantLock();
1967 <        this.termination = lck.newCondition();
2153 >        // Use nearest power 2 for workQueues size. See Hackers Delight sec 3.2.
2154 >        int n = parallelism - 1;
2155 >        n |= n >>> 1; n |= n >>> 2; n |= n >>> 4; n |= n >>> 8; n |= n >>> 16;
2156 >        int size = (n + 1) << 1;        // #slots = 2*#workers
2157 >        this.submitMask = size - 1;     // room for max # of submit queues
2158 >        this.workQueues = new WorkQueue[size];
2159 >        this.termination = (this.lock = new Mutex()).newCondition();
2160          this.stealCount = new AtomicLong();
2161          this.nextWorkerNumber = new AtomicInteger();
2162 +        int pn = poolNumberGenerator.incrementAndGet();
2163          StringBuilder sb = new StringBuilder("ForkJoinPool-");
2164 <        sb.append(poolNumberGenerator.incrementAndGet());
2164 >        sb.append(Integer.toString(pn));
2165          sb.append("-worker-");
2166          this.workerNamePrefix = sb.toString();
2167 <        // Create initial submission queue
2168 <        WorkQueue sq = tryAddSharedQueue(0);
2169 <        if (sq != null)
1977 <            sq.growArray(false);
2167 >        lock.lock();
2168 >        this.runState = 1;              // set init flag
2169 >        lock.unlock();
2170      }
2171  
2172      // Execution methods
# Line 1996 | Line 2188 | public class ForkJoinPool extends Abstra
2188       *         scheduled for execution
2189       */
2190      public <T> T invoke(ForkJoinTask<T> task) {
2191 +        if (task == null)
2192 +            throw new NullPointerException();
2193          doSubmit(task);
2194          return task.join();
2195      }
# Line 2009 | Line 2203 | public class ForkJoinPool extends Abstra
2203       *         scheduled for execution
2204       */
2205      public void execute(ForkJoinTask<?> task) {
2206 +        if (task == null)
2207 +            throw new NullPointerException();
2208          doSubmit(task);
2209      }
2210  
# Line 2026 | Line 2222 | public class ForkJoinPool extends Abstra
2222          if (task instanceof ForkJoinTask<?>) // avoid re-wrap
2223              job = (ForkJoinTask<?>) task;
2224          else
2225 <            job = ForkJoinTask.adapt(task, null);
2225 >            job = new ForkJoinTask.AdaptedRunnableAction(task);
2226          doSubmit(job);
2227      }
2228  
# Line 2040 | Line 2236 | public class ForkJoinPool extends Abstra
2236       *         scheduled for execution
2237       */
2238      public <T> ForkJoinTask<T> submit(ForkJoinTask<T> task) {
2239 +        if (task == null)
2240 +            throw new NullPointerException();
2241          doSubmit(task);
2242          return task;
2243      }
# Line 2050 | Line 2248 | public class ForkJoinPool extends Abstra
2248       *         scheduled for execution
2249       */
2250      public <T> ForkJoinTask<T> submit(Callable<T> task) {
2251 <        if (task == null)
2054 <            throw new NullPointerException();
2055 <        ForkJoinTask<T> job = ForkJoinTask.adapt(task);
2251 >        ForkJoinTask<T> job = new ForkJoinTask.AdaptedCallable<T>(task);
2252          doSubmit(job);
2253          return job;
2254      }
# Line 2063 | Line 2259 | public class ForkJoinPool extends Abstra
2259       *         scheduled for execution
2260       */
2261      public <T> ForkJoinTask<T> submit(Runnable task, T result) {
2262 <        if (task == null)
2067 <            throw new NullPointerException();
2068 <        ForkJoinTask<T> job = ForkJoinTask.adapt(task, result);
2262 >        ForkJoinTask<T> job = new ForkJoinTask.AdaptedRunnable<T>(task, result);
2263          doSubmit(job);
2264          return job;
2265      }
# Line 2082 | Line 2276 | public class ForkJoinPool extends Abstra
2276          if (task instanceof ForkJoinTask<?>) // avoid re-wrap
2277              job = (ForkJoinTask<?>) task;
2278          else
2279 <            job = ForkJoinTask.adapt(task, null);
2279 >            job = new ForkJoinTask.AdaptedRunnableAction(task);
2280          doSubmit(job);
2281          return job;
2282      }
# Line 2092 | Line 2286 | public class ForkJoinPool extends Abstra
2286       * @throws RejectedExecutionException {@inheritDoc}
2287       */
2288      public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) {
2289 <        ArrayList<ForkJoinTask<T>> forkJoinTasks =
2290 <            new ArrayList<ForkJoinTask<T>>(tasks.size());
2291 <        for (Callable<T> task : tasks)
2292 <            forkJoinTasks.add(ForkJoinTask.adapt(task));
2293 <        invoke(new InvokeAll<T>(forkJoinTasks));
2294 <
2289 >        // In previous versions of this class, this method constructed
2290 >        // a task to run ForkJoinTask.invokeAll, but now external
2291 >        // invocation of multiple tasks is at least as efficient.
2292 >        List<ForkJoinTask<T>> fs = new ArrayList<ForkJoinTask<T>>(tasks.size());
2293 >        // Workaround needed because method wasn't declared with
2294 >        // wildcards in return type but should have been.
2295          @SuppressWarnings({"unchecked", "rawtypes"})
2296 <            List<Future<T>> futures = (List<Future<T>>) (List) forkJoinTasks;
2103 <        return futures;
2104 <    }
2296 >            List<Future<T>> futures = (List<Future<T>>) (List) fs;
2297  
2298 <    static final class InvokeAll<T> extends RecursiveAction {
2299 <        final ArrayList<ForkJoinTask<T>> tasks;
2300 <        InvokeAll(ArrayList<ForkJoinTask<T>> tasks) { this.tasks = tasks; }
2301 <        public void compute() {
2302 <            try { invokeAll(tasks); }
2303 <            catch (Exception ignore) {}
2298 >        boolean done = false;
2299 >        try {
2300 >            for (Callable<T> t : tasks) {
2301 >                ForkJoinTask<T> f = new ForkJoinTask.AdaptedCallable<T>(t);
2302 >                doSubmit(f);
2303 >                fs.add(f);
2304 >            }
2305 >            for (ForkJoinTask<T> f : fs)
2306 >                f.quietlyJoin();
2307 >            done = true;
2308 >            return futures;
2309 >        } finally {
2310 >            if (!done)
2311 >                for (ForkJoinTask<T> f : fs)
2312 >                    f.cancel(false);
2313          }
2113        private static final long serialVersionUID = -7914297376763021607L;
2314      }
2315  
2316      /**
# Line 2175 | Line 2375 | public class ForkJoinPool extends Abstra
2375          int rc = 0;
2376          WorkQueue[] ws; WorkQueue w;
2377          if ((ws = workQueues) != null) {
2378 <            int n = ws.length;
2379 <            for (int i = 1; i < n; i += 2) {
2180 <                Thread.State s; ForkJoinWorkerThread wt;
2181 <                if ((w = ws[i]) != null && (wt = w.owner) != null &&
2182 <                    w.eventCount >= 0 &&
2183 <                    (s = wt.getState()) != Thread.State.BLOCKED &&
2184 <                    s != Thread.State.WAITING &&
2185 <                    s != Thread.State.TIMED_WAITING)
2378 >            for (int i = 1; i < ws.length; i += 2) {
2379 >                if ((w = ws[i]) != null && w.isApparentlyUnblocked())
2380                      ++rc;
2381              }
2382          }
# Line 2231 | Line 2425 | public class ForkJoinPool extends Abstra
2425          long count = stealCount.get();
2426          WorkQueue[] ws; WorkQueue w;
2427          if ((ws = workQueues) != null) {
2428 <            int n = ws.length;
2235 <            for (int i = 1; i < n; i += 2) {
2428 >            for (int i = 1; i < ws.length; i += 2) {
2429                  if ((w = ws[i]) != null)
2430                      count += w.totalSteals;
2431              }
# Line 2254 | Line 2447 | public class ForkJoinPool extends Abstra
2447          long count = 0;
2448          WorkQueue[] ws; WorkQueue w;
2449          if ((ws = workQueues) != null) {
2450 <            int n = ws.length;
2258 <            for (int i = 1; i < n; i += 2) {
2450 >            for (int i = 1; i < ws.length; i += 2) {
2451                  if ((w = ws[i]) != null)
2452                      count += w.queueSize();
2453              }
# Line 2274 | Line 2466 | public class ForkJoinPool extends Abstra
2466          int count = 0;
2467          WorkQueue[] ws; WorkQueue w;
2468          if ((ws = workQueues) != null) {
2469 <            int n = ws.length;
2278 <            for (int i = 0; i < n; i += 2) {
2469 >            for (int i = 0; i < ws.length; i += 2) {
2470                  if ((w = ws[i]) != null)
2471                      count += w.queueSize();
2472              }
# Line 2292 | Line 2483 | public class ForkJoinPool extends Abstra
2483      public boolean hasQueuedSubmissions() {
2484          WorkQueue[] ws; WorkQueue w;
2485          if ((ws = workQueues) != null) {
2486 <            int n = ws.length;
2487 <            for (int i = 0; i < n; i += 2) {
2297 <                if ((w = ws[i]) != null && w.queueSize() != 0)
2486 >            for (int i = 0; i < ws.length; i += 2) {
2487 >                if ((w = ws[i]) != null && !w.isEmpty())
2488                      return true;
2489              }
2490          }
# Line 2311 | Line 2501 | public class ForkJoinPool extends Abstra
2501      protected ForkJoinTask<?> pollSubmission() {
2502          WorkQueue[] ws; WorkQueue w; ForkJoinTask<?> t;
2503          if ((ws = workQueues) != null) {
2504 <            int n = ws.length;
2315 <            for (int i = 0; i < n; i += 2) {
2504 >            for (int i = 0; i < ws.length; i += 2) {
2505                  if ((w = ws[i]) != null && (t = w.poll()) != null)
2506                      return t;
2507              }
# Line 2341 | Line 2530 | public class ForkJoinPool extends Abstra
2530          int count = 0;
2531          WorkQueue[] ws; WorkQueue w; ForkJoinTask<?> t;
2532          if ((ws = workQueues) != null) {
2533 <            int n = ws.length;
2345 <            for (int i = 0; i < n; ++i) {
2533 >            for (int i = 0; i < ws.length; ++i) {
2534                  if ((w = ws[i]) != null) {
2535                      while ((t = w.poll()) != null) {
2536                          c.add(t);
# Line 2362 | Line 2550 | public class ForkJoinPool extends Abstra
2550       * @return a string identifying this pool, as well as its state
2551       */
2552      public String toString() {
2553 <        long st = getStealCount();
2554 <        long qt = getQueuedTaskCount();
2555 <        long qs = getQueuedSubmissionCount();
2368 <        int rc = getRunningThreadCount();
2369 <        int pc = parallelism;
2553 >        // Use a single pass through workQueues to collect counts
2554 >        long qt = 0L, qs = 0L; int rc = 0;
2555 >        long st = stealCount.get();
2556          long c = ctl;
2557 +        WorkQueue[] ws; WorkQueue w;
2558 +        if ((ws = workQueues) != null) {
2559 +            for (int i = 0; i < ws.length; ++i) {
2560 +                if ((w = ws[i]) != null) {
2561 +                    int size = w.queueSize();
2562 +                    if ((i & 1) == 0)
2563 +                        qs += size;
2564 +                    else {
2565 +                        qt += size;
2566 +                        st += w.totalSteals;
2567 +                        if (w.isApparentlyUnblocked())
2568 +                            ++rc;
2569 +                    }
2570 +                }
2571 +            }
2572 +        }
2573 +        int pc = parallelism;
2574          int tc = pc + (short)(c >>> TC_SHIFT);
2575          int ac = pc + (int)(c >> AC_SHIFT);
2576          if (ac < 0) // ignore transient negative
# Line 2403 | Line 2606 | public class ForkJoinPool extends Abstra
2606       */
2607      public void shutdown() {
2608          checkPermission();
2609 <        enableShutdown();
2407 <        tryTerminate(false);
2609 >        tryTerminate(false, true);
2610      }
2611  
2612      /**
# Line 2425 | Line 2627 | public class ForkJoinPool extends Abstra
2627       */
2628      public List<Runnable> shutdownNow() {
2629          checkPermission();
2630 <        enableShutdown();
2429 <        tryTerminate(true);
2630 >        tryTerminate(true, true);
2631          return Collections.emptyList();
2632      }
2633  
# Line 2483 | Line 2684 | public class ForkJoinPool extends Abstra
2684      public boolean awaitTermination(long timeout, TimeUnit unit)
2685          throws InterruptedException {
2686          long nanos = unit.toNanos(timeout);
2687 <        final ReentrantLock lock = this.lock;
2687 >        final Mutex lock = this.lock;
2688          lock.lock();
2689          try {
2690              for (;;) {
# Line 2597 | Line 2798 | public class ForkJoinPool extends Abstra
2798          ForkJoinPool p = ((t instanceof ForkJoinWorkerThread) ?
2799                            ((ForkJoinWorkerThread)t).pool : null);
2800          while (!blocker.isReleasable()) {
2801 <            if (p == null || p.tryCompensate()) {
2801 >            if (p == null || p.tryCompensate(null, blocker)) {
2802                  try {
2803                      do {} while (!blocker.isReleasable() && !blocker.block());
2804                  } finally {
# Line 2614 | Line 2815 | public class ForkJoinPool extends Abstra
2815      // implement RunnableFuture.
2816  
2817      protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
2818 <        return (RunnableFuture<T>) ForkJoinTask.adapt(runnable, value);
2818 >        return new ForkJoinTask.AdaptedRunnable<T>(runnable, value);
2819      }
2820  
2821      protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
2822 <        return (RunnableFuture<T>) ForkJoinTask.adapt(callable);
2822 >        return new ForkJoinTask.AdaptedCallable<T>(callable);
2823      }
2824  
2825      // Unsafe mechanics
2826      private static final sun.misc.Unsafe U;
2827      private static final long CTL;
2627    private static final long RUNSTATE;
2828      private static final long PARKBLOCKER;
2829 +    private static final int ABASE;
2830 +    private static final int ASHIFT;
2831  
2832      static {
2833          poolNumberGenerator = new AtomicInteger();
2834 +        nextSubmitterSeed = new AtomicInteger(0x55555555);
2835          modifyThreadPermission = new RuntimePermission("modifyThread");
2836          defaultForkJoinWorkerThreadFactory =
2837              new DefaultForkJoinWorkerThreadFactory();
2838 +        submitters = new ThreadSubmitter();
2839          int s;
2840          try {
2841              U = getUnsafe();
2842              Class<?> k = ForkJoinPool.class;
2843 <            Class<?> tk = Thread.class;
2843 >            Class<?> ak = ForkJoinTask[].class;
2844              CTL = U.objectFieldOffset
2845                  (k.getDeclaredField("ctl"));
2846 <            RUNSTATE = U.objectFieldOffset
2643 <                (k.getDeclaredField("runState"));
2846 >            Class<?> tk = Thread.class;
2847              PARKBLOCKER = U.objectFieldOffset
2848                  (tk.getDeclaredField("parkBlocker"));
2849 +            ABASE = U.arrayBaseOffset(ak);
2850 +            s = U.arrayIndexScale(ak);
2851          } catch (Exception e) {
2852              throw new Error(e);
2853          }
2854 +        if ((s & (s-1)) != 0)
2855 +            throw new Error("data type scale not a power of two");
2856 +        ASHIFT = 31 - Integer.numberOfLeadingZeros(s);
2857      }
2858  
2859      /**

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines