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.120 by jsr166, Tue Jan 31 01:32:25 2012 UTC vs.
Revision 1.129 by dl, Tue May 22 23:08:19 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 177 | 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 207 | Line 209 | public class ForkJoinPool extends Abstra
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, so never block.
212 >     * other queues -- they block only when creating and registering
213 >     * new queues.
214       *
215       * Management
216       * ==========
# Line 233 | Line 236 | public class ForkJoinPool extends Abstra
236       * deregister WorkQueues, as well as to enable shutdown. It is
237       * only modified under a lock (normally briefly held, but
238       * occasionally protecting allocations and resizings) but even
239 <     * when locked remains available to check consistency. An
237 <     * auxiliary field "growHints", also only modified under lock,
238 <     * contains a candidate index for the next WorkQueue and
239 <     * a mask for submission queue indices.
239 >     * when locked remains available to check consistency.
240       *
241       * Recording WorkQueues.  WorkQueues are recorded in the
242       * "workQueues" array that is created upon pool construction and
# 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 currently
256 <     * used indices.
251 >     * scanning.
252       *
253       * All worker thread creation is on-demand, triggered by task
254       * submissions, replacement of terminated workers, and/or
# Line 385 | 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 workQueues 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 397 | 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 449 | Line 465 | public class ForkJoinPool extends Abstra
465      // Static utilities
466  
467      /**
452     * Computes an initial hash code (also serving as a non-zero
453     * random seed) for a thread id. This method is expected to
454     * provide higher-quality hash codes than using method hashCode().
455     */
456    static final int hashId(long id) {
457        int h = (int)id ^ (int)(id >>> 32); // Use MurmurHash of thread id
458        h ^= h >>> 16; h *= 0x85ebca6b;
459        h ^= h >>> 13; h *= 0xc2b2ae35;
460        h ^= h >>> 16;
461        return (h == 0)? 1 : h; // ensure nonzero
462    }
463
464    /**
468       * If there is a security manager, makes sure caller has
469       * permission to modify threads.
470       */
# Line 592 | Line 595 | public class ForkJoinPool extends Abstra
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 619 | 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) {
630 <            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.
648         * @param p if non-null, pool to signal if necessary
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 691 | 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; ForkJoinTask<?> t;
725 <            while ((b = base) - top < 0 && (a = array) != null) {
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 &&
# Line 708 | Line 756 | public class ForkJoinPool extends Abstra
756          }
757  
758          /**
759 <         * Takes next task, if one exists, in LIFO order.  Call only
712 <         * by owner in unshared queues. (We do not have a shared
713 <         * version of this method because it is never needed.)
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)) {
724 <                        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 749 | Line 799 | public class ForkJoinPool extends Abstra
799          }
800  
801          /**
752         * Returns task at index b if b is current base of queue.
753         */
754        final ForkJoinTask<?> pollAt(int b) {
755            ForkJoinTask<?> t; ForkJoinTask<?>[] a;
756            if ((a = array) != null) {
757                int j = (((a.length - 1) & b) << ASHIFT) + ABASE;
758                if ((t = (ForkJoinTask<?>)U.getObjectVolatile(a, j)) != null &&
759                    base == b &&
760                    U.compareAndSwapObject(a, j, t, null)) {
761                    base = b + 1;
762                    return t;
763                }
764            }
765            return null;
766        }
767
768        /**
802           * Pops the given task only if it is at the current top.
803           */
804          final boolean tryUnpush(ForkJoinTask<?> t) {
# Line 796 | Line 829 | public class ForkJoinPool extends Abstra
829          }
830  
831          /**
799         * If present, removes from queue and executes the given task, or
800         * any other cancelled task. Returns (true) immediately on any CAS
801         * or consistency check failure so caller can retry.
802         *
803         * @return false if no progress can be made
804         */
805        final boolean tryRemoveAndExec(ForkJoinTask<?> task) {
806            boolean removed = false, empty = true, progress = true;
807            ForkJoinTask<?>[] a; int m, s, b, n;
808            if ((a = array) != null && (m = a.length - 1) >= 0 &&
809                (n = (s = top) - (b = base)) > 0) {
810                for (ForkJoinTask<?> t;;) {           // traverse from s to b
811                    int j = ((--s & m) << ASHIFT) + ABASE;
812                    t = (ForkJoinTask<?>)U.getObjectVolatile(a, j);
813                    if (t == null)                    // inconsistent length
814                        break;
815                    else if (t == task) {
816                        if (s + 1 == top) {           // pop
817                            if (!U.compareAndSwapObject(a, j, task, null))
818                                break;
819                            top = s;
820                            removed = true;
821                        }
822                        else if (base == b)           // replace with proxy
823                            removed = U.compareAndSwapObject(a, j, task,
824                                                             new EmptyTask());
825                        break;
826                    }
827                    else if (t.status >= 0)
828                        empty = false;
829                    else if (s + 1 == top) {          // pop and throw away
830                        if (U.compareAndSwapObject(a, j, t, null))
831                            top = s;
832                        break;
833                    }
834                    if (--n == 0) {
835                        if (!empty && base == b)
836                            progress = false;
837                        break;
838                    }
839                }
840            }
841            if (removed)
842                task.doExec();
843            return progress;
844        }
845
846        /**
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 892 | Line 877 | public class ForkJoinPool extends Abstra
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 several usages in ForkJoinPool
881 <         * to avoid writes inside busy scan loops.
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;
# Line 905 | Line 890 | public class ForkJoinPool extends Abstra
890          // Execution methods
891  
892          /**
893 <         * Removes and runs tasks until empty, using local mode
909 <         * 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.
921         *
922         * @return true unless terminating
971           */
972 <        final boolean runTask(ForkJoinTask<?> t) {
925 <            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              }
933            else if (runState < 0)            // terminating
934                alive = false;
935            return alive;
985          }
986  
987          /**
# Line 998 | Line 1047 | public class ForkJoinPool extends Abstra
1047              ASHIFT = 31 - Integer.numberOfLeadingZeros(s);
1048          }
1049      }
1001
1050      /**
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;
1068 <        Submitter() { seed = hashId(Thread.currentThread().getId()); }
1068 >        Submitter() {
1069 >            int s = nextSubmitterSeed.getAndAdd(SEED_INCREMENT);
1070 >            seed = (s == 0) ? 1 : s; // ensure non-zero
1071 >        }
1072      }
1073  
1074      /** ThreadLocal class for Submitters */
# Line 1031 | Line 1091 | public class ForkJoinPool extends Abstra
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       */
# Line 1063 | Line 1129 | public class ForkJoinPool extends Abstra
1129      private static final long SHRINK_TIMEOUT = SHRINK_RATE - (SHRINK_RATE / 10);
1130  
1131      /**
1132 <     * The maximum stolen->joining link depth allowed in tryHelpStealer.
1133 <     * Depths for legitimate chains are unbounded, but we use a fixed
1134 <     * constant to avoid (otherwise unchecked) cycles and to bound
1135 <     * staleness of traversal parameters at the expense of sometimes
1136 <     * blocking when we could be helping.
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 >    /**
1155 >     * Increment for seed generators. See class ThreadLocal for
1156 >     * explanation.
1157       */
1158 <    private static final int MAX_HELP_DEPTH = 16;
1158 >    private static final int SEED_INCREMENT = 0x61c88647;
1159  
1160      /**
1161       * Bits and masks for control variables
# Line 1101 | Line 1187 | public class ForkJoinPool extends Abstra
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 (15 bits)
1191 <     * MASK: mask (power of 2 - 1) covering all registered poolIndexes (16 bits)
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 combination of mask and sequence number enables simple
1194 <     * consistency checks: Staleness of read-only operations on the
1195 <     * workQueues array can be checked by comparing runState before vs
1110 <     * after the reads. The low 16 bits (i.e, anding with SMASK) hold
1111 <     * the smallest power of two covering all indices, minus
1112 <     * one.
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
# Line 1119 | Line 1202 | public class ForkJoinPool extends Abstra
1202      private static final int  EC_SHIFT   = 16;
1203  
1204      // bounds
1122    private static final int  POOL_MAX   = 0x7fff;  // max #workers - 1
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;
# Line 1148 | Line 1231 | public class ForkJoinPool extends Abstra
1231  
1232      // runState bits
1233      private static final int SHUTDOWN    = 1 << 31;
1151    private static final int RS_SEQ      = 1 << 16;
1152    private static final int RS_SEQ_MASK = 0x7fff0000;
1234  
1235      // access mode for WorkQueue
1236      static final int LIFO_QUEUE          =  0;
# Line 1168 | Line 1249 | public class ForkJoinPool extends Abstra
1249      volatile long ctl;                         // main pool control
1250      final int parallelism;                     // parallelism level
1251      final int localMode;                       // per-worker scheduling mode
1252 <    int growHints;                             // for expanding indices/ranges
1253 <    volatile int runState;                     // shutdown status, seq, and mask
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
# Line 1179 | Line 1261 | public class ForkJoinPool extends Abstra
1261      final AtomicInteger nextWorkerNumber;      // to create worker name string
1262      final String workerNamePrefix;             // to create worker name string
1263  
1264 <    //  Creating, registering, deregistering and running workers
1264 >    //  Creating, registering, and deregistering workers
1265  
1266      /**
1267       * Tries to create and start a worker
# Line 1210 | 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;
1303 >
1304 >    final void registerWorker(WorkQueue w) {
1305          Mutex lock = this.lock;
1306          lock.lock();
1307          try {
1223            int g = growHints, k = g & SMASK;
1308              WorkQueue[] ws = workQueues;
1309 <            if (ws != null) {                       // ignore on shutdown
1310 <                int n = ws.length;
1311 <                if ((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.eventCount = w.poolIndex = k;     // establish before recording
1318 <                ws[k] = w;
1319 <                growHints = (g & ~SMASK) | ((k + 2) & SMASK);
1320 <                int rs = runState;
1321 <                int m = rs & SMASK;                 // recalculate runState mask
1322 <                if (k > m)
1323 <                    m = (m << 1) + 1;
1324 <                runState = (rs & SHUTDOWN) | ((rs + RS_SEQ) & RS_SEQ_MASK) | m;
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 1254 | 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;
1262            Mutex 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) {
1353 >                if (ws != null && idx >= 0 && idx < ws.length && ws[idx] == w)
1354                      ws[idx] = null;
1268                    growHints = (growHints & ~SMASK) | idx;
1269                }
1355              } finally {
1356                  lock.unlock();
1357              }
# Line 1290 | Line 1375 | public class ForkJoinPool extends Abstra
1375              U.throwException(ex);
1376      }
1377  
1293    /**
1294     * Top-level runloop for workers, called by ForkJoinWorkerThread.run.
1295     */
1296    final void runWorker(ForkJoinWorkerThread wt) {
1297        // Initialize queue array and seed in this thread
1298        WorkQueue w = wt.workQueue;
1299        w.growArray(false);
1300        w.seed = hashId(Thread.currentThread().getId());
1301
1302        do {} while (w.runTask(scan(w)));
1303    }
1378  
1379      // Submissions
1380  
1381      /**
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 unless
1385 <     * pool lock is busy.  If the queue and/or lock are busy, another
1386 <     * index is randomly chosen. The mask in growHints controls the
1387 <     * effective index range of queues considered. The mask is
1388 <     * expanded, up to the current workerQueue mask, upon any detected
1389 <     * contention but otherwise remains small to avoid needlessly
1316 <     * creating queues when there is no contention.
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 task the task. Caller must ensure non-null.
1390       */
1391      private void doSubmit(ForkJoinTask<?> task) {
1319        if (task == null)
1320            throw new NullPointerException();
1392          Submitter s = submitters.get();
1393 <        for (int r = s.seed, m = growHints >>> 16;;) {
1394 <            WorkQueue[] ws; WorkQueue q; Mutex lk;
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 <            if ((q = ws[k]) == null && (lk = lock).tryAcquire(0)) {
1399 <                try {                        // try to create new queue
1400 <                    if (ws == workQueues && (q = ws[k]) == null) {
1401 <                        int rs;              // update runState seq
1402 <                        ws[k] = q = new WorkQueue(null, SHARED_QUEUE);
1403 <                        runState = (((rs = runState) & SHUTDOWN) |
1404 <                                    ((rs + RS_SEQ) & ~SHUTDOWN));
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 <                    lk.unlock();
1409 >                    lock.unlock();
1410                  }
1411              }
1412 <            if (q != null) {
1413 <                if (q.trySharedPush(task)) {
1414 <                    signalWork();
1415 <                    return;
1416 <                }
1417 <                else if (m < parallelism - 1 && m < (runState & SMASK)) {
1418 <                    Mutex lock = this.lock;
1346 <                    lock.lock();             // block until lock free
1347 <                    int g = growHints;
1348 <                    if (g >>> 16 == m)       // expand range
1349 <                        growHints = (((m << 1) + 1) << 16) | (g & SMASK);
1350 <                    lock.unlock();           // no need for try/finally
1351 <                }
1352 <                else if ((r & m) == 0)
1353 <                    Thread.yield();          // occasionally yield if busy
1354 <            }
1355 <            if (m == (m = growHints >>> 16)) {
1356 <                r ^= r << 13;                // update seed unless new range
1357 <                r ^= r >>> 17;               // same xorshift as WorkQueues
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          }
1424      }
1425  
# Line 1405 | Line 1468 | public class ForkJoinPool extends Abstra
1468          }
1469      }
1470  
1471 +    // Scanning for tasks
1472 +
1473      /**
1474 <     * Tries to decrement active count (sometimes implicitly) and
1410 <     * possibly release or create a compensating worker in preparation
1411 <     * for blocking. Fails on contention or termination.
1412 <     *
1413 <     * @return true if the caller can block, else should recheck and retry
1474 >     * Top-level runloop for workers, called by ForkJoinWorkerThread.run.
1475       */
1476 <    final boolean tryCompensate() {
1477 <        WorkQueue w; Thread p;
1478 <        int pc = parallelism, e, u, ac, tc, i;
1418 <        long c = ctl;
1419 <        WorkQueue[] ws = workQueues;
1420 <        if ((e = (int)c) >= 0) {
1421 <            if ((ac = ((u = (int)(c >>> 32)) >> UAC_SHIFT)) <= 0 &&
1422 <                e != 0 && ws != null && (i = e & SMASK) < ws.length &&
1423 <                (w = ws[i]) != null) {
1424 <                long nc = (long)(w.nextWait & E_MASK) | (c & (AC_MASK|TC_MASK));
1425 <                if (w.eventCount == (e | INT_SIGN) &&
1426 <                    U.compareAndSwapLong(this, CTL, c, nc)) {
1427 <                    w.eventCount = (e + E_SEQ) & E_MASK;
1428 <                    if ((p = w.parker) != null)
1429 <                        U.unpark(p);
1430 <                    return true;             // release an idle worker
1431 <                }
1432 <            }
1433 <            else if ((tc = (short)(u >>> UTC_SHIFT)) >= 0 && ac + pc > 1) {
1434 <                long nc = ((c - AC_UNIT) & AC_MASK) | (c & ~AC_MASK);
1435 <                if (U.compareAndSwapLong(this, CTL, c, nc))
1436 <                    return true;             // no compensation needed
1437 <            }
1438 <            else if (tc + pc < POOL_MAX) {
1439 <                long nc = ((c + TC_UNIT) & TC_MASK) | (c & ~TC_MASK);
1440 <                if (U.compareAndSwapLong(this, CTL, c, nc)) {
1441 <                    addWorker();
1442 <                    return true;             // create replacement
1443 <                }
1444 <            }
1445 <        }
1446 <        return false;
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  
1449    // Scanning for tasks
1450
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 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
1467 <     * 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       *
# Line 1475 | 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       *
1478     * * If the caller has run a task since the last empty scan,
1479     * return (to allow rescan) if other workers are not also yet
1480     * enqueued.  Field WorkQueue.rescans counts down on each scan to
1481     * ensure eventual inactivation and blocking.
1482     *
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
1488 <     * is quiescent, relay to idleAwaitWork to check for termination
1489 <     * 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) { // consistency check
1529 <            for (int k = 0, j = -1 - m; ; ++j) {
1530 <                WorkQueue q; int b;
1531 <                if (j < 0) {                 // random probes while j negative
1532 <                    r ^= r << 13; r ^= r >>> 17; k = (r ^= r << 5) | (j & 1);
1533 <                }                            // worker (not submit) for odd j
1534 <                else                         // cyclic scan when j >= 0
1535 <                    k += 7;                  // step 7 reduces array packing bias
1536 <                if ((q = ws[k & m]) != null && (b = q.base) - q.top < 0) {
1537 <                    ForkJoinTask<?> t = (ec >= 0) ? q.pollAt(b) : null;
1538 <                    w.seed = r;              // save seed for next scan
1539 <                    if (t != null)
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 >                        if (q.top - (q.base = b + 1) > 1)
1539 >                            signalWork();    // help pushes signal
1540                          return t;
1541 <                    break;
1541 >                    }
1542 >                    else if (ec < 0 || j <= m) {
1543 >                        rs = 0;               // mark scan as imcomplete
1544 >                        break;                // caller can retry after release
1545 >                    }
1546                  }
1547 <                else if (j - m > m) {
1515 <                    if (rs == runState)      // staleness check
1516 <                        swept = true;
1547 >                if (--j < 0)
1548                      break;
1518                }
1549              }
1550  
1521            // Decode ctl on empty scan
1551              long c = ctl; int e = (int)c, a = (int)(c >> AC_SHIFT), nr, ns;
1552 <            if (e < 0)                       // pool is terminating
1553 <                w.runState = -1;
1554 <            else if (!swept) {               // try to release a waiter
1555 <                WorkQueue v; Thread p;
1556 <                if (e > 0 && a < 0 && (v = ws[e & m]) != null &&
1557 <                    v.eventCount == (e | INT_SIGN)) {
1552 >            if (e < 0)                        // decode ctl on empty scan
1553 >                w.runState = -1;              // pool is terminating
1554 >            else if (rs == 0 || rs != runState) { // incomplete scan
1555 >                WorkQueue v; Thread p;        // try to release a waiter
1556 >                if (e > 0 && a < 0 && w.eventCount == ec &&
1557 >                    (v = ws[e & m]) != null && v.eventCount == (e | INT_SIGN)) {
1558                      long nc = ((long)(v.nextWait & E_MASK) |
1559                                 ((c + AC_UNIT) & (AC_MASK|TC_MASK)));
1560 <                    if (U.compareAndSwapLong(this, CTL, c, nc)) {
1560 >                    if (ctl == c && U.compareAndSwapLong(this, CTL, c, nc)) {
1561                          v.eventCount = (e + E_SEQ) & E_MASK;
1562                          if ((p = v.parker) != null)
1563                              U.unpark(p);
1564                      }
1565                  }
1566              }
1567 <            else if ((nr = w.rescans) > 0) { // continue rescanning
1539 <                int ac = a + parallelism;
1540 <                if (((w.rescans = (ac < nr) ? ac : nr - 1) & 3) == 0 &&
1541 <                    w.eventCount == ec)
1542 <                    Thread.yield();          // occasionally yield
1543 <            }
1544 <            else if (ec >= 0) {              // try to enqueue
1567 >            else if (ec >= 0) {               // try to enqueue/inactivate
1568                  long nc = (long)ec | ((c - AC_UNIT) & (AC_MASK|TC_MASK));
1569                  w.nextWait = e;
1570 <                w.eventCount = ec | INT_SIGN;// mark as inactive
1571 <                if (!U.compareAndSwapLong(this, CTL, c, nc))
1572 <                    w.eventCount = ec;       // unmark on CAS failure
1573 <                else if ((ns = w.nsteals) != 0) {
1574 <                    w.nsteals = 0;           // set rescans if ran task
1575 <                    w.rescans = a + parallelism;
1576 <                    w.totalSteals += ns;
1570 >                w.eventCount = ec | INT_SIGN; // mark as inactive
1571 >                if (ctl != c || !U.compareAndSwapLong(this, CTL, c, nc))
1572 >                    w.eventCount = ec;        // unmark on CAS failure
1573 >                else {
1574 >                    if ((ns = w.nsteals) != 0) {
1575 >                        w.nsteals = 0;        // set rescans if ran task
1576 >                        w.rescans = (a > 0) ? 0 : a + parallelism;
1577 >                        w.totalSteals += ns;
1578 >                    }
1579 >                    if (a == 1 - parallelism) // quiescent
1580 >                        idleAwaitWork(w, nc, c);
1581                  }
1582              }
1583 <            else{                            // already queued
1584 <                if (parallelism == -a)
1585 <                    idleAwaitWork(w);        // quiescent
1586 <                if (w.eventCount == ec) {
1587 <                    Thread.interrupted();    // clear status
1588 <                    ForkJoinWorkerThread wt = w.owner;
1583 >            else if (w.eventCount < 0) {      // already queued
1584 >                if ((nr = w.rescans) > 0) {   // continue rescanning
1585 >                    int ac = a + parallelism;
1586 >                    if (((w.rescans = (ac < nr) ? ac : nr - 1) & 3) == 0)
1587 >                        Thread.yield();       // yield before block
1588 >                }
1589 >                else {
1590 >                    Thread.interrupted();     // clear status
1591 >                    Thread wt = Thread.currentThread();
1592                      U.putObject(wt, PARKBLOCKER, this);
1593 <                    w.parker = wt;           // emulate LockSupport.park
1594 <                    if (w.eventCount == ec)  // recheck
1595 <                        U.park(false, 0L);   // block
1593 >                    w.parker = wt;            // emulate LockSupport.park
1594 >                    if (w.eventCount < 0)     // recheck
1595 >                        U.park(false, 0L);
1596                      w.parker = null;
1597                      U.putObject(wt, PARKBLOCKER, null);
1598                  }
# Line 1572 | Line 1602 | public class ForkJoinPool extends Abstra
1602      }
1603  
1604      /**
1605 <     * If inactivating worker w has caused pool to become quiescent,
1606 <     * checks for pool termination, and, so long as this is not the
1607 <     * only worker, waits for event for up to SHRINK_RATE nanosecs.
1608 <     * On timeout, if ctl has not changed, terminates the worker,
1609 <     * which will in turn wake up another worker to possibly repeat
1610 <     * this process.
1605 >     * If inactivating worker w has caused the pool to become
1606 >     * quiescent, checks for pool termination, and, so long as this is
1607 >     * not the only worker, waits for event for up to SHRINK_RATE
1608 >     * nanosecs.  On timeout, if ctl has not changed, terminates the
1609 >     * worker, which will in turn wake up another worker to possibly
1610 >     * repeat this process.
1611       *
1612       * @param w the calling worker
1613 +     * @param currentCtl the ctl value triggering possible quiescence
1614 +     * @param prevCtl the ctl value to restore if thread is terminated
1615       */
1616 <    private void idleAwaitWork(WorkQueue w) {
1617 <        long c; int nw, ec;
1618 <        if (!tryTerminate(false, false) &&
1619 <            (int)((c = ctl) >> AC_SHIFT) + parallelism == 0 &&
1620 <            (ec = w.eventCount) == ((int)c | INT_SIGN) &&
1621 <            (nw = w.nextWait) != 0) {
1590 <            long nc = ((long)(nw & E_MASK) | // ctl to restore on timeout
1591 <                       ((c + AC_UNIT) & AC_MASK) | (c & TC_MASK));
1592 <            ForkJoinWorkerThread wt = w.owner;
1593 <            while (ctl == c) {
1616 >    private void idleAwaitWork(WorkQueue w, long currentCtl, long prevCtl) {
1617 >        if (w.eventCount < 0 && !tryTerminate(false, false) &&
1618 >            (int)prevCtl != 0 && !hasQueuedSubmissions() && ctl == currentCtl) {
1619 >            Thread wt = Thread.currentThread();
1620 >            Thread.yield();            // yield before block
1621 >            while (ctl == currentCtl) {
1622                  long startTime = System.nanoTime();
1623                  Thread.interrupted();  // timed variant of version in scan()
1624                  U.putObject(wt, PARKBLOCKER, this);
1625                  w.parker = wt;
1626 <                if (ctl == c)
1626 >                if (ctl == currentCtl)
1627                      U.park(false, SHRINK_RATE);
1628                  w.parker = null;
1629                  U.putObject(wt, PARKBLOCKER, null);
1630 <                if (ctl != c)
1630 >                if (ctl != currentCtl)
1631                      break;
1632                  if (System.nanoTime() - startTime >= SHRINK_TIMEOUT &&
1633 <                    U.compareAndSwapLong(this, CTL, c, nc)) {
1634 <                    w.eventCount = (ec + E_SEQ) | E_MASK;
1635 <                    w.runState = -1;          // shrink
1633 >                    U.compareAndSwapLong(this, CTL, currentCtl, prevCtl)) {
1634 >                    w.eventCount = (w.eventCount + E_SEQ) | E_MASK;
1635 >                    w.runState = -1;   // shrink
1636                      break;
1637                  }
1638              }
# Line 1622 | Line 1650 | public class ForkJoinPool extends Abstra
1650       * leaves hints in workers to speed up subsequent calls. The
1651       * implementation is very branchy to cope with potential
1652       * inconsistencies or loops encountering chains that are stale,
1653 <     * unknown, or of length greater than MAX_HELP_DEPTH links.  All
1626 <     * of these cases are dealt with by just retrying by caller.
1653 >     * unknown, or so long that they are likely cyclic.
1654       *
1655       * @param joiner the joining worker
1656       * @param task the task to join
1657 <     * @return true if found or ran a task (and so is immediately retryable)
1657 >     * @return 0 if no progress can be made, negative if task
1658 >     * known complete, else positive
1659       */
1660 <    final boolean tryHelpStealer(WorkQueue joiner, ForkJoinTask<?> task) {
1661 <        ForkJoinTask<?> subtask;    // current target
1662 <        boolean progress = false;
1663 <        int depth = 0;              // current chain depth
1664 <        int m = runState & SMASK;
1665 <        WorkQueue[] ws = workQueues;
1666 <
1667 <        if (ws != null && ws.length > m && (subtask = task).status >= 0) {
1668 <            outer:for (WorkQueue j = joiner;;) {
1669 <                // Try to find the stealer of subtask, by first using hint
1642 <                WorkQueue stealer = null;
1643 <                WorkQueue v = ws[j.stealHint & m];
1644 <                if (v != null && v.currentSteal == subtask)
1645 <                    stealer = v;
1646 <                else {
1647 <                    for (int i = 1; i <= m; i += 2) {
1648 <                        if ((v = ws[i]) != null && v.currentSteal == subtask) {
1649 <                            stealer = v;
1650 <                            j.stealHint = i; // save hint
1651 <                            break;
1652 <                        }
1660 >    private int tryHelpStealer(WorkQueue joiner, ForkJoinTask<?> task) {
1661 >        int stat = 0, steps = 0;                    // bound to avoid cycles
1662 >        if (joiner != null && task != null) {       // hoist null checks
1663 >            restart: for (;;) {
1664 >                ForkJoinTask<?> subtask = task;     // current target
1665 >                for (WorkQueue j = joiner, v;;) {   // v is stealer of subtask
1666 >                    WorkQueue[] ws; int m, s, h;
1667 >                    if ((s = task.status) < 0) {
1668 >                        stat = s;
1669 >                        break restart;
1670                      }
1671 <                    if (stealer == null)
1672 <                        break;
1673 <                }
1674 <
1675 <                for (WorkQueue q = stealer;;) { // Try to help stealer
1676 <                    ForkJoinTask<?> t; int b;
1677 <                    if (task.status < 0)
1678 <                        break outer;
1679 <                    if ((b = q.base) - q.top < 0) {
1680 <                        progress = true;
1681 <                        if (subtask.status < 0)
1682 <                            break outer;               // stale
1683 <                        if ((t = q.pollAt(b)) != null) {
1684 <                            stealer.stealHint = joiner.poolIndex;
1685 <                            joiner.runSubtask(t);
1671 >                    if ((ws = workQueues) == null || (m = ws.length - 1) <= 0)
1672 >                        break restart;              // shutting down
1673 >                    if ((v = ws[h = (j.stealHint | 1) & m]) == null ||
1674 >                        v.currentSteal != subtask) {
1675 >                        for (int origin = h;;) {    // find stealer
1676 >                            if (((h = (h + 2) & m) & 15) == 1 &&
1677 >                                (subtask.status < 0 || j.currentJoin != subtask))
1678 >                                continue restart;   // occasional staleness check
1679 >                            if ((v = ws[h]) != null &&
1680 >                                v.currentSteal == subtask) {
1681 >                                j.stealHint = h;    // save hint
1682 >                                break;
1683 >                            }
1684 >                            if (h == origin)
1685 >                                break restart;      // cannot find stealer
1686                          }
1687                      }
1688 <                    else { // empty - try to descend to find stealer's stealer
1689 <                        ForkJoinTask<?> next = stealer.currentJoin;
1690 <                        if (++depth == MAX_HELP_DEPTH || subtask.status < 0 ||
1691 <                            next == null || next == subtask)
1692 <                            break outer;  // max depth, stale, dead-end, cyclic
1693 <                        subtask = next;
1694 <                        j = stealer;
1695 <                        break;
1688 >                    for (;;) { // help stealer or descend to its stealer
1689 >                        ForkJoinTask[] a;  int b;
1690 >                        if (subtask.status < 0)     // surround probes with
1691 >                            continue restart;       //   consistency checks
1692 >                        if ((b = v.base) - v.top < 0 && (a = v.array) != null) {
1693 >                            int i = (((a.length - 1) & b) << ASHIFT) + ABASE;
1694 >                            ForkJoinTask<?> t =
1695 >                                (ForkJoinTask<?>)U.getObjectVolatile(a, i);
1696 >                            if (subtask.status < 0 || j.currentJoin != subtask ||
1697 >                                v.currentSteal != subtask)
1698 >                                continue restart;   // stale
1699 >                            stat = 1;               // apparent progress
1700 >                            if (t != null && v.base == b &&
1701 >                                U.compareAndSwapObject(a, i, t, null)) {
1702 >                                v.base = b + 1;     // help stealer
1703 >                                joiner.runSubtask(t);
1704 >                            }
1705 >                            else if (v.base == b && ++steps == MAX_HELP)
1706 >                                break restart;      // v apparently stalled
1707 >                        }
1708 >                        else {                      // empty -- try to descend
1709 >                            ForkJoinTask<?> next = v.currentJoin;
1710 >                            if (subtask.status < 0 || j.currentJoin != subtask ||
1711 >                                v.currentSteal != subtask)
1712 >                                continue restart;   // stale
1713 >                            else if (next == null || ++steps == MAX_HELP)
1714 >                                break restart;      // dead-end or maybe cyclic
1715 >                            else {
1716 >                                subtask = next;
1717 >                                j = v;
1718 >                                break;
1719 >                            }
1720 >                        }
1721                      }
1722                  }
1723              }
1724          }
1725 <        return progress;
1725 >        return stat;
1726      }
1727  
1728      /**
# Line 1689 | Line 1731 | public class ForkJoinPool extends Abstra
1731       * @param joiner the joining worker
1732       * @param task the task
1733       */
1734 <    final void tryPollForAndExec(WorkQueue joiner, ForkJoinTask<?> task) {
1734 >    private void tryPollForAndExec(WorkQueue joiner, ForkJoinTask<?> task) {
1735          WorkQueue[] ws;
1736 <        int m = runState & SMASK;
1737 <        if ((ws = workQueues) != null && ws.length > m) {
1696 <            for (int j = 1; j <= m && task.status >= 0; j += 2) {
1736 >        if ((ws = workQueues) != null) {
1737 >            for (int j = 1; j < ws.length && task.status >= 0; j += 2) {
1738                  WorkQueue q = ws[j];
1739                  if (q != null && q.pollFor(task)) {
1740                      joiner.runSubtask(task);
# Line 1704 | Line 1745 | public class ForkJoinPool extends Abstra
1745      }
1746  
1747      /**
1748 <     * Returns a non-empty steal queue, if one is found during a random,
1749 <     * then cyclic scan, else null.  This method must be retried by
1750 <     * caller if, by the time it tries to use the queue, it is empty.
1748 >     * Tries to decrement active count (sometimes implicitly) and
1749 >     * possibly release or create a compensating worker in preparation
1750 >     * for blocking. Fails on contention or termination. Otherwise,
1751 >     * adds a new thread if no idle workers are available and either
1752 >     * pool would become completely starved or: (at least half
1753 >     * starved, and fewer than 50% spares exist, and there is at least
1754 >     * one task apparently available). Even though the availability
1755 >     * check requires a full scan, it is worthwhile in reducing false
1756 >     * alarms.
1757 >     *
1758 >     * @param task if non-null, a task being waited for
1759 >     * @param blocker if non-null, a blocker being waited for
1760 >     * @return true if the caller can block, else should recheck and retry
1761 >     */
1762 >    final boolean tryCompensate(ForkJoinTask<?> task, ManagedBlocker blocker) {
1763 >        int pc = parallelism, e;
1764 >        long c = ctl;
1765 >        WorkQueue[] ws = workQueues;
1766 >        if ((e = (int)c) >= 0 && ws != null) {
1767 >            int u, a, ac, hc;
1768 >            int tc = (short)((u = (int)(c >>> 32)) >>> UTC_SHIFT) + pc;
1769 >            boolean replace = false;
1770 >            if ((a = u >> UAC_SHIFT) <= 0) {
1771 >                if ((ac = a + pc) <= 1)
1772 >                    replace = true;
1773 >                else if ((e > 0 || (task != null &&
1774 >                                    ac <= (hc = pc >>> 1) && tc < pc + hc))) {
1775 >                    WorkQueue w;
1776 >                    for (int j = 0; j < ws.length; ++j) {
1777 >                        if ((w = ws[j]) != null && !w.isEmpty()) {
1778 >                            replace = true;
1779 >                            break;   // in compensation range and tasks available
1780 >                        }
1781 >                    }
1782 >                }
1783 >            }
1784 >            if ((task == null || task.status >= 0) && // recheck need to block
1785 >                (blocker == null || !blocker.isReleasable()) && ctl == c) {
1786 >                if (!replace) {          // no compensation
1787 >                    long nc = ((c - AC_UNIT) & AC_MASK) | (c & ~AC_MASK);
1788 >                    if (U.compareAndSwapLong(this, CTL, c, nc))
1789 >                        return true;
1790 >                }
1791 >                else if (e != 0) {       // release an idle worker
1792 >                    WorkQueue w; Thread p; int i;
1793 >                    if ((i = e & SMASK) < ws.length && (w = ws[i]) != null) {
1794 >                        long nc = ((long)(w.nextWait & E_MASK) |
1795 >                                   (c & (AC_MASK|TC_MASK)));
1796 >                        if (w.eventCount == (e | INT_SIGN) &&
1797 >                            U.compareAndSwapLong(this, CTL, c, nc)) {
1798 >                            w.eventCount = (e + E_SEQ) & E_MASK;
1799 >                            if ((p = w.parker) != null)
1800 >                                U.unpark(p);
1801 >                            return true;
1802 >                        }
1803 >                    }
1804 >                }
1805 >                else if (tc < MAX_CAP) { // create replacement
1806 >                    long nc = ((c + TC_UNIT) & TC_MASK) | (c & ~TC_MASK);
1807 >                    if (U.compareAndSwapLong(this, CTL, c, nc)) {
1808 >                        addWorker();
1809 >                        return true;
1810 >                    }
1811 >                }
1812 >            }
1813 >        }
1814 >        return false;
1815 >    }
1816 >
1817 >    /**
1818 >     * Helps and/or blocks until the given task is done.
1819 >     *
1820 >     * @param joiner the joining worker
1821 >     * @param task the task
1822 >     * @return task status on exit
1823 >     */
1824 >    final int awaitJoin(WorkQueue joiner, ForkJoinTask<?> task) {
1825 >        int s;
1826 >        if ((s = task.status) >= 0) {
1827 >            ForkJoinTask<?> prevJoin = joiner.currentJoin;
1828 >            joiner.currentJoin = task;
1829 >            long startTime = 0L;
1830 >            for (int k = 0;;) {
1831 >                if ((s = (joiner.isEmpty() ?           // try to help
1832 >                          tryHelpStealer(joiner, task) :
1833 >                          joiner.tryRemoveAndExec(task))) == 0 &&
1834 >                    (s = task.status) >= 0) {
1835 >                    if (k == 0) {
1836 >                        startTime = System.nanoTime();
1837 >                        tryPollForAndExec(joiner, task); // check uncommon case
1838 >                    }
1839 >                    else if ((k & (MAX_HELP - 1)) == 0 &&
1840 >                             System.nanoTime() - startTime >=
1841 >                             COMPENSATION_DELAY &&
1842 >                             tryCompensate(task, null)) {
1843 >                        if (task.trySetSignal()) {
1844 >                            synchronized (task) {
1845 >                                if (task.status >= 0) {
1846 >                                    try {                // see ForkJoinTask
1847 >                                        task.wait();     //  for explanation
1848 >                                    } catch (InterruptedException ie) {
1849 >                                    }
1850 >                                }
1851 >                                else
1852 >                                    task.notifyAll();
1853 >                            }
1854 >                        }
1855 >                        long c;                          // re-activate
1856 >                        do {} while (!U.compareAndSwapLong
1857 >                                     (this, CTL, c = ctl, c + AC_UNIT));
1858 >                    }
1859 >                }
1860 >                if (s < 0 || (s = task.status) < 0) {
1861 >                    joiner.currentJoin = prevJoin;
1862 >                    break;
1863 >                }
1864 >                else if ((k++ & (MAX_HELP - 1)) == MAX_HELP >>> 1)
1865 >                    Thread.yield();                     // for politeness
1866 >            }
1867 >        }
1868 >        return s;
1869 >    }
1870 >
1871 >    /**
1872 >     * Stripped-down variant of awaitJoin used by timed joins. Tries
1873 >     * to help join only while there is continuous progress. (Caller
1874 >     * will then enter a timed wait.)
1875 >     *
1876 >     * @param joiner the joining worker
1877 >     * @param task the task
1878 >     * @return task status on exit
1879 >     */
1880 >    final int helpJoinOnce(WorkQueue joiner, ForkJoinTask<?> task) {
1881 >        int s;
1882 >        while ((s = task.status) >= 0 &&
1883 >               (joiner.isEmpty() ?
1884 >                tryHelpStealer(joiner, task) :
1885 >                joiner.tryRemoveAndExec(task)) != 0)
1886 >            ;
1887 >        return s;
1888 >    }
1889 >
1890 >    /**
1891 >     * Returns a (probably) non-empty steal queue, if one is found
1892 >     * during a random, then cyclic scan, else null.  This method must
1893 >     * be retried by caller if, by the time it tries to use the queue,
1894 >     * it is empty.
1895       */
1896      private WorkQueue findNonEmptyStealQueue(WorkQueue w) {
1897 <        int r = w.seed;    // Same idea as scan(), but ignoring submissions
1897 >        // Similar to loop in scan(), but ignoring submissions
1898 >        int r = w.seed; r ^= r << 13; r ^= r >>> 17; w.seed = r ^= r << 5;
1899 >        int step = (r >>> 16) | 1;
1900          for (WorkQueue[] ws;;) {
1901 <            int m = runState & SMASK;
1902 <            if ((ws = workQueues) == null)
1901 >            int rs = runState, m;
1902 >            if ((ws = workQueues) == null || (m = ws.length - 1) < 1)
1903                  return null;
1904 <            if (ws.length > m) {
1905 <                WorkQueue q;
1906 <                for (int k = 0, j = -1 - m;; ++j) {
1907 <                    if (j < 0) {
1908 <                        r ^= r << 13; r ^= r >>> 17; k = r ^= r << 5;
1909 <                    }
1723 <                    else
1724 <                        k += 7;
1725 <                    if ((q = ws[(k | 1) & m]) != null && q.base - q.top < 0) {
1726 <                        w.seed = r;
1727 <                        return q;
1728 <                    }
1729 <                    else if (j - m > m)
1904 >            for (int j = (m + 1) << 2; ; r += step) {
1905 >                WorkQueue q = ws[((r << 1) | 1) & m];
1906 >                if (q != null && !q.isEmpty())
1907 >                    return q;
1908 >                else if (--j < 0) {
1909 >                    if (runState == rs)
1910                          return null;
1911 +                    break;
1912                  }
1913              }
1914          }
1915      }
1916  
1917 +
1918      /**
1919       * Runs tasks until {@code isQuiescent()}. We piggyback on
1920       * active count ctl maintenance, but rather than blocking
# Line 1741 | Line 1923 | public class ForkJoinPool extends Abstra
1923       */
1924      final void helpQuiescePool(WorkQueue w) {
1925          for (boolean active = true;;) {
1926 <            w.runLocalTasks();      // exhaust local queue
1926 >            ForkJoinTask<?> localTask; // exhaust local queue
1927 >            while ((localTask = w.nextLocalTask()) != null)
1928 >                localTask.doExec();
1929              WorkQueue q = findNonEmptyStealQueue(w);
1930              if (q != null) {
1931 <                ForkJoinTask<?> t;
1931 >                ForkJoinTask<?> t; int b;
1932                  if (!active) {      // re-establish active count
1933                      long c;
1934                      active = true;
1935                      do {} while (!U.compareAndSwapLong
1936                                   (this, CTL, c = ctl, c + AC_UNIT));
1937                  }
1938 <                if ((t = q.poll()) != null)
1938 >                if ((b = q.base) - q.top < 0 && (t = q.pollAt(b)) != null)
1939                      w.runSubtask(t);
1940              }
1941              else {
# Line 1779 | Line 1963 | public class ForkJoinPool extends Abstra
1963       */
1964      final ForkJoinTask<?> nextTaskFor(WorkQueue w) {
1965          for (ForkJoinTask<?> t;;) {
1966 <            WorkQueue q;
1966 >            WorkQueue q; int b;
1967              if ((t = w.nextLocalTask()) != null)
1968                  return t;
1969              if ((q = findNonEmptyStealQueue(w)) == null)
1970                  return null;
1971 <            if ((t = q.poll()) != null)
1971 >            if ((b = q.base) - q.top < 0 && (t = q.pollAt(b)) != null)
1972                  return t;
1973          }
1974      }
# Line 1959 | Line 2143 | public class ForkJoinPool extends Abstra
2143          checkPermission();
2144          if (factory == null)
2145              throw new NullPointerException();
2146 <        if (parallelism <= 0 || parallelism > POOL_MAX)
2146 >        if (parallelism <= 0 || parallelism > MAX_CAP)
2147              throw new IllegalArgumentException();
2148          this.parallelism = parallelism;
2149          this.factory = factory;
2150          this.ueh = handler;
2151          this.localMode = asyncMode ? FIFO_QUEUE : LIFO_QUEUE;
1968        this.growHints = 1;
2152          long np = (long)(-parallelism); // offset ctl counts
2153          this.ctl = ((np << AC_SHIFT) & AC_MASK) | ((np << TC_SHIFT) & TC_MASK);
2154 <        // initialize workQueues array with room for 2*parallelism if possible
2155 <        int n = parallelism << 1;
2156 <        if (n >= POOL_MAX)
2157 <            n = POOL_MAX;
2158 <        else { // See Hackers Delight, sec 3.2, where n < (1 << 16)
2159 <            n |= n >>> 1; n |= n >>> 2; n |= n >>> 4; n |= n >>> 8;
1977 <        }
1978 <        this.workQueues = new WorkQueue[(n + 1) << 1]; // #slots = 2 * #workers
2154 >        // Use nearest power 2 for workQueues size. See Hackers Delight sec 3.2.
2155 >        int n = parallelism - 1;
2156 >        n |= n >>> 1; n |= n >>> 2; n |= n >>> 4; n |= n >>> 8; n |= n >>> 16;
2157 >        int size = (n + 1) << 1;        // #slots = 2*#workers
2158 >        this.submitMask = size - 1;     // room for max # of submit queues
2159 >        this.workQueues = new WorkQueue[size];
2160          this.termination = (this.lock = new Mutex()).newCondition();
2161          this.stealCount = new AtomicLong();
2162          this.nextWorkerNumber = new AtomicInteger();
2163 +        int pn = poolNumberGenerator.incrementAndGet();
2164          StringBuilder sb = new StringBuilder("ForkJoinPool-");
2165 <        sb.append(poolNumberGenerator.incrementAndGet());
2165 >        sb.append(Integer.toString(pn));
2166          sb.append("-worker-");
2167          this.workerNamePrefix = sb.toString();
2168 +        lock.lock();
2169 +        this.runState = 1;              // set init flag
2170 +        lock.unlock();
2171      }
2172  
2173      // Execution methods
# Line 2004 | Line 2189 | public class ForkJoinPool extends Abstra
2189       *         scheduled for execution
2190       */
2191      public <T> T invoke(ForkJoinTask<T> task) {
2192 +        if (task == null)
2193 +            throw new NullPointerException();
2194          doSubmit(task);
2195          return task.join();
2196      }
# Line 2017 | Line 2204 | public class ForkJoinPool extends Abstra
2204       *         scheduled for execution
2205       */
2206      public void execute(ForkJoinTask<?> task) {
2207 +        if (task == null)
2208 +            throw new NullPointerException();
2209          doSubmit(task);
2210      }
2211  
# Line 2034 | Line 2223 | public class ForkJoinPool extends Abstra
2223          if (task instanceof ForkJoinTask<?>) // avoid re-wrap
2224              job = (ForkJoinTask<?>) task;
2225          else
2226 <            job = ForkJoinTask.adapt(task, null);
2226 >            job = new ForkJoinTask.AdaptedRunnableAction(task);
2227          doSubmit(job);
2228      }
2229  
# Line 2048 | Line 2237 | public class ForkJoinPool extends Abstra
2237       *         scheduled for execution
2238       */
2239      public <T> ForkJoinTask<T> submit(ForkJoinTask<T> task) {
2240 +        if (task == null)
2241 +            throw new NullPointerException();
2242          doSubmit(task);
2243          return task;
2244      }
# Line 2058 | Line 2249 | public class ForkJoinPool extends Abstra
2249       *         scheduled for execution
2250       */
2251      public <T> ForkJoinTask<T> submit(Callable<T> task) {
2252 <        if (task == null)
2062 <            throw new NullPointerException();
2063 <        ForkJoinTask<T> job = ForkJoinTask.adapt(task);
2252 >        ForkJoinTask<T> job = new ForkJoinTask.AdaptedCallable<T>(task);
2253          doSubmit(job);
2254          return job;
2255      }
# Line 2071 | Line 2260 | public class ForkJoinPool extends Abstra
2260       *         scheduled for execution
2261       */
2262      public <T> ForkJoinTask<T> submit(Runnable task, T result) {
2263 <        if (task == null)
2075 <            throw new NullPointerException();
2076 <        ForkJoinTask<T> job = ForkJoinTask.adapt(task, result);
2263 >        ForkJoinTask<T> job = new ForkJoinTask.AdaptedRunnable<T>(task, result);
2264          doSubmit(job);
2265          return job;
2266      }
# Line 2090 | Line 2277 | public class ForkJoinPool extends Abstra
2277          if (task instanceof ForkJoinTask<?>) // avoid re-wrap
2278              job = (ForkJoinTask<?>) task;
2279          else
2280 <            job = ForkJoinTask.adapt(task, null);
2280 >            job = new ForkJoinTask.AdaptedRunnableAction(task);
2281          doSubmit(job);
2282          return job;
2283      }
# Line 2112 | Line 2299 | public class ForkJoinPool extends Abstra
2299          boolean done = false;
2300          try {
2301              for (Callable<T> t : tasks) {
2302 <                ForkJoinTask<T> f = ForkJoinTask.adapt(t);
2302 >                ForkJoinTask<T> f = new ForkJoinTask.AdaptedCallable<T>(t);
2303                  doSubmit(f);
2304                  fs.add(f);
2305              }
# Line 2298 | Line 2485 | public class ForkJoinPool extends Abstra
2485          WorkQueue[] ws; WorkQueue w;
2486          if ((ws = workQueues) != null) {
2487              for (int i = 0; i < ws.length; i += 2) {
2488 <                if ((w = ws[i]) != null && w.queueSize() != 0)
2488 >                if ((w = ws[i]) != null && !w.isEmpty())
2489                      return true;
2490              }
2491          }
# Line 2612 | Line 2799 | public class ForkJoinPool extends Abstra
2799          ForkJoinPool p = ((t instanceof ForkJoinWorkerThread) ?
2800                            ((ForkJoinWorkerThread)t).pool : null);
2801          while (!blocker.isReleasable()) {
2802 <            if (p == null || p.tryCompensate()) {
2802 >            if (p == null || p.tryCompensate(null, blocker)) {
2803                  try {
2804                      do {} while (!blocker.isReleasable() && !blocker.block());
2805                  } finally {
# Line 2629 | Line 2816 | public class ForkJoinPool extends Abstra
2816      // implement RunnableFuture.
2817  
2818      protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
2819 <        return (RunnableFuture<T>) ForkJoinTask.adapt(runnable, value);
2819 >        return new ForkJoinTask.AdaptedRunnable<T>(runnable, value);
2820      }
2821  
2822      protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
2823 <        return (RunnableFuture<T>) ForkJoinTask.adapt(callable);
2823 >        return new ForkJoinTask.AdaptedCallable<T>(callable);
2824      }
2825  
2826      // Unsafe mechanics
2827      private static final sun.misc.Unsafe U;
2828      private static final long CTL;
2829      private static final long PARKBLOCKER;
2830 +    private static final int ABASE;
2831 +    private static final int ASHIFT;
2832  
2833      static {
2834          poolNumberGenerator = new AtomicInteger();
2835 +        nextSubmitterSeed = new AtomicInteger(0x55555555);
2836          modifyThreadPermission = new RuntimePermission("modifyThread");
2837          defaultForkJoinWorkerThreadFactory =
2838              new DefaultForkJoinWorkerThreadFactory();
2839          submitters = new ThreadSubmitter();
2840 +        int s;
2841          try {
2842              U = getUnsafe();
2843              Class<?> k = ForkJoinPool.class;
2844 +            Class<?> ak = ForkJoinTask[].class;
2845              CTL = U.objectFieldOffset
2846                  (k.getDeclaredField("ctl"));
2847              Class<?> tk = Thread.class;
2848              PARKBLOCKER = U.objectFieldOffset
2849                  (tk.getDeclaredField("parkBlocker"));
2850 +            ABASE = U.arrayBaseOffset(ak);
2851 +            s = U.arrayIndexScale(ak);
2852          } catch (Exception e) {
2853              throw new Error(e);
2854          }
2855 +        if ((s & (s-1)) != 0)
2856 +            throw new Error("data type scale not a power of two");
2857 +        ASHIFT = 31 - Integer.numberOfLeadingZeros(s);
2858      }
2859  
2860      /**

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines