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.126 by jsr166, Tue Feb 21 00:44:53 2012 UTC vs.
Revision 1.139 by dl, Wed Oct 31 12:49:24 2012 UTC

# Line 5 | Line 5
5   */
6  
7   package jsr166y;
8 +
9   import java.util.ArrayList;
10   import java.util.Arrays;
11   import java.util.Collection;
# Line 41 | Line 42 | import java.util.concurrent.locks.Condit
42   * ForkJoinPool}s may also be appropriate for use with event-style
43   * tasks that are never joined.
44   *
45 < * <p>A {@code ForkJoinPool} is constructed with a given target
46 < * parallelism level; by default, equal to the number of available
47 < * processors. The pool attempts to maintain enough active (or
48 < * available) threads by dynamically adding, suspending, or resuming
49 < * internal worker threads, even if some tasks are stalled waiting to
50 < * join others. However, no such adjustments are guaranteed in the
51 < * face of blocked IO or other unmanaged synchronization. The nested
52 < * {@link ManagedBlocker} interface enables extension of the kinds of
45 > * <p>A static {@link #commonPool} is available and appropriate for
46 > * most applications. The common pool is used by any ForkJoinTask that
47 > * is not explicitly submitted to a specified pool. Using the common
48 > * pool normally reduces resource usage (its threads are slowly
49 > * reclaimed during periods of non-use, and reinstated upon subsequent
50 > * use).  The common pool is by default constructed with default
51 > * parameters, but these may be controlled by setting any or all of
52 > * the three properties {@code
53 > * java.util.concurrent.ForkJoinPool.common.{parallelism,
54 > * threadFactory, exceptionHandler}}.
55 > *
56 > * <p>For applications that require separate or custom pools, a {@code
57 > * ForkJoinPool} may be constructed with a given target parallelism
58 > * level; by default, equal to the number of available processors. The
59 > * pool attempts to maintain enough active (or available) threads by
60 > * dynamically adding, suspending, or resuming internal worker
61 > * threads, even if some tasks are stalled waiting to join
62 > * others. However, no such adjustments are guaranteed in the face of
63 > * blocked IO or other unmanaged synchronization. The nested {@link
64 > * ManagedBlocker} interface enables extension of the kinds of
65   * synchronization accommodated.
66   *
67   * <p>In addition to execution and lifecycle control methods, this
# Line 93 | Line 106 | import java.util.concurrent.locks.Condit
106   *  </tr>
107   * </table>
108   *
96 * <p><b>Sample Usage.</b> Normally a single {@code ForkJoinPool} is
97 * used for all parallel task execution in a program or subsystem.
98 * Otherwise, use would not usually outweigh the construction and
99 * bookkeeping overhead of creating a large set of threads. For
100 * example, a common pool could be used for the {@code SortTasks}
101 * illustrated in {@link RecursiveAction}. Because {@code
102 * ForkJoinPool} uses threads in {@linkplain java.lang.Thread#isDaemon
103 * daemon} mode, there is typically no need to explicitly {@link
104 * #shutdown} such a pool upon program exit.
105 *
106 *  <pre> {@code
107 * static final ForkJoinPool mainPool = new ForkJoinPool();
108 * ...
109 * public void sort(long[] array) {
110 *   mainPool.invoke(new SortTask(array, 0, array.length));
111 * }}</pre>
112 *
109   * <p><b>Implementation notes</b>: This implementation restricts the
110   * maximum number of running threads to 32767. Attempts to create
111   * pools with greater than the maximum number result in
# Line 239 | Line 235 | public class ForkJoinPool extends Abstra
235       * when locked remains available to check consistency.
236       *
237       * Recording WorkQueues.  WorkQueues are recorded in the
238 <     * "workQueues" array that is created upon pool construction and
239 <     * expanded if necessary.  Updates to the array while recording
240 <     * new workers and unrecording terminated ones are protected from
241 <     * each other by a lock but the array is otherwise concurrently
242 <     * readable, and accessed directly.  To simplify index-based
243 <     * operations, the array size is always a power of two, and all
244 <     * readers must tolerate null slots. Shared (submission) queues
245 <     * are at even indices, worker queues at odd indices. Grouping
246 <     * them together in this way simplifies and speeds up task
251 <     * scanning.
238 >     * "workQueues" array that is created upon first use and expanded
239 >     * if necessary.  Updates to the array while recording new workers
240 >     * and unrecording terminated ones are protected from each other
241 >     * by a lock but the array is otherwise concurrently readable, and
242 >     * accessed directly.  To simplify index-based operations, the
243 >     * array size is always a power of two, and all readers must
244 >     * tolerate null slots. Shared (submission) queues are at even
245 >     * indices, worker queues at odd indices. Grouping them together
246 >     * in this way simplifies and speeds up task scanning.
247       *
248       * All worker thread creation is on-demand, triggered by task
249       * submissions, replacement of terminated workers, and/or
# Line 320 | Line 315 | public class ForkJoinPool extends Abstra
315       *
316       * Trimming workers. To release resources after periods of lack of
317       * use, a worker starting to wait when the pool is quiescent will
318 <     * time out and terminate if the pool has remained quiescent for
319 <     * SHRINK_RATE nanosecs. This will slowly propagate, eventually
320 <     * terminating all workers after long periods of non-use.
318 >     * time out and terminate if the pool has remained quiescent for a
319 >     * given period -- a short period if there are more threads than
320 >     * parallelism, longer as the number of threads decreases. This
321 >     * will slowly propagate, eventually terminating all workers after
322 >     * periods of non-use.
323       *
324       * Shutdown and Termination. A call to shutdownNow atomically sets
325       * a runState bit and then (non-atomically) sets each worker's
# Line 504 | Line 501 | public class ForkJoinPool extends Abstra
501      }
502  
503      /**
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    /**
504       * Class for artificial tasks that are used to replace the target
505       * of local joins if they are removed from an interior queue slot
506       * in WorkQueue.tryRemoveAndExec. We don't need the proxy to
# Line 629 | Line 603 | public class ForkJoinPool extends Abstra
603          final ForkJoinPool pool;   // the containing pool (may be null)
604          final ForkJoinWorkerThread owner; // owning thread or null if shared
605          volatile Thread parker;    // == owner during call to park; else null
606 <        ForkJoinTask<?> currentJoin;  // task being joined in awaitJoin
606 >        volatile ForkJoinTask<?> currentJoin;  // task being joined in awaitJoin
607          ForkJoinTask<?> currentSteal; // current non-local task being executed
608          // Heuristic padding to ameliorate unfortunate memory placements
609          Object p00, p01, p02, p03, p04, p05, p06, p07;
# Line 717 | Line 691 | public class ForkJoinPool extends Abstra
691  
692          /**
693           * Takes next task, if one exists, in LIFO order.  Call only
694 <         * by owner in unshared queues. (We do not have a shared
721 <         * version of this method because it is never needed.)
694 >         * by owner in unshared queues.
695           */
696          final ForkJoinTask<?> pop() {
697 <            ForkJoinTask<?> t; int m;
698 <            ForkJoinTask<?>[] a = array;
726 <            if (a != null && (m = a.length - 1) >= 0) {
697 >            ForkJoinTask<?>[] a; ForkJoinTask<?> t; int m;
698 >            if ((a = array) != null && (m = a.length - 1) >= 0) {
699                  for (int s; (s = top - 1) - base >= 0;) {
700 <                    int j = ((m & s) << ASHIFT) + ABASE;
701 <                    if ((t = (ForkJoinTask<?>)U.getObjectVolatile(a, j)) == null)
700 >                    long j = ((m & s) << ASHIFT) + ABASE;
701 >                    if ((t = (ForkJoinTask<?>)U.getObject(a, j)) == null)
702                          break;
703                      if (U.compareAndSwapObject(a, j, t, null)) {
704                          top = s;
# Line 737 | Line 709 | public class ForkJoinPool extends Abstra
709              return null;
710          }
711  
712 +        final ForkJoinTask<?> sharedPop() {
713 +            ForkJoinTask<?> task = null;
714 +            if (runState == 0 && U.compareAndSwapInt(this, RUNSTATE, 0, 1)) {
715 +                try {
716 +                    ForkJoinTask<?>[] a; int m;
717 +                    if ((a = array) != null && (m = a.length - 1) >= 0) {
718 +                        for (int s; (s = top - 1) - base >= 0;) {
719 +                            long j = ((m & s) << ASHIFT) + ABASE;
720 +                            ForkJoinTask<?> t =
721 +                                (ForkJoinTask<?>)U.getObject(a, j);
722 +                            if (t == null)
723 +                                break;
724 +                            if (U.compareAndSwapObject(a, j, t, null)) {
725 +                                top = s;
726 +                                task = t;
727 +                                break;
728 +                            }
729 +                        }
730 +                    }
731 +                } finally {
732 +                    runState = 0;
733 +                }
734 +            }
735 +            return task;
736 +        }
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
# Line 814 | Line 813 | public class ForkJoinPool extends Abstra
813          }
814  
815          /**
816 +         * Version of tryUnpush for shared queues; called by non-FJ
817 +         * submitters after prechecking that task probably exists.
818 +         */
819 +        final boolean trySharedUnpush(ForkJoinTask<?> t) {
820 +            boolean success = false;
821 +            if (runState == 0 && U.compareAndSwapInt(this, RUNSTATE, 0, 1)) {
822 +                try {
823 +                    ForkJoinTask<?>[] a; int s;
824 +                    if ((a = array) != null && (s = top) != base &&
825 +                        U.compareAndSwapObject
826 +                        (a, (((a.length - 1) & --s) << ASHIFT) + ABASE, t, null)) {
827 +                        top = s;
828 +                        success = true;
829 +                    }
830 +                } finally {
831 +                    runState = 0;                         // unlock
832 +                }
833 +            }
834 +            return success;
835 +        }
836 +
837 +        /**
838           * Polls the given task only if it is at the current base.
839           */
840          final boolean pollFor(ForkJoinTask<?> task) {
# Line 830 | Line 851 | public class ForkJoinPool extends Abstra
851          }
852  
853          /**
833         * If present, removes from queue and executes the given task, or
834         * any other cancelled task. Returns (true) immediately on any CAS
835         * or consistency check failure so caller can retry.
836         *
837         * @return false if no progress can be made
838         */
839        final boolean tryRemoveAndExec(ForkJoinTask<?> task) {
840            boolean removed = false, empty = true, progress = true;
841            ForkJoinTask<?>[] a; int m, s, b, n;
842            if ((a = array) != null && (m = a.length - 1) >= 0 &&
843                (n = (s = top) - (b = base)) > 0) {
844                for (ForkJoinTask<?> t;;) {           // traverse from s to b
845                    int j = ((--s & m) << ASHIFT) + ABASE;
846                    t = (ForkJoinTask<?>)U.getObjectVolatile(a, j);
847                    if (t == null)                    // inconsistent length
848                        break;
849                    else if (t == task) {
850                        if (s + 1 == top) {           // pop
851                            if (!U.compareAndSwapObject(a, j, task, null))
852                                break;
853                            top = s;
854                            removed = true;
855                        }
856                        else if (base == b)           // replace with proxy
857                            removed = U.compareAndSwapObject(a, j, task,
858                                                             new EmptyTask());
859                        break;
860                    }
861                    else if (t.status >= 0)
862                        empty = false;
863                    else if (s + 1 == top) {          // pop and throw away
864                        if (U.compareAndSwapObject(a, j, t, null))
865                            top = s;
866                        break;
867                    }
868                    if (--n == 0) {
869                        if (!empty && base == b)
870                            progress = false;
871                        break;
872                    }
873                }
874            }
875            if (removed)
876                task.doExec();
877            return progress;
878        }
879
880        /**
854           * Initializes or doubles the capacity of array. Call either
855           * by owner or with lock held -- it is OK for base, but not
856           * top, to move while resizings are in progress.
# Line 936 | Line 909 | public class ForkJoinPool extends Abstra
909              return seed = r ^= r << 5;
910          }
911  
912 <        // Execution methods
912 >        // Specialized execution methods
913  
914          /**
915 <         * Removes and runs tasks until empty, using local mode
943 <         * ordering. Normally called only after checking for apparent
944 <         * non-emptiness.
915 >         * Pops and runs tasks until empty.
916           */
917 <        final void runLocalTasks() {
918 <            // hoist checks from repeated pop/poll
919 <            ForkJoinTask<?>[] a; int m;
920 <            if ((a = array) != null && (m = a.length - 1) >= 0) {
921 <                if (mode == 0) {
922 <                    for (int s; (s = top - 1) - base >= 0;) {
923 <                        int j = ((m & s) << ASHIFT) + ABASE;
924 <                        ForkJoinTask<?> t =
925 <                            (ForkJoinTask<?>)U.getObjectVolatile(a, j);
926 <                        if (t != null) {
927 <                            if (U.compareAndSwapObject(a, j, t, null)) {
928 <                                top = s;
929 <                                t.doExec();
930 <                            }
917 >        private void popAndExecAll() {
918 >            // A bit faster than repeated pop calls
919 >            ForkJoinTask<?>[] a; int m, s; long j; ForkJoinTask<?> t;
920 >            while ((a = array) != null && (m = a.length - 1) >= 0 &&
921 >                   (s = top - 1) - base >= 0 &&
922 >                   (t = ((ForkJoinTask<?>)
923 >                         U.getObject(a, j = ((m & s) << ASHIFT) + ABASE)))
924 >                   != null) {
925 >                if (U.compareAndSwapObject(a, j, t, null)) {
926 >                    top = s;
927 >                    t.doExec();
928 >                }
929 >            }
930 >        }
931 >
932 >        /**
933 >         * Polls and runs tasks until empty.
934 >         */
935 >        private void pollAndExecAll() {
936 >            for (ForkJoinTask<?> t; (t = poll()) != null;)
937 >                t.doExec();
938 >        }
939 >
940 >        /**
941 >         * If present, removes from queue and executes the given task, or
942 >         * any other cancelled task. Returns (true) immediately on any CAS
943 >         * or consistency check failure so caller can retry.
944 >         *
945 >         * @return 0 if no progress can be made, else positive
946 >         * (this unusual convention simplifies use with tryHelpStealer.)
947 >         */
948 >        final int tryRemoveAndExec(ForkJoinTask<?> task) {
949 >            int stat = 1;
950 >            boolean removed = false, empty = true;
951 >            ForkJoinTask<?>[] a; int m, s, b, n;
952 >            if ((a = array) != null && (m = a.length - 1) >= 0 &&
953 >                (n = (s = top) - (b = base)) > 0) {
954 >                for (ForkJoinTask<?> t;;) {           // traverse from s to b
955 >                    int j = ((--s & m) << ASHIFT) + ABASE;
956 >                    t = (ForkJoinTask<?>)U.getObjectVolatile(a, j);
957 >                    if (t == null)                    // inconsistent length
958 >                        break;
959 >                    else if (t == task) {
960 >                        if (s + 1 == top) {           // pop
961 >                            if (!U.compareAndSwapObject(a, j, task, null))
962 >                                break;
963 >                            top = s;
964 >                            removed = true;
965                          }
966 <                        else
967 <                            break;
966 >                        else if (base == b)           // replace with proxy
967 >                            removed = U.compareAndSwapObject(a, j, task,
968 >                                                             new EmptyTask());
969 >                        break;
970 >                    }
971 >                    else if (t.status >= 0)
972 >                        empty = false;
973 >                    else if (s + 1 == top) {          // pop and throw away
974 >                        if (U.compareAndSwapObject(a, j, t, null))
975 >                            top = s;
976 >                        break;
977 >                    }
978 >                    if (--n == 0) {
979 >                        if (!empty && base == b)
980 >                            stat = 0;
981 >                        break;
982                      }
983                  }
984 <                else {
985 <                    for (int b; (b = base) - top < 0;) {
986 <                        int j = ((m & b) << ASHIFT) + ABASE;
987 <                        ForkJoinTask<?> t =
988 <                            (ForkJoinTask<?>)U.getObjectVolatile(a, j);
989 <                        if (t != null) {
990 <                            if (base == b &&
991 <                                U.compareAndSwapObject(a, j, t, null)) {
992 <                                base = b + 1;
993 <                                t.doExec();
994 <                            }
995 <                        } else if (base == b) {
996 <                            if (b + 1 == top)
984 >            }
985 >            if (removed)
986 >                task.doExec();
987 >            return stat;
988 >        }
989 >
990 >        /**
991 >         * Version of shared pop that takes top element only if it
992 >         * its root is the given CountedCompleter.
993 >         */
994 >        final CountedCompleter<?> sharedPopCC(CountedCompleter<?> root) {
995 >            CountedCompleter<?> task = null;
996 >            if (runState == 0 && U.compareAndSwapInt(this, RUNSTATE, 0, 1)) {
997 >                try {
998 >                    ForkJoinTask<?>[] a; int m;
999 >                    if ((a = array) != null && (m = a.length - 1) >= 0) {
1000 >                        outer:for (int s; (s = top - 1) - base >= 0;) {
1001 >                            long j = ((m & s) << ASHIFT) + ABASE;
1002 >                            ForkJoinTask<?> t =
1003 >                                (ForkJoinTask<?>)U.getObject(a, j);
1004 >                            if (t == null || !(t instanceof CountedCompleter))
1005                                  break;
1006 <                            Thread.yield(); // wait for lagging update
1006 >                            CountedCompleter<?> cc = (CountedCompleter<?>)t;
1007 >                            for (CountedCompleter<?> q = cc, p;;) {
1008 >                                if (q == root) {
1009 >                                    if (U.compareAndSwapObject(a, j, cc, null)) {
1010 >                                        top = s;
1011 >                                        task = cc;
1012 >                                        break outer;
1013 >                                    }
1014 >                                    break;
1015 >                                }
1016 >                                if ((p = q.completer) == null)
1017 >                                    break outer;
1018 >                                q = p;
1019 >                            }
1020                          }
1021                      }
1022 +                } finally {
1023 +                    runState = 0;
1024                  }
1025              }
1026 +            return task;
1027          }
1028  
1029          /**
1030           * Executes a top-level task and any local tasks remaining
1031           * after execution.
989         *
990         * @return true unless terminating
1032           */
1033 <        final boolean runTask(ForkJoinTask<?> t) {
993 <            boolean alive = true;
1033 >        final void runTask(ForkJoinTask<?> t) {
1034              if (t != null) {
1035                  currentSteal = t;
1036                  t.doExec();
1037 <                if (top != base)        // conservative guard
1038 <                    runLocalTasks();
1037 >                if (top != base) {       // process remaining local tasks
1038 >                    if (mode == 0)
1039 >                        popAndExecAll();
1040 >                    else
1041 >                        pollAndExecAll();
1042 >                }
1043                  ++nsteals;
1044                  currentSteal = null;
1045              }
1002            else if (runState < 0)      // terminating
1003                alive = false;
1004            return alive;
1046          }
1047  
1048          /**
# Line 1106 | Line 1147 | public class ForkJoinPool extends Abstra
1147      public static final ForkJoinWorkerThreadFactory
1148          defaultForkJoinWorkerThreadFactory;
1149  
1150 +    /** Property prefix for constructing common pool */
1151 +    private static final String propPrefix =
1152 +        "java.util.concurrent.ForkJoinPool.common.";
1153 +
1154 +    /**
1155 +     * Common (static) pool. Non-null for public use unless a static
1156 +     * construction exception, but internal usages must null-check on
1157 +     * use.
1158 +     */
1159 +    static final ForkJoinPool commonPool;
1160 +
1161 +    /**
1162 +     * Common pool parallelism. Must equal commonPool.parallelism.
1163 +     */
1164 +    static final int commonPoolParallelism;
1165 +
1166      /**
1167       * Generator for assigning sequence numbers as pool names.
1168       */
# Line 1124 | Line 1181 | public class ForkJoinPool extends Abstra
1181      private static final RuntimePermission modifyThreadPermission;
1182  
1183      /**
1184 <     * Per-thread submission bookeeping. Shared across all pools
1184 >     * Per-thread submission bookkeeping. Shared across all pools
1185       * to reduce ThreadLocal pollution and because random motion
1186       * to avoid contention in one pool is likely to hold for others.
1187       */
# Line 1133 | Line 1190 | public class ForkJoinPool extends Abstra
1190      // static constants
1191  
1192      /**
1193 <     * The wakeup interval (in nanoseconds) for a worker waiting for a
1194 <     * task when the pool is quiescent to instead try to shrink the
1195 <     * number of workers.  The exact value does not matter too
1139 <     * much. It must be short enough to release resources during
1140 <     * sustained periods of idleness, but not so short that threads
1141 <     * are continually re-created.
1193 >     * Initial timeout value (in nanoseconds) for the thread triggering
1194 >     * quiescence to park waiting for new work. On timeout, the thread
1195 >     * will instead try to shrink the number of workers.
1196       */
1197 <    private static final long SHRINK_RATE =
1144 <        4L * 1000L * 1000L * 1000L; // 4 seconds
1197 >    private static final long IDLE_TIMEOUT      = 1000L * 1000L * 1000L; // 1sec
1198  
1199      /**
1200 <     * The timeout value for attempted shrinkage, includes
1148 <     * some slop to cope with system timer imprecision.
1200 >     * Timeout value when there are more threads than parallelism level
1201       */
1202 <    private static final long SHRINK_TIMEOUT = SHRINK_RATE - (SHRINK_RATE / 10);
1202 >    private static final long FAST_IDLE_TIMEOUT =  100L * 1000L * 1000L;
1203  
1204      /**
1205       * The maximum stolen->joining link depth allowed in method
# Line 1160 | Line 1212 | public class ForkJoinPool extends Abstra
1212       * traversal parameters at the expense of sometimes blocking when
1213       * we could be helping.
1214       */
1215 <    private static final int MAX_HELP = 32;
1215 >    private static final int MAX_HELP = 64;
1216  
1217      /**
1218       * Secondary time-based bound (in nanosecs) for helping attempts
# Line 1170 | Line 1222 | public class ForkJoinPool extends Abstra
1222       * value should roughly approximate the time required to create
1223       * and/or activate a worker thread.
1224       */
1225 <    private static final long COMPENSATION_DELAY = 100L * 1000L; // 0.1 millisec
1225 >    private static final long COMPENSATION_DELAY = 1L << 18; // ~0.25 millisec
1226  
1227      /**
1228       * Increment for seed generators. See class ThreadLocal for
# Line 1267 | Line 1319 | public class ForkJoinPool extends Abstra
1319       * empirically works OK on current JVMs.
1320       */
1321  
1322 +    volatile long stealCount;                  // collects worker counts
1323      volatile long ctl;                         // main pool control
1324      final int parallelism;                     // parallelism level
1325      final int localMode;                       // per-worker scheduling mode
1326 +    volatile int nextWorkerNumber;             // to create worker name string
1327      final int submitMask;                      // submit queue index bound
1328      int nextSeed;                              // for initializing worker seeds
1329 +    volatile int mainLock;                     // spinlock for array updates
1330      volatile int runState;                     // shutdown status and seq
1331      WorkQueue[] workQueues;                    // main registry
1277    final Mutex lock;                          // for registration
1278    final Condition termination;               // for awaitTermination
1332      final ForkJoinWorkerThreadFactory factory; // factory for new workers
1333      final Thread.UncaughtExceptionHandler ueh; // per-worker UEH
1281    final AtomicLong stealCount;               // collect counts when terminated
1282    final AtomicInteger nextWorkerNumber;      // to create worker name string
1334      final String workerNamePrefix;             // to create worker name string
1335  
1336 +    /*
1337 +     * Mechanics for main lock protecting worker array updates.  Uses
1338 +     * the same strategy as ConcurrentHashMap bins -- a spinLock for
1339 +     * normal cases, but falling back to builtin lock when (rarely)
1340 +     * needed.  See internal ConcurrentHashMap documentation for
1341 +     * explanation.
1342 +     */
1343 +
1344 +    static final int LOCK_WAITING = 2; // bit to indicate need for signal
1345 +    static final int MAX_LOCK_SPINS = 1 << 8;
1346 +
1347 +    private void tryAwaitMainLock() {
1348 +        int spins = MAX_LOCK_SPINS, r = 0, h;
1349 +        while (((h = mainLock) & 1) != 0) {
1350 +            if (r == 0)
1351 +                r = ThreadLocalRandom.current().nextInt(); // randomize spins
1352 +            else if (spins >= 0) {
1353 +                r ^= r << 1; r ^= r >>> 3; r ^= r << 10; // xorshift
1354 +                if (r >= 0)
1355 +                    --spins;
1356 +            }
1357 +            else if (U.compareAndSwapInt(this, MAINLOCK, h, h | LOCK_WAITING)) {
1358 +                synchronized (this) {
1359 +                    if ((mainLock & LOCK_WAITING) != 0) {
1360 +                        try {
1361 +                            wait();
1362 +                        } catch (InterruptedException ie) {
1363 +                            try {
1364 +                                Thread.currentThread().interrupt();
1365 +                            } catch (SecurityException ignore) {
1366 +                            }
1367 +                        }
1368 +                    }
1369 +                    else
1370 +                        notifyAll(); // possibly won race vs signaller
1371 +                }
1372 +                break;
1373 +            }
1374 +        }
1375 +    }
1376 +
1377      //  Creating, registering, and deregistering workers
1378  
1379      /**
# Line 1308 | Line 1400 | public class ForkJoinPool extends Abstra
1400       * ForkJoinWorkerThread.
1401       */
1402      final String nextWorkerName() {
1403 <        return workerNamePrefix.concat
1404 <            (Integer.toString(nextWorkerNumber.addAndGet(1)));
1403 >        int n;
1404 >        do {} while (!U.compareAndSwapInt(this, NEXTWORKERNUMBER,
1405 >                                          n = nextWorkerNumber, ++n));
1406 >        return workerNamePrefix.concat(Integer.toString(n));
1407      }
1408  
1409      /**
# Line 1322 | Line 1416 | public class ForkJoinPool extends Abstra
1416       * @param w the worker's queue
1417       */
1418      final void registerWorker(WorkQueue w) {
1419 <        Mutex lock = this.lock;
1420 <        lock.lock();
1419 >        while (!U.compareAndSwapInt(this, MAINLOCK, 0, 1))
1420 >            tryAwaitMainLock();
1421          try {
1422 <            WorkQueue[] ws = workQueues;
1423 <            if (w != null && ws != null) {          // skip on shutdown/failure
1424 <                int rs, n;
1425 <                while ((n = ws.length) <            // ensure can hold total
1426 <                       (parallelism + (short)(ctl >>> TC_SHIFT) << 1))
1333 <                    workQueues = ws = Arrays.copyOf(ws, n << 1);
1334 <                int m = n - 1;
1422 >            WorkQueue[] ws;
1423 >            if ((ws = workQueues) == null)
1424 >                ws = workQueues = new WorkQueue[submitMask + 1];
1425 >            if (w != null) {
1426 >                int rs, n =  ws.length, m = n - 1;
1427                  int s = nextSeed += SEED_INCREMENT; // rarely-colliding sequence
1428                  w.seed = (s == 0) ? 1 : s;          // ensure non-zero seed
1429                  int r = (s << 1) | 1;               // use odd-numbered indices
1430 <                while (ws[r &= m] != null)          // step by approx half size
1431 <                    r += ((n >>> 1) & SQMASK) + 2;
1430 >                if (ws[r &= m] != null) {           // collision
1431 >                    int probes = 0;                 // step by approx half size
1432 >                    int step = (n <= 4) ? 2 : ((n >>> 1) & SQMASK) + 2;
1433 >                    while (ws[r = (r + step) & m] != null) {
1434 >                        if (++probes >= n) {
1435 >                            workQueues = ws = Arrays.copyOf(ws, n <<= 1);
1436 >                            m = n - 1;
1437 >                            probes = 0;
1438 >                        }
1439 >                    }
1440 >                }
1441                  w.eventCount = w.poolIndex = r;     // establish before recording
1442                  ws[r] = w;                          // also update seq
1443                  runState = ((rs = runState) & SHUTDOWN) | ((rs + 2) & ~SHUTDOWN);
1444              }
1445          } finally {
1446 <            lock.unlock();
1446 >            if (!U.compareAndSwapInt(this, MAINLOCK, 1, 0)) {
1447 >                mainLock = 0;
1448 >                synchronized (this) { notifyAll(); };
1449 >            }
1450          }
1451      }
1452  
# Line 1356 | Line 1460 | public class ForkJoinPool extends Abstra
1460       * @param ex the exception causing failure, or null if none
1461       */
1462      final void deregisterWorker(ForkJoinWorkerThread wt, Throwable ex) {
1359        Mutex lock = this.lock;
1463          WorkQueue w = null;
1464          if (wt != null && (w = wt.workQueue) != null) {
1465              w.runState = -1;                // ensure runState is set
1466 <            stealCount.getAndAdd(w.totalSteals + w.nsteals);
1466 >            long steals = w.totalSteals + w.nsteals, sc;
1467 >            do {} while (!U.compareAndSwapLong(this, STEALCOUNT,
1468 >                                               sc = stealCount, sc + steals));
1469              int idx = w.poolIndex;
1470 <            lock.lock();
1471 <            try {                           // remove record from array
1470 >            while (!U.compareAndSwapInt(this, MAINLOCK, 0, 1))
1471 >                tryAwaitMainLock();
1472 >            try {
1473                  WorkQueue[] ws = workQueues;
1474                  if (ws != null && idx >= 0 && idx < ws.length && ws[idx] == w)
1475                      ws[idx] = null;
1476              } finally {
1477 <                lock.unlock();
1477 >                if (!U.compareAndSwapInt(this, MAINLOCK, 1, 0)) {
1478 >                    mainLock = 0;
1479 >                    synchronized (this) { notifyAll(); };
1480 >                }
1481              }
1482          }
1483  
# Line 1387 | Line 1496 | public class ForkJoinPool extends Abstra
1496          }
1497  
1498          if (ex != null)                     // rethrow
1499 <            U.throwException(ex);
1499 >            ForkJoinTask.rethrow(ex);
1500      }
1501  
1393
1502      // Submissions
1503  
1504      /**
# Line 1408 | Line 1516 | public class ForkJoinPool extends Abstra
1516          for (int r = s.seed, m = submitMask;;) {
1517              WorkQueue[] ws; WorkQueue q;
1518              int k = r & m & SQMASK;          // use only even indices
1519 <            if (runState < 0 || (ws = workQueues) == null || ws.length <= k)
1519 >            if (runState < 0)
1520                  throw new RejectedExecutionException(); // shutting down
1521 +            else if ((ws = workQueues) == null || ws.length <= k) {
1522 +                while (!U.compareAndSwapInt(this, MAINLOCK, 0, 1))
1523 +                    tryAwaitMainLock();
1524 +                try {
1525 +                    if (workQueues == null)
1526 +                        workQueues = new WorkQueue[submitMask + 1];
1527 +                } finally {
1528 +                    if (!U.compareAndSwapInt(this, MAINLOCK, 1, 0)) {
1529 +                        mainLock = 0;
1530 +                        synchronized (this) { notifyAll(); };
1531 +                    }
1532 +                }
1533 +            }
1534              else if ((q = ws[k]) == null) {  // create new queue
1535                  WorkQueue nq = new WorkQueue(this, null, SHARED_QUEUE);
1536 <                Mutex lock = this.lock;      // construct outside lock
1537 <                lock.lock();
1538 <                try {                        // recheck under lock
1536 >                while (!U.compareAndSwapInt(this, MAINLOCK, 0, 1))
1537 >                    tryAwaitMainLock();
1538 >                try {
1539                      int rs = runState;       // to update seq
1540                      if (ws == workQueues && ws[k] == null) {
1541                          ws[k] = nq;
1542                          runState = ((rs & SHUTDOWN) | ((rs + 2) & ~SHUTDOWN));
1543                      }
1544                  } finally {
1545 <                    lock.unlock();
1545 >                    if (!U.compareAndSwapInt(this, MAINLOCK, 1, 0)) {
1546 >                        mainLock = 0;
1547 >                        synchronized (this) { notifyAll(); };
1548 >                    }
1549                  }
1550              }
1551              else if (q.trySharedPush(task)) {
# Line 1438 | Line 1562 | public class ForkJoinPool extends Abstra
1562          }
1563      }
1564  
1565 +    /**
1566 +     * Submits the given (non-null) task to the common pool, if possible.
1567 +     */
1568 +    static void submitToCommonPool(ForkJoinTask<?> task) {
1569 +        ForkJoinPool p;
1570 +        if ((p = commonPool) == null)
1571 +            throw new RejectedExecutionException("Common Pool Unavailable");
1572 +        p.doSubmit(task);
1573 +    }
1574 +
1575 +    /**
1576 +     * Returns true if the given task was submitted to common pool
1577 +     * and has not yet commenced execution, and is available for
1578 +     * removal according to execution policies; if so removing the
1579 +     * submission from the pool.
1580 +     *
1581 +     * @param task the task
1582 +     * @return true if successful
1583 +     */
1584 +    static boolean tryUnsubmitFromCommonPool(ForkJoinTask<?> task) {
1585 +        // If not oversaturating platform, peek, looking for task and
1586 +        // eligibility before using trySharedUnpush to actually take
1587 +        // it under lock
1588 +        ForkJoinPool p; WorkQueue[] ws; WorkQueue w, q;
1589 +        ForkJoinTask<?>[] a; int ac, s, m;
1590 +        if ((p = commonPool) != null && (ws = p.workQueues) != null) {
1591 +            int k = submitters.get().seed & p.submitMask & SQMASK;
1592 +            if ((m = ws.length - 1) >= k && (q = ws[k]) != null &&
1593 +                (ac = (int)(p.ctl >> AC_SHIFT)) <= 0) {
1594 +                if (ac == 0) { // double check if all workers active
1595 +                    for (int i = 1; i <= m; i += 2) {
1596 +                        if ((w = ws[i]) != null && w.parker != null) {
1597 +                            ac = -1;
1598 +                            break;
1599 +                        }
1600 +                    }
1601 +                }
1602 +                return (ac < 0 && (a = q.array) != null &&
1603 +                        (s = q.top - 1) - q.base >= 0 &&
1604 +                        s >= 0 && s < a.length &&
1605 +                        a[s] == task &&
1606 +                        q.trySharedUnpush(task));
1607 +            }
1608 +        }
1609 +        return false;
1610 +    }
1611 +
1612 +    /**
1613 +     * Tries to pop and run a task within same computation from common pool
1614 +     */
1615 +    static void popAndExecCCFromCommonPool(CountedCompleter<?> cc) {
1616 +        ForkJoinPool p; WorkQueue[] ws; WorkQueue q, w; int m, ac;
1617 +        CountedCompleter<?> par, task;
1618 +        if ((p = commonPool) != null && (ws = p.workQueues) != null) {
1619 +            while ((par = cc.completer) != null) // find root
1620 +                cc = par;
1621 +            int k = submitters.get().seed & p.submitMask & SQMASK;
1622 +            if ((m = ws.length - 1) >= k && (q = ws[k]) != null &&
1623 +                (ac = (int)(p.ctl >> AC_SHIFT)) <= 0) {
1624 +                if (ac == 0) {
1625 +                    for (int i = 1; i <= m; i += 2) {
1626 +                        if ((w = ws[i]) != null && w.parker != null) {
1627 +                            ac = -1;
1628 +                            break;
1629 +                        }
1630 +                    }
1631 +                }
1632 +                if (ac < 0 && q.top - q.base > 0 &&
1633 +                    (task = q.sharedPopCC(cc)) != null)
1634 +                    task.exec();
1635 +            }
1636 +        }
1637 +    }
1638 +
1639      // Maintaining ctl counts
1640  
1641      /**
# Line 1449 | Line 1647 | public class ForkJoinPool extends Abstra
1647      }
1648  
1649      /**
1650 <     * Tries to activate or create a worker if too few are active.
1650 >     * Tries to create one or activate one or more workers if too few are active.
1651       */
1652      final void signalWork() {
1653          long c; int u;
# Line 1483 | Line 1681 | public class ForkJoinPool extends Abstra
1681          }
1682      }
1683  
1486
1684      // Scanning for tasks
1685  
1686      /**
# Line 1491 | Line 1688 | public class ForkJoinPool extends Abstra
1688       */
1689      final void runWorker(WorkQueue w) {
1690          w.growArray(false);         // initialize queue array in this thread
1691 <        do {} while (w.runTask(scan(w)));
1691 >        do { w.runTask(scan(w)); } while (w.runState >= 0);
1692      }
1693  
1694      /**
# Line 1534 | Line 1731 | public class ForkJoinPool extends Abstra
1731       * awaiting signal,
1732       *
1733       * @param w the worker (via its WorkQueue)
1734 <     * @return a task or null of none found
1734 >     * @return a task or null if none found
1735       */
1736      private final ForkJoinTask<?> scan(WorkQueue w) {
1737          WorkQueue[] ws;                       // first update random seed
# Line 1551 | Line 1748 | public class ForkJoinPool extends Abstra
1748                      t = (ForkJoinTask<?>)U.getObjectVolatile(a, i);
1749                      if (q.base == b && ec >= 0 && t != null &&
1750                          U.compareAndSwapObject(a, i, t, null)) {
1751 <                        q.base = b + 1;       // specialization of pollAt
1751 >                        if (q.top - (q.base = b + 1) > 0)
1752 >                            signalWork();    // help pushes signal
1753                          return t;
1754                      }
1755 <                    else if ((t != null || b + 1 != q.top) &&
1558 <                             (ec < 0 || j <= m)) {
1755 >                    else if (ec < 0 || j <= m) {
1756                          rs = 0;               // mark scan as imcomplete
1757                          break;                // caller can retry after release
1758                      }
# Line 1563 | Line 1760 | public class ForkJoinPool extends Abstra
1760                  if (--j < 0)
1761                      break;
1762              }
1763 +
1764              long c = ctl; int e = (int)c, a = (int)(c >> AC_SHIFT), nr, ns;
1765              if (e < 0)                        // decode ctl on empty scan
1766                  w.runState = -1;              // pool is terminating
# Line 1596 | Line 1794 | public class ForkJoinPool extends Abstra
1794                  }
1795              }
1796              else if (w.eventCount < 0) {      // already queued
1797 <                if ((nr = w.rescans) > 0) {   // continue rescanning
1798 <                    int ac = a + parallelism;
1799 <                    if (((w.rescans = (ac < nr) ? ac : nr - 1) & 3) == 0)
1800 <                        Thread.yield();       // yield before block
1603 <                }
1604 <                else {
1797 >                int ac = a + parallelism;
1798 >                if ((nr = w.rescans) > 0)     // continue rescanning
1799 >                    w.rescans = (ac < nr) ? ac : nr - 1;
1800 >                else if (((w.seed >>> 16) & ac) == 0) { // randomize park
1801                      Thread.interrupted();     // clear status
1802                      Thread wt = Thread.currentThread();
1803                      U.putObject(wt, PARKBLOCKER, this);
# Line 1619 | Line 1815 | public class ForkJoinPool extends Abstra
1815      /**
1816       * If inactivating worker w has caused the pool to become
1817       * quiescent, checks for pool termination, and, so long as this is
1818 <     * not the only worker, waits for event for up to SHRINK_RATE
1819 <     * nanosecs.  On timeout, if ctl has not changed, terminates the
1818 >     * not the only worker, waits for event for up to a given
1819 >     * duration.  On timeout, if ctl has not changed, terminates the
1820       * worker, which will in turn wake up another worker to possibly
1821       * repeat this process.
1822       *
# Line 1630 | Line 1826 | public class ForkJoinPool extends Abstra
1826       */
1827      private void idleAwaitWork(WorkQueue w, long currentCtl, long prevCtl) {
1828          if (w.eventCount < 0 && !tryTerminate(false, false) &&
1829 <            (int)prevCtl != 0 && ctl == currentCtl) {
1829 >            (int)prevCtl != 0 && !hasQueuedSubmissions() && ctl == currentCtl) {
1830 >            int dc = -(short)(currentCtl >>> TC_SHIFT);
1831 >            long parkTime = dc < 0 ? FAST_IDLE_TIMEOUT: (dc + 1) * IDLE_TIMEOUT;
1832 >            long deadline = System.nanoTime() + parkTime - 100000L; // 1ms slop
1833              Thread wt = Thread.currentThread();
1635            Thread.yield();            // yield before block
1834              while (ctl == currentCtl) {
1637                long startTime = System.nanoTime();
1835                  Thread.interrupted();  // timed variant of version in scan()
1836                  U.putObject(wt, PARKBLOCKER, this);
1837                  w.parker = wt;
1838                  if (ctl == currentCtl)
1839 <                    U.park(false, SHRINK_RATE);
1839 >                    U.park(false, parkTime);
1840                  w.parker = null;
1841                  U.putObject(wt, PARKBLOCKER, null);
1842                  if (ctl != currentCtl)
1843                      break;
1844 <                if (System.nanoTime() - startTime >= SHRINK_TIMEOUT &&
1844 >                if (deadline - System.nanoTime() <= 0L &&
1845                      U.compareAndSwapLong(this, CTL, currentCtl, prevCtl)) {
1846                      w.eventCount = (w.eventCount + E_SEQ) | E_MASK;
1847                      w.runState = -1;   // shrink
# Line 1665 | Line 1862 | public class ForkJoinPool extends Abstra
1862       * leaves hints in workers to speed up subsequent calls. The
1863       * implementation is very branchy to cope with potential
1864       * inconsistencies or loops encountering chains that are stale,
1865 <     * unknown, or so long that they are likely cyclic.  All of these
1669 <     * cases are dealt with by just retrying by caller.
1865 >     * unknown, or so long that they are likely cyclic.
1866       *
1867       * @param joiner the joining worker
1868       * @param task the task to join
1869 <     * @return true if found or ran a task (and so is immediately retryable)
1869 >     * @return 0 if no progress can be made, negative if task
1870 >     * known complete, else positive
1871       */
1872 <    private boolean tryHelpStealer(WorkQueue joiner, ForkJoinTask<?> task) {
1873 <        WorkQueue[] ws;
1874 <        int m, depth = MAX_HELP;                // remaining chain depth
1875 <        boolean progress = false;
1876 <        if ((ws = workQueues) != null && (m = ws.length - 1) > 0 &&
1877 <            task.status >= 0) {
1878 <            ForkJoinTask<?> subtask = task;     // current target
1879 <            outer: for (WorkQueue j = joiner;;) {
1880 <                WorkQueue stealer = null;       // find stealer of subtask
1881 <                WorkQueue v = ws[j.stealHint & m]; // try hint
1882 <                if (v != null && v.currentSteal == subtask)
1883 <                    stealer = v;
1884 <                else {                          // scan
1885 <                    for (int i = 1; i <= m; i += 2) {
1886 <                        if ((v = ws[i]) != null && v.currentSteal == subtask &&
1887 <                            v != joiner) {
1888 <                            stealer = v;
1889 <                            j.stealHint = i;    // save hint
1890 <                            break;
1872 >    private int tryHelpStealer(WorkQueue joiner, ForkJoinTask<?> task) {
1873 >        int stat = 0, steps = 0;                    // bound to avoid cycles
1874 >        if (joiner != null && task != null) {       // hoist null checks
1875 >            restart: for (;;) {
1876 >                ForkJoinTask<?> subtask = task;     // current target
1877 >                for (WorkQueue j = joiner, v;;) {   // v is stealer of subtask
1878 >                    WorkQueue[] ws; int m, s, h;
1879 >                    if ((s = task.status) < 0) {
1880 >                        stat = s;
1881 >                        break restart;
1882 >                    }
1883 >                    if ((ws = workQueues) == null || (m = ws.length - 1) <= 0)
1884 >                        break restart;              // shutting down
1885 >                    if ((v = ws[h = (j.stealHint | 1) & m]) == null ||
1886 >                        v.currentSteal != subtask) {
1887 >                        for (int origin = h;;) {    // find stealer
1888 >                            if (((h = (h + 2) & m) & 15) == 1 &&
1889 >                                (subtask.status < 0 || j.currentJoin != subtask))
1890 >                                continue restart;   // occasional staleness check
1891 >                            if ((v = ws[h]) != null &&
1892 >                                v.currentSteal == subtask) {
1893 >                                j.stealHint = h;    // save hint
1894 >                                break;
1895 >                            }
1896 >                            if (h == origin)
1897 >                                break restart;      // cannot find stealer
1898                          }
1899                      }
1900 <                    if (stealer == null)
1901 <                        break;
1902 <                }
1903 <
1904 <                for (WorkQueue q = stealer;;) { // try to help stealer
1905 <                    ForkJoinTask[] a; ForkJoinTask<?> t; int b;
1906 <                    if (task.status < 0)
1907 <                        break outer;
1908 <                    if ((b = q.base) - q.top < 0 && (a = q.array) != null) {
1909 <                        progress = true;
1910 <                        int i = (((a.length - 1) & b) << ASHIFT) + ABASE;
1911 <                        t = (ForkJoinTask<?>)U.getObjectVolatile(a, i);
1912 <                        if (subtask.status < 0) // must recheck before taking
1913 <                            break outer;
1914 <                        if (t != null &&
1915 <                            q.base == b &&
1916 <                            U.compareAndSwapObject(a, i, t, null)) {
1917 <                            q.base = b + 1;
1918 <                            joiner.runSubtask(t);
1900 >                    for (;;) { // help stealer or descend to its stealer
1901 >                        ForkJoinTask[] a;  int b;
1902 >                        if (subtask.status < 0)     // surround probes with
1903 >                            continue restart;       //   consistency checks
1904 >                        if ((b = v.base) - v.top < 0 && (a = v.array) != null) {
1905 >                            int i = (((a.length - 1) & b) << ASHIFT) + ABASE;
1906 >                            ForkJoinTask<?> t =
1907 >                                (ForkJoinTask<?>)U.getObjectVolatile(a, i);
1908 >                            if (subtask.status < 0 || j.currentJoin != subtask ||
1909 >                                v.currentSteal != subtask)
1910 >                                continue restart;   // stale
1911 >                            stat = 1;               // apparent progress
1912 >                            if (t != null && v.base == b &&
1913 >                                U.compareAndSwapObject(a, i, t, null)) {
1914 >                                v.base = b + 1;     // help stealer
1915 >                                joiner.runSubtask(t);
1916 >                            }
1917 >                            else if (v.base == b && ++steps == MAX_HELP)
1918 >                                break restart;      // v apparently stalled
1919 >                        }
1920 >                        else {                      // empty -- try to descend
1921 >                            ForkJoinTask<?> next = v.currentJoin;
1922 >                            if (subtask.status < 0 || j.currentJoin != subtask ||
1923 >                                v.currentSteal != subtask)
1924 >                                continue restart;   // stale
1925 >                            else if (next == null || ++steps == MAX_HELP)
1926 >                                break restart;      // dead-end or maybe cyclic
1927 >                            else {
1928 >                                subtask = next;
1929 >                                j = v;
1930 >                                break;
1931 >                            }
1932                          }
1716                        else if (q.base == b)
1717                            break outer;        // possibly stalled
1718                    }
1719                    else {                      // descend
1720                        ForkJoinTask<?> next = stealer.currentJoin;
1721                        if (--depth <= 0 || subtask.status < 0 ||
1722                            next == null || next == subtask)
1723                            break outer;        // stale, dead-end, or cyclic
1724                        subtask = next;
1725                        j = stealer;
1726                        break;
1933                      }
1934                  }
1935              }
1936          }
1937 <        return progress;
1937 >        return stat;
1938      }
1939  
1940      /**
# Line 1828 | Line 2034 | public class ForkJoinPool extends Abstra
2034       * @return task status on exit
2035       */
2036      final int awaitJoin(WorkQueue joiner, ForkJoinTask<?> task) {
2037 <        ForkJoinTask<?> prevJoin = joiner.currentJoin;
2038 <        joiner.currentJoin = task;
2039 <        long startTime = 0L;
2040 <        for (int k = 0, s; ; ++k) {
2041 <            if ((joiner.isEmpty() ?                  // try to help
2042 <                 !tryHelpStealer(joiner, task) :
2043 <                 !joiner.tryRemoveAndExec(task))) {
2044 <                if (k == 0) {
2045 <                    startTime = System.nanoTime();
2046 <                    tryPollForAndExec(joiner, task); // check uncommon case
2047 <                }
2048 <                else if ((k & (MAX_HELP - 1)) == 0 &&
2049 <                         System.nanoTime() - startTime >= COMPENSATION_DELAY &&
2050 <                         tryCompensate(task, null)) {
2051 <                    if (task.trySetSignal() && task.status >= 0) {
2052 <                        synchronized (task) {
2053 <                            if (task.status >= 0) {
2054 <                                try {                // see ForkJoinTask
2055 <                                    task.wait();     //  for explanation
2056 <                                } catch (InterruptedException ie) {
2037 >        int s;
2038 >        if ((s = task.status) >= 0) {
2039 >            ForkJoinTask<?> prevJoin = joiner.currentJoin;
2040 >            joiner.currentJoin = task;
2041 >            long startTime = 0L;
2042 >            for (int k = 0;;) {
2043 >                if ((s = (joiner.isEmpty() ?           // try to help
2044 >                          tryHelpStealer(joiner, task) :
2045 >                          joiner.tryRemoveAndExec(task))) == 0 &&
2046 >                    (s = task.status) >= 0) {
2047 >                    if (k == 0) {
2048 >                        startTime = System.nanoTime();
2049 >                        tryPollForAndExec(joiner, task); // check uncommon case
2050 >                    }
2051 >                    else if ((k & (MAX_HELP - 1)) == 0 &&
2052 >                             System.nanoTime() - startTime >=
2053 >                             COMPENSATION_DELAY &&
2054 >                             tryCompensate(task, null)) {
2055 >                        if (task.trySetSignal()) {
2056 >                            synchronized (task) {
2057 >                                if (task.status >= 0) {
2058 >                                    try {                // see ForkJoinTask
2059 >                                        task.wait();     //  for explanation
2060 >                                    } catch (InterruptedException ie) {
2061 >                                    }
2062                                  }
2063 +                                else
2064 +                                    task.notifyAll();
2065                              }
1853                            else
1854                                task.notifyAll();
2066                          }
2067 +                        long c;                          // re-activate
2068 +                        do {} while (!U.compareAndSwapLong
2069 +                                     (this, CTL, c = ctl, c + AC_UNIT));
2070                      }
1857                    long c;                          // re-activate
1858                    do {} while (!U.compareAndSwapLong
1859                                 (this, CTL, c = ctl, c + AC_UNIT));
2071                  }
2072 +                if (s < 0 || (s = task.status) < 0) {
2073 +                    joiner.currentJoin = prevJoin;
2074 +                    break;
2075 +                }
2076 +                else if ((k++ & (MAX_HELP - 1)) == MAX_HELP >>> 1)
2077 +                    Thread.yield();                     // for politeness
2078              }
1862            if ((s = task.status) < 0) {
1863                joiner.currentJoin = prevJoin;
1864                return s;
1865            }
1866            else if ((k & (MAX_HELP - 1)) == MAX_HELP >>> 1)
1867                Thread.yield();                     // for politeness
2079          }
2080 +        return s;
2081      }
2082  
2083      /**
# Line 1882 | Line 2094 | public class ForkJoinPool extends Abstra
2094          while ((s = task.status) >= 0 &&
2095                 (joiner.isEmpty() ?
2096                  tryHelpStealer(joiner, task) :
2097 <                joiner.tryRemoveAndExec(task)))
2097 >                joiner.tryRemoveAndExec(task)) != 0)
2098              ;
2099          return s;
2100      }
# Line 1922 | Line 2134 | public class ForkJoinPool extends Abstra
2134       */
2135      final void helpQuiescePool(WorkQueue w) {
2136          for (boolean active = true;;) {
2137 <            if (w.base - w.top < 0)
2138 <                w.runLocalTasks();  // exhaust local queue
2137 >            ForkJoinTask<?> localTask; // exhaust local queue
2138 >            while ((localTask = w.nextLocalTask()) != null)
2139 >                localTask.doExec();
2140              WorkQueue q = findNonEmptyStealQueue(w);
2141              if (q != null) {
2142                  ForkJoinTask<?> t; int b;
# Line 1955 | Line 2168 | public class ForkJoinPool extends Abstra
2168      }
2169  
2170      /**
2171 +     * Restricted version of helpQuiescePool for non-FJ callers
2172 +     */
2173 +    static void externalHelpQuiescePool() {
2174 +        ForkJoinPool p; WorkQueue[] ws; WorkQueue q, sq;
2175 +        ForkJoinTask<?>[] a; int b;
2176 +        ForkJoinTask<?> t = null;
2177 +        int k = submitters.get().seed & SQMASK;
2178 +        if ((p = commonPool) != null &&
2179 +            (ws = p.workQueues) != null &&
2180 +            ws.length > (k &= p.submitMask) &&
2181 +            (q = ws[k]) != null) {
2182 +            while (q.top - q.base > 0) {
2183 +                if ((t = q.sharedPop()) != null)
2184 +                    break;
2185 +            }
2186 +            if (t == null && (sq = p.findNonEmptyStealQueue(q)) != null &&
2187 +                (b = sq.base) - sq.top < 0)
2188 +                t = sq.pollAt(b);
2189 +            if (t != null)
2190 +                t.doExec();
2191 +        }
2192 +    }
2193 +
2194 +    /**
2195       * Gets and removes a local or stolen task for the given worker.
2196       *
2197       * @return a task, if available
# Line 1987 | Line 2224 | public class ForkJoinPool extends Abstra
2224                  8);
2225      }
2226  
2227 +    /**
2228 +     * Returns approximate submission queue length for the given caller
2229 +     */
2230 +    static int getEstimatedSubmitterQueueLength() {
2231 +        ForkJoinPool p; WorkQueue[] ws; WorkQueue q;
2232 +        int k = submitters.get().seed & SQMASK;
2233 +        return ((p = commonPool) != null && (ws = p.workQueues) != null &&
2234 +                ws.length > (k &= p.submitMask) &&
2235 +                (q = ws[k]) != null) ?
2236 +            q.queueSize() : 0;
2237 +    }
2238 +
2239      //  Termination
2240  
2241      /**
# Line 2004 | Line 2253 | public class ForkJoinPool extends Abstra
2253       * @return true if now terminating or terminated
2254       */
2255      private boolean tryTerminate(boolean now, boolean enable) {
2007        Mutex lock = this.lock;
2256          for (long c;;) {
2257              if (((c = ctl) & STOP_BIT) != 0) {      // already terminating
2258                  if ((short)(c >>> TC_SHIFT) == -parallelism) {
2259 <                    lock.lock();                    // don't need try/finally
2260 <                    termination.signalAll();        // signal when 0 workers
2261 <                    lock.unlock();
2259 >                    synchronized (this) {
2260 >                        notifyAll();                // signal when 0 workers
2261 >                    }
2262                  }
2263                  return true;
2264              }
2265              if (runState >= 0) {                    // not yet enabled
2266                  if (!enable)
2267                      return false;
2268 <                lock.lock();
2269 <                runState |= SHUTDOWN;
2270 <                lock.unlock();
2268 >                while (!U.compareAndSwapInt(this, MAINLOCK, 0, 1))
2269 >                    tryAwaitMainLock();
2270 >                try {
2271 >                    runState |= SHUTDOWN;
2272 >                } finally {
2273 >                    if (!U.compareAndSwapInt(this, MAINLOCK, 1, 0)) {
2274 >                        mainLock = 0;
2275 >                        synchronized (this) { notifyAll(); };
2276 >                    }
2277 >                }
2278              }
2279              if (!now) {                             // check if idle & no tasks
2280                  if ((int)(c >> AC_SHIFT) != -parallelism ||
# Line 2152 | Line 2407 | public class ForkJoinPool extends Abstra
2407          // Use nearest power 2 for workQueues size. See Hackers Delight sec 3.2.
2408          int n = parallelism - 1;
2409          n |= n >>> 1; n |= n >>> 2; n |= n >>> 4; n |= n >>> 8; n |= n >>> 16;
2410 <        int size = (n + 1) << 1;        // #slots = 2*#workers
2156 <        this.submitMask = size - 1;     // room for max # of submit queues
2157 <        this.workQueues = new WorkQueue[size];
2158 <        this.termination = (this.lock = new Mutex()).newCondition();
2159 <        this.stealCount = new AtomicLong();
2160 <        this.nextWorkerNumber = new AtomicInteger();
2410 >        this.submitMask = ((n + 1) << 1) - 1;
2411          int pn = poolNumberGenerator.incrementAndGet();
2412          StringBuilder sb = new StringBuilder("ForkJoinPool-");
2413          sb.append(Integer.toString(pn));
2414          sb.append("-worker-");
2415          this.workerNamePrefix = sb.toString();
2166        lock.lock();
2416          this.runState = 1;              // set init flag
2417 <        lock.unlock();
2417 >    }
2418 >
2419 >    /**
2420 >     * Constructor for common pool, suitable only for static initialization.
2421 >     * Basically the same as above, but uses smallest possible initial footprint.
2422 >     */
2423 >    ForkJoinPool(int parallelism, int submitMask,
2424 >                 ForkJoinWorkerThreadFactory factory,
2425 >                 Thread.UncaughtExceptionHandler handler) {
2426 >        this.factory = factory;
2427 >        this.ueh = handler;
2428 >        this.submitMask = submitMask;
2429 >        this.parallelism = parallelism;
2430 >        long np = (long)(-parallelism);
2431 >        this.ctl = ((np << AC_SHIFT) & AC_MASK) | ((np << TC_SHIFT) & TC_MASK);
2432 >        this.localMode = LIFO_QUEUE;
2433 >        this.workerNamePrefix = "ForkJoinPool.commonPool-worker-";
2434 >        this.runState = 1;
2435 >    }
2436 >
2437 >    /**
2438 >     * Returns the common pool instance.
2439 >     *
2440 >     * @return the common pool instance
2441 >     */
2442 >    public static ForkJoinPool commonPool() {
2443 >        ForkJoinPool p;
2444 >        if ((p = commonPool) == null)
2445 >            throw new Error("Common Pool Unavailable");
2446 >        return p;
2447      }
2448  
2449      // Execution methods
# Line 2341 | Line 2619 | public class ForkJoinPool extends Abstra
2619      }
2620  
2621      /**
2622 +     * Returns the targeted parallelism level of the common pool.
2623 +     *
2624 +     * @return the targeted parallelism level of the common pool
2625 +     */
2626 +    public static int getCommonPoolParallelism() {
2627 +        return commonPoolParallelism;
2628 +    }
2629 +
2630 +    /**
2631       * Returns the number of worker threads that have started but not
2632       * yet terminated.  The result returned by this method may differ
2633       * from {@link #getParallelism} when threads are created to
# Line 2421 | Line 2708 | public class ForkJoinPool extends Abstra
2708       * @return the number of steals
2709       */
2710      public long getStealCount() {
2711 <        long count = stealCount.get();
2711 >        long count = stealCount;
2712          WorkQueue[] ws; WorkQueue w;
2713          if ((ws = workQueues) != null) {
2714              for (int i = 1; i < ws.length; i += 2) {
# Line 2551 | Line 2838 | public class ForkJoinPool extends Abstra
2838      public String toString() {
2839          // Use a single pass through workQueues to collect counts
2840          long qt = 0L, qs = 0L; int rc = 0;
2841 <        long st = stealCount.get();
2841 >        long st = stealCount;
2842          long c = ctl;
2843          WorkQueue[] ws; WorkQueue w;
2844          if ((ws = workQueues) != null) {
# Line 2592 | Line 2879 | public class ForkJoinPool extends Abstra
2879      }
2880  
2881      /**
2882 <     * Initiates an orderly shutdown in which previously submitted
2883 <     * tasks are executed, but no new tasks will be accepted.
2884 <     * Invocation has no additional effect if already shut down.
2885 <     * Tasks that are in the process of being submitted concurrently
2886 <     * during the course of this method may or may not be rejected.
2882 >     * Possibly initiates an orderly shutdown in which previously
2883 >     * submitted tasks are executed, but no new tasks will be
2884 >     * accepted. Invocation has no effect on execution state if this
2885 >     * is the {@link #commonPool}, and no additional effect if
2886 >     * already shut down.  Tasks that are in the process of being
2887 >     * submitted concurrently during the course of this method may or
2888 >     * may not be rejected.
2889       *
2890       * @throws SecurityException if a security manager exists and
2891       *         the caller is not permitted to modify threads
# Line 2605 | Line 2894 | public class ForkJoinPool extends Abstra
2894       */
2895      public void shutdown() {
2896          checkPermission();
2897 <        tryTerminate(false, true);
2897 >        if (this != commonPool)
2898 >            tryTerminate(false, true);
2899      }
2900  
2901      /**
2902 <     * Attempts to cancel and/or stop all tasks, and reject all
2903 <     * subsequently submitted tasks.  Tasks that are in the process of
2904 <     * being submitted or executed concurrently during the course of
2905 <     * this method may or may not be rejected. This method cancels
2906 <     * both existing and unexecuted tasks, in order to permit
2907 <     * termination in the presence of task dependencies. So the method
2908 <     * always returns an empty list (unlike the case for some other
2909 <     * Executors).
2902 >     * Possibly attempts to cancel and/or stop all tasks, and reject
2903 >     * all subsequently submitted tasks.  Invocation has no effect on
2904 >     * execution state if this is the {@link #commonPool}, and no
2905 >     * additional effect if already shut down. Otherwise, tasks that
2906 >     * are in the process of being submitted or executed concurrently
2907 >     * during the course of this method may or may not be
2908 >     * rejected. This method cancels both existing and unexecuted
2909 >     * tasks, in order to permit termination in the presence of task
2910 >     * dependencies. So the method always returns an empty list
2911 >     * (unlike the case for some other Executors).
2912       *
2913       * @return an empty list
2914       * @throws SecurityException if a security manager exists and
# Line 2626 | Line 2918 | public class ForkJoinPool extends Abstra
2918       */
2919      public List<Runnable> shutdownNow() {
2920          checkPermission();
2921 <        tryTerminate(true, true);
2921 >        if (this != commonPool)
2922 >            tryTerminate(true, true);
2923          return Collections.emptyList();
2924      }
2925  
# Line 2683 | Line 2976 | public class ForkJoinPool extends Abstra
2976      public boolean awaitTermination(long timeout, TimeUnit unit)
2977          throws InterruptedException {
2978          long nanos = unit.toNanos(timeout);
2979 <        final Mutex lock = this.lock;
2980 <        lock.lock();
2981 <        try {
2982 <            for (;;) {
2983 <                if (isTerminated())
2984 <                    return true;
2985 <                if (nanos <= 0)
2986 <                    return false;
2987 <                nanos = termination.awaitNanos(nanos);
2979 >        if (isTerminated())
2980 >            return true;
2981 >        long startTime = System.nanoTime();
2982 >        boolean terminated = false;
2983 >        synchronized (this) {
2984 >            for (long waitTime = nanos, millis = 0L;;) {
2985 >                if (terminated = isTerminated() ||
2986 >                    waitTime <= 0L ||
2987 >                    (millis = unit.toMillis(waitTime)) <= 0L)
2988 >                    break;
2989 >                wait(millis);
2990 >                waitTime = nanos - (System.nanoTime() - startTime);
2991              }
2696        } finally {
2697            lock.unlock();
2992          }
2993 +        return terminated;
2994      }
2995  
2996      /**
# Line 2827 | Line 3122 | public class ForkJoinPool extends Abstra
3122      private static final long PARKBLOCKER;
3123      private static final int ABASE;
3124      private static final int ASHIFT;
3125 +    private static final long NEXTWORKERNUMBER;
3126 +    private static final long STEALCOUNT;
3127 +    private static final long MAINLOCK;
3128  
3129      static {
3130          poolNumberGenerator = new AtomicInteger();
# Line 2842 | Line 3140 | public class ForkJoinPool extends Abstra
3140              Class<?> ak = ForkJoinTask[].class;
3141              CTL = U.objectFieldOffset
3142                  (k.getDeclaredField("ctl"));
3143 +            NEXTWORKERNUMBER = U.objectFieldOffset
3144 +                (k.getDeclaredField("nextWorkerNumber"));
3145 +            STEALCOUNT = U.objectFieldOffset
3146 +                (k.getDeclaredField("stealCount"));
3147 +            MAINLOCK = U.objectFieldOffset
3148 +                (k.getDeclaredField("mainLock"));
3149              Class<?> tk = Thread.class;
3150              PARKBLOCKER = U.objectFieldOffset
3151                  (tk.getDeclaredField("parkBlocker"));
3152              ABASE = U.arrayBaseOffset(ak);
3153              s = U.arrayIndexScale(ak);
3154 +            ASHIFT = 31 - Integer.numberOfLeadingZeros(s);
3155          } catch (Exception e) {
3156              throw new Error(e);
3157          }
3158          if ((s & (s-1)) != 0)
3159              throw new Error("data type scale not a power of two");
3160 <        ASHIFT = 31 - Integer.numberOfLeadingZeros(s);
3160 >        try { // Establish common pool
3161 >            String pp = System.getProperty(propPrefix + "parallelism");
3162 >            String fp = System.getProperty(propPrefix + "threadFactory");
3163 >            String up = System.getProperty(propPrefix + "exceptionHandler");
3164 >            ForkJoinWorkerThreadFactory fac = (fp == null) ?
3165 >                defaultForkJoinWorkerThreadFactory :
3166 >                ((ForkJoinWorkerThreadFactory)ClassLoader.
3167 >                 getSystemClassLoader().loadClass(fp).newInstance());
3168 >            Thread.UncaughtExceptionHandler ueh = (up == null) ? null :
3169 >                ((Thread.UncaughtExceptionHandler)ClassLoader.
3170 >                 getSystemClassLoader().loadClass(up).newInstance());
3171 >            int par;
3172 >            if ((pp == null || (par = Integer.parseInt(pp)) <= 0))
3173 >                par = Runtime.getRuntime().availableProcessors();
3174 >            if (par > MAX_CAP)
3175 >                par = MAX_CAP;
3176 >            commonPoolParallelism = par;
3177 >            int n = par - 1; // precompute submit mask
3178 >            n |= n >>> 1; n |= n >>> 2; n |= n >>> 4;
3179 >            n |= n >>> 8; n |= n >>> 16;
3180 >            int mask = ((n + 1) << 1) - 1;
3181 >            commonPool = new ForkJoinPool(par, mask, fac, ueh);
3182 >        } catch (Exception e) {
3183 >            throw new Error(e);
3184 >        }
3185      }
3186  
3187      /**

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines