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.124 by jsr166, Mon Feb 20 23:32:24 2012 UTC vs.
Revision 1.137 by dl, Tue Oct 30 14:23:11 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 413 | Line 410 | public class ForkJoinPool extends Abstra
410       * unblocked threads to the point that we know they are available)
411       * leading to more situations requiring more threads, and so
412       * on. This aspect of control can be seen as an (analytically
413 <     * intractible) game with an opponent that may choose the worst
413 >     * intractable) game with an opponent that may choose the worst
414       * (for us) active thread to stall at any time.  We take several
415       * precautions to bound losses (and thus bound gains), mainly in
416       * methods tryCompensate and awaitJoin: (1) We only try
# 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 +         * Version of pop that takes top element only if it
740 +         * its root is the given CountedCompleter.
741 +         */
742 +        final ForkJoinTask<?> popCC(CountedCompleter<?> root) {
743 +            ForkJoinTask<?>[] a; int m;
744 +            if (root != null && (a = array) != null && (m = a.length - 1) >= 0) {
745 +                for (int s; (s = top - 1) - base >= 0;) {
746 +                    long j = ((m & s) << ASHIFT) + ABASE;
747 +                    ForkJoinTask<?> t =
748 +                        (ForkJoinTask<?>)U.getObject(a, j);
749 +                    if (t == null || !(t instanceof CountedCompleter) ||
750 +                        ((CountedCompleter<?>)t).getRoot() != root)
751 +                        break;
752 +                    if (U.compareAndSwapObject(a, j, t, null)) {
753 +                        top = s;
754 +                        return t;
755 +                    }
756 +                    if (root.status < 0)
757 +                        break;
758 +                }
759 +            }
760 +            return null;
761 +        }
762 +
763 +        /**
764 +         * Shared version of popCC
765 +         */
766 +        final ForkJoinTask<?> sharedPopCC(CountedCompleter<?> root) {
767 +            ForkJoinTask<?> task = null;
768 +            if (root != null &&
769 +                runState == 0 && U.compareAndSwapInt(this, RUNSTATE, 0, 1)) {
770 +                try {
771 +                    ForkJoinTask<?>[] a; int m;
772 +                    if ((a = array) != null && (m = a.length - 1) >= 0) {
773 +                        for (int s; (s = top - 1) - base >= 0;) {
774 +                            long j = ((m & s) << ASHIFT) + ABASE;
775 +                            ForkJoinTask<?> t =
776 +                                (ForkJoinTask<?>)U.getObject(a, j);
777 +                            if (t == null || !(t instanceof CountedCompleter) ||
778 +                                ((CountedCompleter<?>)t).getRoot() != root)
779 +                                break;
780 +                            if (U.compareAndSwapObject(a, j, t, null)) {
781 +                                top = s;
782 +                                task = t;
783 +                                break;
784 +                            }
785 +                            if (root.status < 0)
786 +                                break;
787 +                        }
788 +                    }
789 +                } finally {
790 +                    runState = 0;
791 +                }
792 +            }
793 +            return task;
794 +        }
795 +
796          /**
797           * Takes a task in FIFO order if b is base of queue and a task
798           * can be claimed without contention. Specialized versions
# Line 814 | Line 870 | public class ForkJoinPool extends Abstra
870          }
871  
872          /**
873 +         * Version of tryUnpush for shared queues; called by non-FJ
874 +         * submitters after prechecking that task probably exists.
875 +         */
876 +        final boolean trySharedUnpush(ForkJoinTask<?> t) {
877 +            boolean success = false;
878 +            if (runState == 0 && U.compareAndSwapInt(this, RUNSTATE, 0, 1)) {
879 +                try {
880 +                    ForkJoinTask<?>[] a; int s;
881 +                    if ((a = array) != null && (s = top) != base &&
882 +                        U.compareAndSwapObject
883 +                        (a, (((a.length - 1) & --s) << ASHIFT) + ABASE, t, null)) {
884 +                        top = s;
885 +                        success = true;
886 +                    }
887 +                } finally {
888 +                    runState = 0;                         // unlock
889 +                }
890 +            }
891 +            return success;
892 +        }
893 +
894 +        /**
895           * Polls the given task only if it is at the current base.
896           */
897          final boolean pollFor(ForkJoinTask<?> task) {
# Line 830 | Line 908 | public class ForkJoinPool extends Abstra
908          }
909  
910          /**
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        /**
911           * Initializes or doubles the capacity of array. Call either
912           * by owner or with lock held -- it is OK for base, but not
913           * top, to move while resizings are in progress.
# Line 939 | Line 969 | public class ForkJoinPool extends Abstra
969          // Execution methods
970  
971          /**
972 <         * Removes and runs tasks until empty, using local mode
943 <         * ordering. Normally called only after checking for apparent
944 <         * non-emptiness.
972 >         * Pops and runs tasks until empty.
973           */
974 <        final void runLocalTasks() {
975 <            // hoist checks from repeated pop/poll
976 <            ForkJoinTask<?>[] a; int m;
977 <            if ((a = array) != null && (m = a.length - 1) >= 0) {
978 <                if (mode == 0) {
979 <                    for (int s; (s = top - 1) - base >= 0;) {
980 <                        int j = ((m & s) << ASHIFT) + ABASE;
981 <                        ForkJoinTask<?> t =
982 <                            (ForkJoinTask<?>)U.getObjectVolatile(a, j);
983 <                        if (t != null) {
984 <                            if (U.compareAndSwapObject(a, j, t, null)) {
957 <                                top = s;
958 <                                t.doExec();
959 <                            }
960 <                        }
961 <                        else
962 <                            break;
963 <                    }
974 >        private void popAndExecAll() {
975 >            // A bit faster than repeated pop calls
976 >            ForkJoinTask<?>[] a; int m, s; long j; ForkJoinTask<?> t;
977 >            while ((a = array) != null && (m = a.length - 1) >= 0 &&
978 >                   (s = top - 1) - base >= 0 &&
979 >                   (t = ((ForkJoinTask<?>)
980 >                         U.getObject(a, j = ((m & s) << ASHIFT) + ABASE)))
981 >                   != null) {
982 >                if (U.compareAndSwapObject(a, j, t, null)) {
983 >                    top = s;
984 >                    t.doExec();
985                  }
986 <                else {
987 <                    for (int b; (b = base) - top < 0;) {
988 <                        int j = ((m & b) << ASHIFT) + ABASE;
989 <                        ForkJoinTask<?> t =
990 <                            (ForkJoinTask<?>)U.getObjectVolatile(a, j);
991 <                        if (t != null) {
992 <                            if (base == b &&
993 <                                U.compareAndSwapObject(a, j, t, null)) {
994 <                                base = b + 1;
995 <                                t.doExec();
996 <                            }
997 <                        } else if (base == b) {
998 <                            if (b + 1 == top)
986 >            }
987 >        }
988 >
989 >        /**
990 >         * Polls and runs tasks until empty.
991 >         */
992 >        private void pollAndExecAll() {
993 >            for (ForkJoinTask<?> t; (t = poll()) != null;)
994 >                t.doExec();
995 >        }
996 >
997 >        /**
998 >         * If present, removes from queue and executes the given task, or
999 >         * any other cancelled task. Returns (true) immediately on any CAS
1000 >         * or consistency check failure so caller can retry.
1001 >         *
1002 >         * @return 0 if no progress can be made, else positive
1003 >         * (this unusual convention simplifies use with tryHelpStealer.)
1004 >         */
1005 >        final int tryRemoveAndExec(ForkJoinTask<?> task) {
1006 >            int stat = 1;
1007 >            boolean removed = false, empty = true;
1008 >            ForkJoinTask<?>[] a; int m, s, b, n;
1009 >            if ((a = array) != null && (m = a.length - 1) >= 0 &&
1010 >                (n = (s = top) - (b = base)) > 0) {
1011 >                for (ForkJoinTask<?> t;;) {           // traverse from s to b
1012 >                    int j = ((--s & m) << ASHIFT) + ABASE;
1013 >                    t = (ForkJoinTask<?>)U.getObjectVolatile(a, j);
1014 >                    if (t == null)                    // inconsistent length
1015 >                        break;
1016 >                    else if (t == task) {
1017 >                        if (s + 1 == top) {           // pop
1018 >                            if (!U.compareAndSwapObject(a, j, task, null))
1019                                  break;
1020 <                            Thread.yield(); // wait for lagging update
1020 >                            top = s;
1021 >                            removed = true;
1022                          }
1023 +                        else if (base == b)           // replace with proxy
1024 +                            removed = U.compareAndSwapObject(a, j, task,
1025 +                                                             new EmptyTask());
1026 +                        break;
1027 +                    }
1028 +                    else if (t.status >= 0)
1029 +                        empty = false;
1030 +                    else if (s + 1 == top) {          // pop and throw away
1031 +                        if (U.compareAndSwapObject(a, j, t, null))
1032 +                            top = s;
1033 +                        break;
1034 +                    }
1035 +                    if (--n == 0) {
1036 +                        if (!empty && base == b)
1037 +                            stat = 0;
1038 +                        break;
1039                      }
1040                  }
1041              }
1042 +            if (removed)
1043 +                task.doExec();
1044 +            return stat;
1045          }
1046  
1047          /**
1048           * Executes a top-level task and any local tasks remaining
1049           * after execution.
989         *
990         * @return true unless terminating
1050           */
1051 <        final boolean runTask(ForkJoinTask<?> t) {
993 <            boolean alive = true;
1051 >        final void runTask(ForkJoinTask<?> t) {
1052              if (t != null) {
1053                  currentSteal = t;
1054                  t.doExec();
1055 <                if (top != base)        // conservative guard
1056 <                    runLocalTasks();
1055 >                if (top != base) {       // process remaining local tasks
1056 >                    if (mode == 0)
1057 >                        popAndExecAll();
1058 >                    else
1059 >                        pollAndExecAll();
1060 >                }
1061                  ++nsteals;
1062                  currentSteal = null;
1063              }
1002            else if (runState < 0)      // terminating
1003                alive = false;
1004            return alive;
1064          }
1065  
1066          /**
# Line 1106 | Line 1165 | public class ForkJoinPool extends Abstra
1165      public static final ForkJoinWorkerThreadFactory
1166          defaultForkJoinWorkerThreadFactory;
1167  
1168 +
1169 +    /** Property prefix for constructing common pool */
1170 +    private static final String propPrefix =
1171 +        "java.util.concurrent.ForkJoinPool.common.";
1172 +
1173 +    /**
1174 +     * Common (static) pool. Non-null for public use unless a static
1175 +     * construction exception, but internal usages must null-check on
1176 +     * use.
1177 +     */
1178 +    static final ForkJoinPool commonPool;
1179 +
1180 +    /**
1181 +     * Common pool parallelism. Must equal commonPool.parallelism.
1182 +     */
1183 +    static final int commonPoolParallelism;
1184 +
1185      /**
1186       * Generator for assigning sequence numbers as pool names.
1187       */
# Line 1124 | Line 1200 | public class ForkJoinPool extends Abstra
1200      private static final RuntimePermission modifyThreadPermission;
1201  
1202      /**
1203 <     * Per-thread submission bookeeping. Shared across all pools
1203 >     * Per-thread submission bookkeeping. Shared across all pools
1204       * to reduce ThreadLocal pollution and because random motion
1205       * to avoid contention in one pool is likely to hold for others.
1206       */
# Line 1133 | Line 1209 | public class ForkJoinPool extends Abstra
1209      // static constants
1210  
1211      /**
1212 <     * The wakeup interval (in nanoseconds) for a worker waiting for a
1213 <     * task when the pool is quiescent to instead try to shrink the
1214 <     * 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.
1212 >     * Initial timeout value (in nanoseconds) for the thread triggering
1213 >     * quiescence to park waiting for new work. On timeout, the thread
1214 >     * will instead try to shrink the number of workers.
1215       */
1216 <    private static final long SHRINK_RATE =
1144 <        4L * 1000L * 1000L * 1000L; // 4 seconds
1216 >    private static final long IDLE_TIMEOUT      = 1000L * 1000L * 1000L; // 1sec
1217  
1218      /**
1219 <     * The timeout value for attempted shrinkage, includes
1148 <     * some slop to cope with system timer imprecision.
1219 >     * Timeout value when there are more threads than parallelism level
1220       */
1221 <    private static final long SHRINK_TIMEOUT = SHRINK_RATE - (SHRINK_RATE / 10);
1221 >    private static final long FAST_IDLE_TIMEOUT =  100L * 1000L * 1000L;
1222  
1223      /**
1224       * The maximum stolen->joining link depth allowed in method
# Line 1160 | Line 1231 | public class ForkJoinPool extends Abstra
1231       * traversal parameters at the expense of sometimes blocking when
1232       * we could be helping.
1233       */
1234 <    private static final int MAX_HELP = 32;
1234 >    private static final int MAX_HELP = 64;
1235  
1236      /**
1237       * Secondary time-based bound (in nanosecs) for helping attempts
# Line 1170 | Line 1241 | public class ForkJoinPool extends Abstra
1241       * value should roughly approximate the time required to create
1242       * and/or activate a worker thread.
1243       */
1244 <    private static final long COMPENSATION_DELAY = 100L * 1000L; // 0.1 millisec
1244 >    private static final long COMPENSATION_DELAY = 1L << 18; // ~0.25 millisec
1245  
1246      /**
1247       * Increment for seed generators. See class ThreadLocal for
# Line 1267 | Line 1338 | public class ForkJoinPool extends Abstra
1338       * empirically works OK on current JVMs.
1339       */
1340  
1341 +    volatile long stealCount;                  // collects worker counts
1342      volatile long ctl;                         // main pool control
1343      final int parallelism;                     // parallelism level
1344      final int localMode;                       // per-worker scheduling mode
1345 +    volatile int nextWorkerNumber;             // to create worker name string
1346      final int submitMask;                      // submit queue index bound
1347      int nextSeed;                              // for initializing worker seeds
1348 +    volatile int mainLock;                     // spinlock for array updates
1349      volatile int runState;                     // shutdown status and seq
1350      WorkQueue[] workQueues;                    // main registry
1277    final Mutex lock;                          // for registration
1278    final Condition termination;               // for awaitTermination
1351      final ForkJoinWorkerThreadFactory factory; // factory for new workers
1352      final Thread.UncaughtExceptionHandler ueh; // per-worker UEH
1281    final AtomicLong stealCount;               // collect counts when terminated
1282    final AtomicInteger nextWorkerNumber;      // to create worker name string
1353      final String workerNamePrefix;             // to create worker name string
1354  
1355 +    /*
1356 +     * Mechanics for main lock protecting worker array updates.  Uses
1357 +     * the same strategy as ConcurrentHashMap bins -- a spinLock for
1358 +     * normal cases, but falling back to builtin lock when (rarely)
1359 +     * needed.  See internal ConcurrentHashMap documentation for
1360 +     * explanation.
1361 +     */
1362 +
1363 +    static final int LOCK_WAITING = 2; // bit to indicate need for signal
1364 +    static final int MAX_LOCK_SPINS = 1 << 8;
1365 +
1366 +    private void tryAwaitMainLock() {
1367 +        int spins = MAX_LOCK_SPINS, r = 0, h;
1368 +        while (((h = mainLock) & 1) != 0) {
1369 +            if (r == 0)
1370 +                r = ThreadLocalRandom.current().nextInt(); // randomize spins
1371 +            else if (spins >= 0) {
1372 +                r ^= r << 1; r ^= r >>> 3; r ^= r << 10; // xorshift
1373 +                if (r >= 0)
1374 +                    --spins;
1375 +            }
1376 +            else if (U.compareAndSwapInt(this, MAINLOCK, h, h | LOCK_WAITING)) {
1377 +                synchronized (this) {
1378 +                    if ((mainLock & LOCK_WAITING) != 0) {
1379 +                        try {
1380 +                            wait();
1381 +                        } catch (InterruptedException ie) {
1382 +                            Thread.currentThread().interrupt();
1383 +                        }
1384 +                    }
1385 +                    else
1386 +                        notifyAll(); // possibly won race vs signaller
1387 +                }
1388 +                break;
1389 +            }
1390 +        }
1391 +    }
1392 +
1393      //  Creating, registering, and deregistering workers
1394  
1395      /**
# Line 1308 | Line 1416 | public class ForkJoinPool extends Abstra
1416       * ForkJoinWorkerThread.
1417       */
1418      final String nextWorkerName() {
1419 <        return workerNamePrefix.concat
1420 <            (Integer.toString(nextWorkerNumber.addAndGet(1)));
1419 >        int n;
1420 >        do {} while(!U.compareAndSwapInt(this, NEXTWORKERNUMBER,
1421 >                                         n = nextWorkerNumber, ++n));
1422 >        return workerNamePrefix.concat(Integer.toString(n));
1423      }
1424  
1425      /**
# Line 1322 | Line 1432 | public class ForkJoinPool extends Abstra
1432       * @param w the worker's queue
1433       */
1434      final void registerWorker(WorkQueue w) {
1435 <        Mutex lock = this.lock;
1436 <        lock.lock();
1435 >        while (!U.compareAndSwapInt(this, MAINLOCK, 0, 1))
1436 >            tryAwaitMainLock();
1437          try {
1438 <            WorkQueue[] ws = workQueues;
1439 <            if (w != null && ws != null) {          // skip on shutdown/failure
1440 <                int rs, n;
1441 <                while ((n = ws.length) <            // ensure can hold total
1442 <                       (parallelism + (short)(ctl >>> TC_SHIFT) << 1))
1333 <                    workQueues = ws = Arrays.copyOf(ws, n << 1);
1334 <                int m = n - 1;
1438 >            WorkQueue[] ws;
1439 >            if ((ws = workQueues) == null)
1440 >                ws = workQueues = new WorkQueue[submitMask + 1];
1441 >            if (w != null) {
1442 >                int rs, n =  ws.length, m = n - 1;
1443                  int s = nextSeed += SEED_INCREMENT; // rarely-colliding sequence
1444                  w.seed = (s == 0) ? 1 : s;          // ensure non-zero seed
1445                  int r = (s << 1) | 1;               // use odd-numbered indices
1446 <                while (ws[r &= m] != null)          // step by approx half size
1447 <                    r += ((n >>> 1) & SQMASK) + 2;
1446 >                if (ws[r &= m] != null) {           // collision
1447 >                    int probes = 0;                 // step by approx half size
1448 >                    int step = (n <= 4) ? 2 : ((n >>> 1) & SQMASK) + 2;
1449 >                    while (ws[r = (r + step) & m] != null) {
1450 >                        if (++probes >= n) {
1451 >                            workQueues = ws = Arrays.copyOf(ws, n <<= 1);
1452 >                            m = n - 1;
1453 >                            probes = 0;
1454 >                        }
1455 >                    }
1456 >                }
1457                  w.eventCount = w.poolIndex = r;     // establish before recording
1458                  ws[r] = w;                          // also update seq
1459                  runState = ((rs = runState) & SHUTDOWN) | ((rs + 2) & ~SHUTDOWN);
1460              }
1461          } finally {
1462 <            lock.unlock();
1462 >            if (!U.compareAndSwapInt(this, MAINLOCK, 1, 0)) {
1463 >                mainLock = 0;
1464 >                synchronized (this) { notifyAll(); };
1465 >            }
1466          }
1467 +
1468      }
1469  
1470      /**
# Line 1356 | Line 1477 | public class ForkJoinPool extends Abstra
1477       * @param ex the exception causing failure, or null if none
1478       */
1479      final void deregisterWorker(ForkJoinWorkerThread wt, Throwable ex) {
1359        Mutex lock = this.lock;
1480          WorkQueue w = null;
1481          if (wt != null && (w = wt.workQueue) != null) {
1482              w.runState = -1;                // ensure runState is set
1483 <            stealCount.getAndAdd(w.totalSteals + w.nsteals);
1483 >            long steals = w.totalSteals + w.nsteals, sc;
1484 >            do {} while(!U.compareAndSwapLong(this, STEALCOUNT,
1485 >                                              sc = stealCount, sc + steals));
1486              int idx = w.poolIndex;
1487 <            lock.lock();
1488 <            try {                           // remove record from array
1487 >            while (!U.compareAndSwapInt(this, MAINLOCK, 0, 1))
1488 >                tryAwaitMainLock();
1489 >            try {
1490                  WorkQueue[] ws = workQueues;
1491                  if (ws != null && idx >= 0 && idx < ws.length && ws[idx] == w)
1492                      ws[idx] = null;
1493              } finally {
1494 <                lock.unlock();
1494 >                if (!U.compareAndSwapInt(this, MAINLOCK, 1, 0)) {
1495 >                    mainLock = 0;
1496 >                    synchronized (this) { notifyAll(); };
1497 >                }
1498              }
1499          }
1500  
# Line 1390 | Line 1516 | public class ForkJoinPool extends Abstra
1516              U.throwException(ex);
1517      }
1518  
1393
1519      // Submissions
1520  
1521      /**
# Line 1399 | Line 1524 | public class ForkJoinPool extends Abstra
1524       * range). If no queue exists at the index, one is created.  If
1525       * the queue is busy, another index is randomly chosen. The
1526       * submitMask bounds the effective number of queues to the
1527 <     * (nearest poswer of two for) parallelism level.
1527 >     * (nearest power of two for) parallelism level.
1528       *
1529       * @param task the task. Caller must ensure non-null.
1530       */
# Line 1408 | Line 1533 | public class ForkJoinPool extends Abstra
1533          for (int r = s.seed, m = submitMask;;) {
1534              WorkQueue[] ws; WorkQueue q;
1535              int k = r & m & SQMASK;          // use only even indices
1536 <            if (runState < 0 || (ws = workQueues) == null || ws.length <= k)
1536 >            if (runState < 0)
1537                  throw new RejectedExecutionException(); // shutting down
1538 +            else if ((ws = workQueues) == null || ws.length <= k) {
1539 +                while (!U.compareAndSwapInt(this, MAINLOCK, 0, 1))
1540 +                    tryAwaitMainLock();
1541 +                try {
1542 +                    if (workQueues == null)
1543 +                        workQueues = new WorkQueue[submitMask + 1];
1544 +                } finally {
1545 +                    if (!U.compareAndSwapInt(this, MAINLOCK, 1, 0)) {
1546 +                        mainLock = 0;
1547 +                        synchronized (this) { notifyAll(); };
1548 +                    }
1549 +                }
1550 +            }
1551              else if ((q = ws[k]) == null) {  // create new queue
1552                  WorkQueue nq = new WorkQueue(this, null, SHARED_QUEUE);
1553 <                Mutex lock = this.lock;      // construct outside lock
1554 <                lock.lock();
1555 <                try {                        // recheck under lock
1553 >                while (!U.compareAndSwapInt(this, MAINLOCK, 0, 1))
1554 >                    tryAwaitMainLock();
1555 >                try {
1556                      int rs = runState;       // to update seq
1557                      if (ws == workQueues && ws[k] == null) {
1558                          ws[k] = nq;
1559                          runState = ((rs & SHUTDOWN) | ((rs + 2) & ~SHUTDOWN));
1560                      }
1561                  } finally {
1562 <                    lock.unlock();
1562 >                    if (!U.compareAndSwapInt(this, MAINLOCK, 1, 0)) {
1563 >                        mainLock = 0;
1564 >                        synchronized (this) { notifyAll(); };
1565 >                    }
1566                  }
1567              }
1568              else if (q.trySharedPush(task)) {
# Line 1438 | Line 1579 | public class ForkJoinPool extends Abstra
1579          }
1580      }
1581  
1582 +    /**
1583 +     * Submits the given (non-null) task to the common pool, if possible.
1584 +     */
1585 +    static void submitToCommonPool(ForkJoinTask<?> task) {
1586 +        ForkJoinPool p;
1587 +        if ((p = commonPool) == null)
1588 +            throw new RejectedExecutionException("Common Pool Unavailable");
1589 +        p.doSubmit(task);
1590 +    }
1591 +
1592 +    /**
1593 +     * Returns true if caller is (or may be) submitter to the common
1594 +     * pool, and not all workers are active, and there appear to be
1595 +     * tasks in the associated submission queue.
1596 +     */
1597 +    static boolean canHelpCommonPool() {
1598 +        ForkJoinPool p; WorkQueue[] ws; WorkQueue q;
1599 +        int k = submitters.get().seed & SQMASK;
1600 +        return ((p = commonPool) != null &&
1601 +                (int)(p.ctl >> AC_SHIFT) < 0 &&
1602 +                (ws = p.workQueues) != null &&
1603 +                ws.length > (k &= p.submitMask) &&
1604 +                (q = ws[k]) != null &&
1605 +                q.top - q.base > 0);
1606 +    }
1607 +
1608 +    /**
1609 +     * Returns true if the given task was submitted to common pool
1610 +     * and has not yet commenced execution, and is available for
1611 +     * removal according to execution policies; if so removing the
1612 +     * submission from the pool.
1613 +     *
1614 +     * @param task the task
1615 +     * @return true if successful
1616 +     */
1617 +    static boolean tryUnsubmitFromCommonPool(ForkJoinTask<?> task) {
1618 +        // Peek, looking for task and eligibility before
1619 +        // using trySharedUnpush to actually take it under lock
1620 +        ForkJoinPool p; WorkQueue[] ws; WorkQueue q;
1621 +        ForkJoinTask<?>[] a; int s;
1622 +        int k = submitters.get().seed & SQMASK;
1623 +        return ((p = commonPool) != null &&
1624 +                (int)(p.ctl >> AC_SHIFT) < 0 &&
1625 +                (ws = p.workQueues) != null &&
1626 +                ws.length > (k &= p.submitMask) &&
1627 +                (q = ws[k]) != null &&
1628 +                (a = q.array) != null &&
1629 +                (s = q.top - 1) - q.base >= 0 &&
1630 +                s >= 0 && s < a.length &&
1631 +                a[s] == task &&
1632 +                q.trySharedUnpush(task));
1633 +    }
1634 +
1635 +    /**
1636 +     * Tries to pop a task from common pool with given root
1637 +     */
1638 +    static ForkJoinTask<?> popCCFromCommonPool(CountedCompleter<?> root) {
1639 +        ForkJoinPool p; WorkQueue[] ws; WorkQueue q;
1640 +        ForkJoinTask<?> t;
1641 +        int k = submitters.get().seed & SQMASK;
1642 +        if (root != null &&
1643 +            (p = commonPool) != null &&
1644 +            (int)(p.ctl >> AC_SHIFT) < 0 &&
1645 +            (ws = p.workQueues) != null &&
1646 +            ws.length > (k &= p.submitMask) &&
1647 +            (q = ws[k]) != null && q.top - q.base > 0 &&
1648 +            root.status < 0 &&
1649 +            (t = q.sharedPopCC(root)) != null)
1650 +            return t;
1651 +        return null;
1652 +    }
1653 +
1654 +
1655      // Maintaining ctl counts
1656  
1657      /**
# Line 1449 | Line 1663 | public class ForkJoinPool extends Abstra
1663      }
1664  
1665      /**
1666 <     * Tries to activate or create a worker if too few are active.
1666 >     * Tries to create one or activate one or more workers if too few are active.
1667       */
1668      final void signalWork() {
1669          long c; int u;
# Line 1483 | Line 1697 | public class ForkJoinPool extends Abstra
1697          }
1698      }
1699  
1486
1700      // Scanning for tasks
1701  
1702      /**
# Line 1491 | Line 1704 | public class ForkJoinPool extends Abstra
1704       */
1705      final void runWorker(WorkQueue w) {
1706          w.growArray(false);         // initialize queue array in this thread
1707 <        do {} while (w.runTask(scan(w)));
1707 >        do { w.runTask(scan(w)); } while (w.runState >= 0);
1708      }
1709  
1710      /**
# Line 1534 | Line 1747 | public class ForkJoinPool extends Abstra
1747       * awaiting signal,
1748       *
1749       * @param w the worker (via its WorkQueue)
1750 <     * @return a task or null of none found
1750 >     * @return a task or null if none found
1751       */
1752      private final ForkJoinTask<?> scan(WorkQueue w) {
1753          WorkQueue[] ws;                       // first update random seed
# Line 1551 | Line 1764 | public class ForkJoinPool extends Abstra
1764                      t = (ForkJoinTask<?>)U.getObjectVolatile(a, i);
1765                      if (q.base == b && ec >= 0 && t != null &&
1766                          U.compareAndSwapObject(a, i, t, null)) {
1767 <                        q.base = b + 1;       // specialization of pollAt
1767 >                        if (q.top - (q.base = b + 1) > 0)
1768 >                            signalWork();    // help pushes signal
1769                          return t;
1770                      }
1771 <                    else if ((t != null || b + 1 != q.top) &&
1558 <                             (ec < 0 || j <= m)) {
1771 >                    else if (ec < 0 || j <= m) {
1772                          rs = 0;               // mark scan as imcomplete
1773                          break;                // caller can retry after release
1774                      }
# Line 1563 | Line 1776 | public class ForkJoinPool extends Abstra
1776                  if (--j < 0)
1777                      break;
1778              }
1779 +
1780              long c = ctl; int e = (int)c, a = (int)(c >> AC_SHIFT), nr, ns;
1781              if (e < 0)                        // decode ctl on empty scan
1782                  w.runState = -1;              // pool is terminating
# Line 1596 | Line 1810 | public class ForkJoinPool extends Abstra
1810                  }
1811              }
1812              else if (w.eventCount < 0) {      // already queued
1813 <                if ((nr = w.rescans) > 0) {   // continue rescanning
1814 <                    int ac = a + parallelism;
1815 <                    if (((w.rescans = (ac < nr) ? ac : nr - 1) & 3) == 0)
1816 <                        Thread.yield();       // yield before block
1603 <                }
1604 <                else {
1813 >                int ac = a + parallelism;
1814 >                if ((nr = w.rescans) > 0)     // continue rescanning
1815 >                    w.rescans = (ac < nr) ? ac : nr - 1;
1816 >                else if (((w.seed >>> 16) & ac) == 0) { // randomize park
1817                      Thread.interrupted();     // clear status
1818                      Thread wt = Thread.currentThread();
1819                      U.putObject(wt, PARKBLOCKER, this);
# Line 1619 | Line 1831 | public class ForkJoinPool extends Abstra
1831      /**
1832       * If inactivating worker w has caused the pool to become
1833       * quiescent, checks for pool termination, and, so long as this is
1834 <     * not the only worker, waits for event for up to SHRINK_RATE
1835 <     * nanosecs.  On timeout, if ctl has not changed, terminates the
1834 >     * not the only worker, waits for event for up to a given
1835 >     * duration.  On timeout, if ctl has not changed, terminates the
1836       * worker, which will in turn wake up another worker to possibly
1837       * repeat this process.
1838       *
# Line 1630 | Line 1842 | public class ForkJoinPool extends Abstra
1842       */
1843      private void idleAwaitWork(WorkQueue w, long currentCtl, long prevCtl) {
1844          if (w.eventCount < 0 && !tryTerminate(false, false) &&
1845 <            (int)prevCtl != 0 && ctl == currentCtl) {
1845 >            (int)prevCtl != 0 && !hasQueuedSubmissions() && ctl == currentCtl) {
1846 >            int dc = -(short)(currentCtl >>> TC_SHIFT);
1847 >            long parkTime = dc < 0 ? FAST_IDLE_TIMEOUT: (dc + 1) * IDLE_TIMEOUT;
1848 >            long deadline = System.nanoTime() + parkTime - 100000L; // 1ms slop
1849              Thread wt = Thread.currentThread();
1635            Thread.yield();            // yield before block
1850              while (ctl == currentCtl) {
1637                long startTime = System.nanoTime();
1851                  Thread.interrupted();  // timed variant of version in scan()
1852                  U.putObject(wt, PARKBLOCKER, this);
1853                  w.parker = wt;
1854                  if (ctl == currentCtl)
1855 <                    U.park(false, SHRINK_RATE);
1855 >                    U.park(false, parkTime);
1856                  w.parker = null;
1857                  U.putObject(wt, PARKBLOCKER, null);
1858                  if (ctl != currentCtl)
1859                      break;
1860 <                if (System.nanoTime() - startTime >= SHRINK_TIMEOUT &&
1860 >                if (deadline - System.nanoTime() <= 0L &&
1861                      U.compareAndSwapLong(this, CTL, currentCtl, prevCtl)) {
1862                      w.eventCount = (w.eventCount + E_SEQ) | E_MASK;
1863                      w.runState = -1;   // shrink
# Line 1665 | Line 1878 | public class ForkJoinPool extends Abstra
1878       * leaves hints in workers to speed up subsequent calls. The
1879       * implementation is very branchy to cope with potential
1880       * inconsistencies or loops encountering chains that are stale,
1881 <     * unknown, or so long that they are likely cyclic.  All of these
1669 <     * cases are dealt with by just retrying by caller.
1881 >     * unknown, or so long that they are likely cyclic.
1882       *
1883       * @param joiner the joining worker
1884       * @param task the task to join
1885 <     * @return true if found or ran a task (and so is immediately retryable)
1885 >     * @return 0 if no progress can be made, negative if task
1886 >     * known complete, else positive
1887       */
1888 <    private boolean tryHelpStealer(WorkQueue joiner, ForkJoinTask<?> task) {
1889 <        WorkQueue[] ws;
1890 <        int m, depth = MAX_HELP;                // remaining chain depth
1891 <        boolean progress = false;
1892 <        if ((ws = workQueues) != null && (m = ws.length - 1) > 0 &&
1893 <            task.status >= 0) {
1894 <            ForkJoinTask<?> subtask = task;     // current target
1895 <            outer: for (WorkQueue j = joiner;;) {
1896 <                WorkQueue stealer = null;       // find stealer of subtask
1897 <                WorkQueue v = ws[j.stealHint & m]; // try hint
1898 <                if (v != null && v.currentSteal == subtask)
1899 <                    stealer = v;
1900 <                else {                          // scan
1901 <                    for (int i = 1; i <= m; i += 2) {
1902 <                        if ((v = ws[i]) != null && v.currentSteal == subtask &&
1903 <                            v != joiner) {
1904 <                            stealer = v;
1905 <                            j.stealHint = i;    // save hint
1906 <                            break;
1888 >    private int tryHelpStealer(WorkQueue joiner, ForkJoinTask<?> task) {
1889 >        int stat = 0, steps = 0;                    // bound to avoid cycles
1890 >        if (joiner != null && task != null) {       // hoist null checks
1891 >            restart: for (;;) {
1892 >                ForkJoinTask<?> subtask = task;     // current target
1893 >                for (WorkQueue j = joiner, v;;) {   // v is stealer of subtask
1894 >                    WorkQueue[] ws; int m, s, h;
1895 >                    if ((s = task.status) < 0) {
1896 >                        stat = s;
1897 >                        break restart;
1898 >                    }
1899 >                    if ((ws = workQueues) == null || (m = ws.length - 1) <= 0)
1900 >                        break restart;              // shutting down
1901 >                    if ((v = ws[h = (j.stealHint | 1) & m]) == null ||
1902 >                        v.currentSteal != subtask) {
1903 >                        for (int origin = h;;) {    // find stealer
1904 >                            if (((h = (h + 2) & m) & 15) == 1 &&
1905 >                                (subtask.status < 0 || j.currentJoin != subtask))
1906 >                                continue restart;   // occasional staleness check
1907 >                            if ((v = ws[h]) != null &&
1908 >                                v.currentSteal == subtask) {
1909 >                                j.stealHint = h;    // save hint
1910 >                                break;
1911 >                            }
1912 >                            if (h == origin)
1913 >                                break restart;      // cannot find stealer
1914                          }
1915                      }
1916 <                    if (stealer == null)
1917 <                        break;
1918 <                }
1919 <
1920 <                for (WorkQueue q = stealer;;) { // try to help stealer
1921 <                    ForkJoinTask[] a; ForkJoinTask<?> t; int b;
1922 <                    if (task.status < 0)
1923 <                        break outer;
1924 <                    if ((b = q.base) - q.top < 0 && (a = q.array) != null) {
1925 <                        progress = true;
1926 <                        int i = (((a.length - 1) & b) << ASHIFT) + ABASE;
1927 <                        t = (ForkJoinTask<?>)U.getObjectVolatile(a, i);
1928 <                        if (subtask.status < 0) // must recheck before taking
1929 <                            break outer;
1930 <                        if (t != null &&
1931 <                            q.base == b &&
1932 <                            U.compareAndSwapObject(a, i, t, null)) {
1933 <                            q.base = b + 1;
1934 <                            joiner.runSubtask(t);
1916 >                    for (;;) { // help stealer or descend to its stealer
1917 >                        ForkJoinTask[] a;  int b;
1918 >                        if (subtask.status < 0)     // surround probes with
1919 >                            continue restart;       //   consistency checks
1920 >                        if ((b = v.base) - v.top < 0 && (a = v.array) != null) {
1921 >                            int i = (((a.length - 1) & b) << ASHIFT) + ABASE;
1922 >                            ForkJoinTask<?> t =
1923 >                                (ForkJoinTask<?>)U.getObjectVolatile(a, i);
1924 >                            if (subtask.status < 0 || j.currentJoin != subtask ||
1925 >                                v.currentSteal != subtask)
1926 >                                continue restart;   // stale
1927 >                            stat = 1;               // apparent progress
1928 >                            if (t != null && v.base == b &&
1929 >                                U.compareAndSwapObject(a, i, t, null)) {
1930 >                                v.base = b + 1;     // help stealer
1931 >                                joiner.runSubtask(t);
1932 >                            }
1933 >                            else if (v.base == b && ++steps == MAX_HELP)
1934 >                                break restart;      // v apparently stalled
1935 >                        }
1936 >                        else {                      // empty -- try to descend
1937 >                            ForkJoinTask<?> next = v.currentJoin;
1938 >                            if (subtask.status < 0 || j.currentJoin != subtask ||
1939 >                                v.currentSteal != subtask)
1940 >                                continue restart;   // stale
1941 >                            else if (next == null || ++steps == MAX_HELP)
1942 >                                break restart;      // dead-end or maybe cyclic
1943 >                            else {
1944 >                                subtask = next;
1945 >                                j = v;
1946 >                                break;
1947 >                            }
1948                          }
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;
1949                      }
1950                  }
1951              }
1952          }
1953 <        return progress;
1953 >        return stat;
1954      }
1955  
1956      /**
# Line 1757 | Line 1979 | public class ForkJoinPool extends Abstra
1979       * adds a new thread if no idle workers are available and either
1980       * pool would become completely starved or: (at least half
1981       * starved, and fewer than 50% spares exist, and there is at least
1982 <     * one task apparently available). Even though the availablity
1982 >     * one task apparently available). Even though the availability
1983       * check requires a full scan, it is worthwhile in reducing false
1984       * alarms.
1985       *
1986 <     * @param task if nonnull, a task being waited for
1987 <     * @param blocker if nonnull, a blocker being waited for
1986 >     * @param task if non-null, a task being waited for
1987 >     * @param blocker if non-null, a blocker being waited for
1988       * @return true if the caller can block, else should recheck and retry
1989       */
1990      final boolean tryCompensate(ForkJoinTask<?> task, ManagedBlocker blocker) {
# Line 1821 | Line 2043 | public class ForkJoinPool extends Abstra
2043      }
2044  
2045      /**
2046 <     * Helps and/or blocks until the given task is done
2046 >     * Helps and/or blocks until the given task is done.
2047       *
2048       * @param joiner the joining worker
2049       * @param task the task
2050       * @return task status on exit
2051       */
2052      final int awaitJoin(WorkQueue joiner, ForkJoinTask<?> task) {
2053 <        ForkJoinTask<?> prevJoin = joiner.currentJoin;
2054 <        joiner.currentJoin = task;
2055 <        long startTime = 0L;
2056 <        for (int k = 0, s; ; ++k) {
2057 <            if ((joiner.isEmpty() ?                  // try to help
2058 <                 !tryHelpStealer(joiner, task) :
2059 <                 !joiner.tryRemoveAndExec(task))) {
2060 <                if (k == 0) {
2061 <                    startTime = System.nanoTime();
2062 <                    tryPollForAndExec(joiner, task); // check uncommon case
2063 <                }
2064 <                else if ((k & (MAX_HELP - 1)) == 0 &&
2065 <                         System.nanoTime() - startTime >= COMPENSATION_DELAY &&
2066 <                         tryCompensate(task, null)) {
2067 <                    if (task.trySetSignal() && task.status >= 0) {
2068 <                        synchronized (task) {
2069 <                            if (task.status >= 0) {
2070 <                                try {                // see ForkJoinTask
2071 <                                    task.wait();     //  for explanation
2072 <                                } catch (InterruptedException ie) {
2053 >        int s;
2054 >        if ((s = task.status) >= 0) {
2055 >            ForkJoinTask<?> prevJoin = joiner.currentJoin;
2056 >            joiner.currentJoin = task;
2057 >            long startTime = 0L;
2058 >            for (int k = 0;;) {
2059 >                if ((s = (joiner.isEmpty() ?           // try to help
2060 >                          tryHelpStealer(joiner, task) :
2061 >                          joiner.tryRemoveAndExec(task))) == 0 &&
2062 >                    (s = task.status) >= 0) {
2063 >                    if (k == 0) {
2064 >                        startTime = System.nanoTime();
2065 >                        tryPollForAndExec(joiner, task); // check uncommon case
2066 >                    }
2067 >                    else if ((k & (MAX_HELP - 1)) == 0 &&
2068 >                             System.nanoTime() - startTime >=
2069 >                             COMPENSATION_DELAY &&
2070 >                             tryCompensate(task, null)) {
2071 >                        if (task.trySetSignal()) {
2072 >                            synchronized (task) {
2073 >                                if (task.status >= 0) {
2074 >                                    try {                // see ForkJoinTask
2075 >                                        task.wait();     //  for explanation
2076 >                                    } catch (InterruptedException ie) {
2077 >                                    }
2078                                  }
2079 +                                else
2080 +                                    task.notifyAll();
2081                              }
1853                            else
1854                                task.notifyAll();
2082                          }
2083 +                        long c;                          // re-activate
2084 +                        do {} while (!U.compareAndSwapLong
2085 +                                     (this, CTL, c = ctl, c + AC_UNIT));
2086                      }
1857                    long c;                          // re-activate
1858                    do {} while (!U.compareAndSwapLong
1859                                 (this, CTL, c = ctl, c + AC_UNIT));
2087                  }
2088 +                if (s < 0 || (s = task.status) < 0) {
2089 +                    joiner.currentJoin = prevJoin;
2090 +                    break;
2091 +                }
2092 +                else if ((k++ & (MAX_HELP - 1)) == MAX_HELP >>> 1)
2093 +                    Thread.yield();                     // for politeness
2094              }
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
2095          }
2096 +        return s;
2097      }
2098  
2099      /**
# Line 1882 | Line 2110 | public class ForkJoinPool extends Abstra
2110          while ((s = task.status) >= 0 &&
2111                 (joiner.isEmpty() ?
2112                  tryHelpStealer(joiner, task) :
2113 <                joiner.tryRemoveAndExec(task)))
2113 >                joiner.tryRemoveAndExec(task)) != 0)
2114              ;
2115          return s;
2116      }
# Line 1922 | Line 2150 | public class ForkJoinPool extends Abstra
2150       */
2151      final void helpQuiescePool(WorkQueue w) {
2152          for (boolean active = true;;) {
2153 <            if (w.base - w.top < 0)
2154 <                w.runLocalTasks();  // exhaust local queue
2153 >            ForkJoinTask<?> localTask; // exhaust local queue
2154 >            while ((localTask = w.nextLocalTask()) != null)
2155 >                localTask.doExec();
2156              WorkQueue q = findNonEmptyStealQueue(w);
2157              if (q != null) {
2158                  ForkJoinTask<?> t; int b;
# Line 1955 | Line 2184 | public class ForkJoinPool extends Abstra
2184      }
2185  
2186      /**
2187 +     * Restricted version of helpQuiescePool for non-FJ callers
2188 +     */
2189 +    static void externalHelpQuiescePool() {
2190 +        ForkJoinPool p; WorkQueue[] ws; WorkQueue q, sq;
2191 +        ForkJoinTask<?>[] a; int b;
2192 +        ForkJoinTask<?> t = null;
2193 +        int k = submitters.get().seed & SQMASK;
2194 +        if ((p = commonPool) != null &&
2195 +            (int)(p.ctl >> AC_SHIFT) < 0 &&
2196 +            (ws = p.workQueues) != null &&
2197 +            ws.length > (k &= p.submitMask) &&
2198 +            (q = ws[k]) != null) {
2199 +            while (q.top - q.base > 0) {
2200 +                if ((t = q.sharedPop()) != null)
2201 +                    break;
2202 +            }
2203 +            if (t == null && (sq = p.findNonEmptyStealQueue(q)) != null &&
2204 +                (b = sq.base) - sq.top < 0)
2205 +                t = sq.pollAt(b);
2206 +            if (t != null)
2207 +                t.doExec();
2208 +        }
2209 +    }
2210 +
2211 +    /**
2212       * Gets and removes a local or stolen task for the given worker.
2213       *
2214       * @return a task, if available
# Line 1987 | Line 2241 | public class ForkJoinPool extends Abstra
2241                  8);
2242      }
2243  
2244 +    /**
2245 +     * Returns approximate submission queue length for the given caller
2246 +     */
2247 +    static int getEstimatedSubmitterQueueLength() {
2248 +        ForkJoinPool p; WorkQueue[] ws; WorkQueue q;
2249 +        int k = submitters.get().seed & SQMASK;
2250 +        return ((p = commonPool) != null &&
2251 +                p.runState >= 0 &&
2252 +                (ws = p.workQueues) != null &&
2253 +                ws.length > (k &= p.submitMask) &&
2254 +                (q = ws[k]) != null) ?
2255 +            q.queueSize() : 0;
2256 +    }
2257 +
2258      //  Termination
2259  
2260      /**
# Line 2004 | Line 2272 | public class ForkJoinPool extends Abstra
2272       * @return true if now terminating or terminated
2273       */
2274      private boolean tryTerminate(boolean now, boolean enable) {
2007        Mutex lock = this.lock;
2275          for (long c;;) {
2276              if (((c = ctl) & STOP_BIT) != 0) {      // already terminating
2277                  if ((short)(c >>> TC_SHIFT) == -parallelism) {
2278 <                    lock.lock();                    // don't need try/finally
2279 <                    termination.signalAll();        // signal when 0 workers
2280 <                    lock.unlock();
2278 >                    synchronized(this) {
2279 >                        notifyAll();                // signal when 0 workers
2280 >                    }
2281                  }
2282                  return true;
2283              }
2284              if (runState >= 0) {                    // not yet enabled
2285                  if (!enable)
2286                      return false;
2287 <                lock.lock();
2288 <                runState |= SHUTDOWN;
2289 <                lock.unlock();
2287 >                while (!U.compareAndSwapInt(this, MAINLOCK, 0, 1))
2288 >                    tryAwaitMainLock();
2289 >                try {
2290 >                    runState |= SHUTDOWN;
2291 >                } finally {
2292 >                    if (!U.compareAndSwapInt(this, MAINLOCK, 1, 0)) {
2293 >                        mainLock = 0;
2294 >                        synchronized (this) { notifyAll(); };
2295 >                    }
2296 >                }
2297              }
2298              if (!now) {                             // check if idle & no tasks
2299                  if ((int)(c >> AC_SHIFT) != -parallelism ||
# Line 2152 | Line 2426 | public class ForkJoinPool extends Abstra
2426          // Use nearest power 2 for workQueues size. See Hackers Delight sec 3.2.
2427          int n = parallelism - 1;
2428          n |= n >>> 1; n |= n >>> 2; n |= n >>> 4; n |= n >>> 8; n |= n >>> 16;
2429 <        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();
2429 >        this.submitMask = ((n + 1) << 1) - 1;
2430          int pn = poolNumberGenerator.incrementAndGet();
2431          StringBuilder sb = new StringBuilder("ForkJoinPool-");
2432          sb.append(Integer.toString(pn));
2433          sb.append("-worker-");
2434          this.workerNamePrefix = sb.toString();
2166        lock.lock();
2435          this.runState = 1;              // set init flag
2436 <        lock.unlock();
2436 >    }
2437 >
2438 >    /**
2439 >     * Constructor for common pool, suitable only for static initialization.
2440 >     * Basically the same as above, but uses smallest possible initial footprint.
2441 >     */
2442 >    ForkJoinPool(int parallelism, int submitMask,
2443 >                 ForkJoinWorkerThreadFactory factory,
2444 >                 Thread.UncaughtExceptionHandler handler) {
2445 >        this.factory = factory;
2446 >        this.ueh = handler;
2447 >        this.submitMask = submitMask;
2448 >        this.parallelism = parallelism;
2449 >        long np = (long)(-parallelism);
2450 >        this.ctl = ((np << AC_SHIFT) & AC_MASK) | ((np << TC_SHIFT) & TC_MASK);
2451 >        this.localMode = LIFO_QUEUE;
2452 >        this.workerNamePrefix = "ForkJoinPool.commonPool-worker-";
2453 >        this.runState = 1;
2454 >    }
2455 >
2456 >    /**
2457 >     * Returns the common pool instance.
2458 >     *
2459 >     * @return the common pool instance
2460 >     */
2461 >    public static ForkJoinPool commonPool() {
2462 >        ForkJoinPool p;
2463 >        if ((p = commonPool) == null)
2464 >            throw new Error("Common Pool Unavailable");
2465 >        return p;
2466      }
2467  
2468      // Execution methods
# Line 2341 | Line 2638 | public class ForkJoinPool extends Abstra
2638      }
2639  
2640      /**
2641 +     * Returns the targeted parallelism level of the common pool.
2642 +     *
2643 +     * @return the targeted parallelism level of the common pool
2644 +     */
2645 +    public static int getCommonPoolParallelism() {
2646 +        return commonPoolParallelism;
2647 +    }
2648 +
2649 +    /**
2650       * Returns the number of worker threads that have started but not
2651       * yet terminated.  The result returned by this method may differ
2652       * from {@link #getParallelism} when threads are created to
# Line 2421 | Line 2727 | public class ForkJoinPool extends Abstra
2727       * @return the number of steals
2728       */
2729      public long getStealCount() {
2730 <        long count = stealCount.get();
2730 >        long count = stealCount;
2731          WorkQueue[] ws; WorkQueue w;
2732          if ((ws = workQueues) != null) {
2733              for (int i = 1; i < ws.length; i += 2) {
# Line 2551 | Line 2857 | public class ForkJoinPool extends Abstra
2857      public String toString() {
2858          // Use a single pass through workQueues to collect counts
2859          long qt = 0L, qs = 0L; int rc = 0;
2860 <        long st = stealCount.get();
2860 >        long st = stealCount;
2861          long c = ctl;
2862          WorkQueue[] ws; WorkQueue w;
2863          if ((ws = workQueues) != null) {
# Line 2592 | Line 2898 | public class ForkJoinPool extends Abstra
2898      }
2899  
2900      /**
2901 <     * Initiates an orderly shutdown in which previously submitted
2902 <     * tasks are executed, but no new tasks will be accepted.
2903 <     * Invocation has no additional effect if already shut down.
2904 <     * Tasks that are in the process of being submitted concurrently
2905 <     * during the course of this method may or may not be rejected.
2901 >     * Possibly initiates an orderly shutdown in which previously
2902 >     * submitted tasks are executed, but no new tasks will be
2903 >     * accepted. Invocation has no effect on execution state if this
2904 >     * is the {@link #commonPool}, and no additional effect if
2905 >     * already shut down.  Tasks that are in the process of being
2906 >     * submitted concurrently during the course of this method may or
2907 >     * may not be rejected.
2908       *
2909       * @throws SecurityException if a security manager exists and
2910       *         the caller is not permitted to modify threads
# Line 2605 | Line 2913 | public class ForkJoinPool extends Abstra
2913       */
2914      public void shutdown() {
2915          checkPermission();
2916 <        tryTerminate(false, true);
2916 >        if (this != commonPool)
2917 >            tryTerminate(false, true);
2918      }
2919  
2920      /**
2921 <     * Attempts to cancel and/or stop all tasks, and reject all
2922 <     * subsequently submitted tasks.  Tasks that are in the process of
2923 <     * being submitted or executed concurrently during the course of
2924 <     * this method may or may not be rejected. This method cancels
2925 <     * both existing and unexecuted tasks, in order to permit
2926 <     * termination in the presence of task dependencies. So the method
2927 <     * always returns an empty list (unlike the case for some other
2928 <     * Executors).
2921 >     * Possibly attempts to cancel and/or stop all tasks, and reject
2922 >     * all subsequently submitted tasks.  Invocation has no effect on
2923 >     * execution state if this is the {@link #commonPool}, and no
2924 >     * additional effect if already shut down. Otherwise, tasks that
2925 >     * are in the process of being submitted or executed concurrently
2926 >     * during the course of this method may or may not be
2927 >     * rejected. This method cancels both existing and unexecuted
2928 >     * tasks, in order to permit termination in the presence of task
2929 >     * dependencies. So the method always returns an empty list
2930 >     * (unlike the case for some other Executors).
2931       *
2932       * @return an empty list
2933       * @throws SecurityException if a security manager exists and
# Line 2626 | Line 2937 | public class ForkJoinPool extends Abstra
2937       */
2938      public List<Runnable> shutdownNow() {
2939          checkPermission();
2940 <        tryTerminate(true, true);
2940 >        if (this != commonPool)
2941 >            tryTerminate(true, true);
2942          return Collections.emptyList();
2943      }
2944  
# Line 2683 | Line 2995 | public class ForkJoinPool extends Abstra
2995      public boolean awaitTermination(long timeout, TimeUnit unit)
2996          throws InterruptedException {
2997          long nanos = unit.toNanos(timeout);
2998 <        final Mutex lock = this.lock;
2999 <        lock.lock();
3000 <        try {
3001 <            for (;;) {
3002 <                if (isTerminated())
3003 <                    return true;
3004 <                if (nanos <= 0)
3005 <                    return false;
3006 <                nanos = termination.awaitNanos(nanos);
2998 >        if (isTerminated())
2999 >            return true;
3000 >        long startTime = System.nanoTime();
3001 >        boolean terminated = false;
3002 >        synchronized(this) {
3003 >            for (long waitTime = nanos, millis = 0L;;) {
3004 >                if (terminated = isTerminated() ||
3005 >                    waitTime <= 0L ||
3006 >                    (millis = unit.toMillis(waitTime)) <= 0L)
3007 >                    break;
3008 >                wait(millis);
3009 >                waitTime = nanos - (System.nanoTime() - startTime);
3010              }
2696        } finally {
2697            lock.unlock();
3011          }
3012 +        return terminated;
3013      }
3014  
3015      /**
# Line 2827 | Line 3141 | public class ForkJoinPool extends Abstra
3141      private static final long PARKBLOCKER;
3142      private static final int ABASE;
3143      private static final int ASHIFT;
3144 +    private static final long NEXTWORKERNUMBER;
3145 +    private static final long STEALCOUNT;
3146 +    private static final long MAINLOCK;
3147  
3148      static {
3149          poolNumberGenerator = new AtomicInteger();
# Line 2842 | Line 3159 | public class ForkJoinPool extends Abstra
3159              Class<?> ak = ForkJoinTask[].class;
3160              CTL = U.objectFieldOffset
3161                  (k.getDeclaredField("ctl"));
3162 +            NEXTWORKERNUMBER = U.objectFieldOffset
3163 +                (k.getDeclaredField("nextWorkerNumber"));
3164 +            STEALCOUNT = U.objectFieldOffset
3165 +                (k.getDeclaredField("stealCount"));
3166 +            MAINLOCK = U.objectFieldOffset
3167 +                (k.getDeclaredField("mainLock"));
3168              Class<?> tk = Thread.class;
3169              PARKBLOCKER = U.objectFieldOffset
3170                  (tk.getDeclaredField("parkBlocker"));
3171              ABASE = U.arrayBaseOffset(ak);
3172              s = U.arrayIndexScale(ak);
3173 +            ASHIFT = 31 - Integer.numberOfLeadingZeros(s);
3174          } catch (Exception e) {
3175              throw new Error(e);
3176          }
3177          if ((s & (s-1)) != 0)
3178              throw new Error("data type scale not a power of two");
3179 <        ASHIFT = 31 - Integer.numberOfLeadingZeros(s);
3179 >        try { // Establish common pool
3180 >            String pp = System.getProperty(propPrefix + "parallelism");
3181 >            String fp = System.getProperty(propPrefix + "threadFactory");
3182 >            String up = System.getProperty(propPrefix + "exceptionHandler");
3183 >            ForkJoinWorkerThreadFactory fac = (fp == null) ?
3184 >                defaultForkJoinWorkerThreadFactory :
3185 >                ((ForkJoinWorkerThreadFactory)ClassLoader.
3186 >                 getSystemClassLoader().loadClass(fp).newInstance());
3187 >            Thread.UncaughtExceptionHandler ueh = (up == null)? null :
3188 >                ((Thread.UncaughtExceptionHandler)ClassLoader.
3189 >                 getSystemClassLoader().loadClass(up).newInstance());
3190 >            int par;
3191 >            if ((pp == null || (par = Integer.parseInt(pp)) <= 0))
3192 >                par = Runtime.getRuntime().availableProcessors();
3193 >            if (par > MAX_CAP)
3194 >                par = MAX_CAP;
3195 >            commonPoolParallelism = par;
3196 >            int n = par - 1; // precompute submit mask
3197 >            n |= n >>> 1; n |= n >>> 2; n |= n >>> 4;
3198 >            n |= n >>> 8; n |= n >>> 16;
3199 >            int mask = ((n + 1) << 1) - 1;
3200 >            commonPool = new ForkJoinPool(par, mask, fac, ueh);
3201 >        } catch (Exception e) {
3202 >            throw new Error(e);
3203 >        }
3204      }
3205  
3206      /**

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines