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.167 by jsr166, Sun Dec 30 02:05:53 2012 UTC vs.
Revision 1.189 by jsr166, Sat Sep 12 19:16:45 2015 UTC

# Line 440 | Line 440 | public class ForkJoinPool extends Abstra
440       * Common Pool
441       * ===========
442       *
443 <     * The static commonPool always exists after static
443 >     * The static common Pool always exists after static
444       * initialization.  Since it (or any other created pool) need
445       * never be used, we minimize initial construction overhead and
446       * footprint to the setup of about a dozen fields, with no nested
# Line 687 | Line 687 | public class ForkJoinPool extends Abstra
687              return (n >= 0) ? 0 : -n; // ignore transient negative
688          }
689  
690 <       /**
690 >        /**
691           * Provides a more accurate estimate of whether this queue has
692           * any tasks than does queueSize, by checking whether a
693           * near-empty queue has at least one unclaimed task.
# Line 708 | Line 708 | public class ForkJoinPool extends Abstra
708           * shared-queue version is embedded in method externalPush.)
709           *
710           * @param task the task. Caller must ensure non-null.
711 <         * @throw RejectedExecutionException if array cannot be resized
711 >         * @throws RejectedExecutionException if array cannot be resized
712           */
713          final void push(ForkJoinTask<?> task) {
714              ForkJoinTask<?>[] a; ForkJoinPool p;
# Line 725 | Line 725 | public class ForkJoinPool extends Abstra
725              }
726          }
727  
728 <       /**
728 >        /**
729           * Initializes or doubles the capacity of array. Call either
730           * by owner or with lock held -- it is OK for base, but not
731           * top, to move while resizings are in progress.
# Line 907 | Line 907 | public class ForkJoinPool extends Abstra
907           * or any other cancelled task. Returns (true) on any CAS
908           * or consistency check failure so caller can retry.
909           *
910 <         * @return false if no progress can be made, else true;
910 >         * @return false if no progress can be made, else true
911           */
912          final boolean tryRemoveAndExec(ForkJoinTask<?> task) {
913              boolean stat = true, removed = false, empty = true;
# Line 952 | Line 952 | public class ForkJoinPool extends Abstra
952  
953          /**
954           * Polls for and executes the given task or any other task in
955 <         * its CountedCompleter computation
955 >         * its CountedCompleter computation.
956           */
957          final boolean pollAndExecCC(ForkJoinTask<?> root) {
958              ForkJoinTask<?>[] a; int b; Object o;
# Line 1026 | Line 1026 | public class ForkJoinPool extends Abstra
1026          private static final int ABASE;
1027          private static final int ASHIFT;
1028          static {
1029            int s;
1029              try {
1030                  U = getUnsafe();
1031                  Class<?> k = WorkQueue.class;
# Line 1034 | Line 1033 | public class ForkJoinPool extends Abstra
1033                  QLOCK = U.objectFieldOffset
1034                      (k.getDeclaredField("qlock"));
1035                  ABASE = U.arrayBaseOffset(ak);
1036 <                s = U.arrayIndexScale(ak);
1036 >                int scale = U.arrayIndexScale(ak);
1037 >                if ((scale & (scale - 1)) != 0)
1038 >                    throw new Error("data type scale not a power of two");
1039 >                ASHIFT = 31 - Integer.numberOfLeadingZeros(scale);
1040              } catch (Exception e) {
1041                  throw new Error(e);
1042              }
1041            if ((s & (s-1)) != 0)
1042                throw new Error("data type scale not a power of two");
1043            ASHIFT = 31 - Integer.numberOfLeadingZeros(s);
1043          }
1044      }
1045  
# Line 1074 | Line 1073 | public class ForkJoinPool extends Abstra
1073       * to paranoically avoid potential initialization circularities
1074       * as well as to simplify generated code.
1075       */
1076 <    static final ForkJoinPool commonPool;
1076 >    static final ForkJoinPool common;
1077  
1078      /**
1079 <     * Common pool parallelism. Must equal commonPool.parallelism.
1079 >     * Common pool parallelism. Must equal common.parallelism.
1080       */
1081 <    static final int commonPoolParallelism;
1081 >    static final int commonParallelism;
1082  
1083      /**
1084       * Sequence number for creating workerNamePrefix.
# Line 1132 | Line 1131 | public class ForkJoinPool extends Abstra
1131       */
1132      private static final int SEED_INCREMENT = 0x61c88647;
1133  
1134 <    /**
1134 >    /*
1135       * Bits and masks for control variables
1136       *
1137       * Field ctl is a long packed with:
# Line 1245 | Line 1244 | public class ForkJoinPool extends Abstra
1244      volatile Object pad10, pad11, pad12, pad13, pad14, pad15, pad16, pad17;
1245      volatile Object pad18, pad19, pad1a, pad1b;
1246  
1247 <    /*
1247 >    /**
1248       * Acquires the plock lock to protect worker array and related
1249       * updates. This method is called only if an initial CAS on plock
1250 <     * fails. This acts as a spinLock for normal cases, but falls back
1250 >     * fails. This acts as a spinlock for normal cases, but falls back
1251       * to builtin monitor to block when (rarely) needed. This would be
1252       * a terrible idea for a highly contended lock, but works fine as
1253       * a more conservative alternative to a pure spinlock.
# Line 1522 | Line 1521 | public class ForkJoinPool extends Abstra
1521                       (m = ws.length - 1) < 0) { // initialize workQueues
1522                  int p = config & SMASK;         // find power of two table size
1523                  int n = (p > 1) ? p - 1 : 1;    // ensure at least 2 slots
1524 <                n |= n >>> 1; n |= n >>> 2;  n |= n >>> 4;
1525 <                n |= n >>> 8; n |= n >>> 16; n = (n + 1) << 1;
1524 >                n |= n >>> 1;
1525 >                n |= n >>> 2;
1526 >                n |= n >>> 4;
1527 >                n |= n >>> 8;
1528 >                n |= n >>> 16;
1529 >                n = (n + 1) << 1;
1530                  WorkQueue[] nws = ((ws = workQueues) == null || ws.length == 0 ?
1531                                     new WorkQueue[n] : null);
1532                  if (((ps = plock) & PL_LOCK) != 0 ||
# Line 1932 | Line 1935 | public class ForkJoinPool extends Abstra
1935       * @param task the task to join
1936       * @param mode if shared, exit upon completing any task
1937       * if all workers are active
1935     *
1938       */
1939      private int helpComplete(ForkJoinTask<?> task, int mode) {
1940          WorkQueue[] ws; WorkQueue q; int m, n, s, u;
# Line 2129 | Line 2131 | public class ForkJoinPool extends Abstra
2131                      w.runSubtask(t);
2132                  }
2133              }
2134 <            else if (active) {       // decrement active count without queuing
2134 >            else if (active) {      // decrement active count without queuing
2135                  long nc = (c = ctl) - AC_UNIT;
2136                  if ((int)(nc >> AC_SHIFT) + (config & SMASK) == 0)
2137 <                    return;          // bypass decrement-then-increment
2137 >                    return;         // bypass decrement-then-increment
2138                  if (U.compareAndSwapLong(this, CTL, c, nc))
2139                      active = false;
2140              }
# Line 2187 | Line 2189 | public class ForkJoinPool extends Abstra
2189       * producing extra tasks amortizes the uncertainty of progress and
2190       * diffusion assumptions.
2191       *
2192 <     * So, users will want to use values larger, but not much larger
2192 >     * So, users will want to use values larger (but not much larger)
2193       * than 1 to both smooth over transient shortages and hedge
2194       * against uneven progress; as traded off against the cost of
2195       * extra task overhead. We leave the user to pick a threshold
# Line 2241 | Line 2243 | public class ForkJoinPool extends Abstra
2243       */
2244      private boolean tryTerminate(boolean now, boolean enable) {
2245          int ps;
2246 <        if (this == commonPool)                    // cannot shut down
2246 >        if (this == common)                    // cannot shut down
2247              return false;
2248          if ((ps = plock) >= 0) {                   // enable by setting plock
2249              if (!enable)
# Line 2332 | Line 2334 | public class ForkJoinPool extends Abstra
2334      static WorkQueue commonSubmitterQueue() {
2335          ForkJoinPool p; WorkQueue[] ws; int m; Submitter z;
2336          return ((z = submitters.get()) != null &&
2337 <                (p = commonPool) != null &&
2337 >                (p = common) != null &&
2338                  (ws = p.workQueues) != null &&
2339                  (m = ws.length - 1) >= 0) ?
2340              ws[m & z.seed & SQMASK] : null;
# Line 2346 | Line 2348 | public class ForkJoinPool extends Abstra
2348          ForkJoinTask<?>[] a;  int m, s;
2349          if (t != null &&
2350              (z = submitters.get()) != null &&
2351 <            (p = commonPool) != null &&
2351 >            (p = common) != null &&
2352              (ws = p.workQueues) != null &&
2353              (m = ws.length - 1) >= 0 &&
2354              (q = ws[m & z.seed & SQMASK]) != null &&
# Line 2423 | Line 2425 | public class ForkJoinPool extends Abstra
2425          ForkJoinTask<?>[] a;  int m, s, n;
2426          if (t != null &&
2427              (z = submitters.get()) != null &&
2428 <            (p = commonPool) != null &&
2428 >            (p = common) != null &&
2429              (ws = p.workQueues) != null &&
2430              (m = ws.length - 1) >= 0 &&
2431              (q = ws[m & z.seed & SQMASK]) != null &&
# Line 2452 | Line 2454 | public class ForkJoinPool extends Abstra
2454          }
2455      }
2456  
2455    /**
2456     * Restricted version of helpQuiescePool for external callers
2457     */
2458    static void externalHelpQuiescePool() {
2459        ForkJoinPool p; ForkJoinTask<?> t; WorkQueue q; int b;
2460        if ((p = commonPool) != null &&
2461            (q = p.findNonEmptyStealQueue(1)) != null &&
2462            (b = q.base) - q.top < 0 &&
2463            (t = q.pollAt(b)) != null) {
2464            if (q.base - q.top < 0)
2465                p.signalWork(q);
2466            t.doExec();
2467        }
2468    }
2469
2457      // Exported methods
2458  
2459      // Constructors
# Line 2483 | Line 2470 | public class ForkJoinPool extends Abstra
2470       *         java.lang.RuntimePermission}{@code ("modifyThread")}
2471       */
2472      public ForkJoinPool() {
2473 <        this(Runtime.getRuntime().availableProcessors(),
2473 >        this(Math.min(MAX_CAP, Runtime.getRuntime().availableProcessors()),
2474               defaultForkJoinWorkerThreadFactory, null, false);
2475      }
2476  
# Line 2566 | Line 2553 | public class ForkJoinPool extends Abstra
2553  
2554      /**
2555       * Returns the common pool instance. This pool is statically
2556 <     * constructed; its run state is unaffected by attempts to
2557 <     * {@link #shutdown} or {@link #shutdownNow}.
2556 >     * constructed; its run state is unaffected by attempts to {@link
2557 >     * #shutdown} or {@link #shutdownNow}. However this pool and any
2558 >     * ongoing processing are automatically terminated upon program
2559 >     * {@link System#exit}.  Any program that relies on asynchronous
2560 >     * task processing to complete before program termination should
2561 >     * invoke {@code commonPool().}{@link #awaitQuiescence}, before
2562 >     * exit.
2563       *
2564       * @return the common pool instance
2565 +     * @since 1.8
2566       */
2567      public static ForkJoinPool commonPool() {
2568 <        // assert commonPool != null : "static init error";
2569 <        return commonPool;
2568 >        // assert common != null : "static init error";
2569 >        return common;
2570      }
2571  
2572      // Execution methods
# Line 2696 | Line 2689 | public class ForkJoinPool extends Abstra
2689          // In previous versions of this class, this method constructed
2690          // a task to run ForkJoinTask.invokeAll, but now external
2691          // invocation of multiple tasks is at least as efficient.
2692 <        List<ForkJoinTask<T>> fs = new ArrayList<ForkJoinTask<T>>(tasks.size());
2700 <        // Workaround needed because method wasn't declared with
2701 <        // wildcards in return type but should have been.
2702 <        @SuppressWarnings({"unchecked", "rawtypes"})
2703 <            List<Future<T>> futures = (List<Future<T>>) (List) fs;
2692 >        ArrayList<Future<T>> futures = new ArrayList<Future<T>>(tasks.size());
2693  
2694          boolean done = false;
2695          try {
2696              for (Callable<T> t : tasks) {
2697                  ForkJoinTask<T> f = new ForkJoinTask.AdaptedCallable<T>(t);
2698 +                futures.add(f);
2699                  externalPush(f);
2710                fs.add(f);
2700              }
2701 <            for (ForkJoinTask<T> f : fs)
2702 <                f.quietlyJoin();
2701 >            for (int i = 0, size = futures.size(); i < size; i++)
2702 >                ((ForkJoinTask<?>)futures.get(i)).quietlyJoin();
2703              done = true;
2704              return futures;
2705          } finally {
2706              if (!done)
2707 <                for (ForkJoinTask<T> f : fs)
2708 <                    f.cancel(false);
2707 >                for (int i = 0, size = futures.size(); i < size; i++)
2708 >                    futures.get(i).cancel(false);
2709          }
2710      }
2711  
# Line 2752 | Line 2741 | public class ForkJoinPool extends Abstra
2741       * Returns the targeted parallelism level of the common pool.
2742       *
2743       * @return the targeted parallelism level of the common pool
2744 +     * @since 1.8
2745       */
2746      public static int getCommonPoolParallelism() {
2747 <        return commonPoolParallelism;
2747 >        return commonParallelism;
2748      }
2749  
2750      /**
# Line 3012 | Line 3002 | public class ForkJoinPool extends Abstra
3002       * Possibly initiates an orderly shutdown in which previously
3003       * submitted tasks are executed, but no new tasks will be
3004       * accepted. Invocation has no effect on execution state if this
3005 <     * is the {@link #commonPool}, and no additional effect if
3005 >     * is the {@link #commonPool()}, and no additional effect if
3006       * already shut down.  Tasks that are in the process of being
3007       * submitted concurrently during the course of this method may or
3008       * may not be rejected.
# Line 3030 | Line 3020 | public class ForkJoinPool extends Abstra
3020      /**
3021       * Possibly attempts to cancel and/or stop all tasks, and reject
3022       * all subsequently submitted tasks.  Invocation has no effect on
3023 <     * execution state if this is the {@link #commonPool}, and no
3023 >     * execution state if this is the {@link #commonPool()}, and no
3024       * additional effect if already shut down. Otherwise, tasks that
3025       * are in the process of being submitted or executed concurrently
3026       * during the course of this method may or may not be
# Line 3093 | Line 3083 | public class ForkJoinPool extends Abstra
3083      /**
3084       * Blocks until all tasks have completed execution after a
3085       * shutdown request, or the timeout occurs, or the current thread
3086 <     * is interrupted, whichever happens first. Note that the {@link
3087 <     * #commonPool()} never terminates until program shutdown so
3088 <     * this method will always time out.
3086 >     * is interrupted, whichever happens first. Because the {@link
3087 >     * #commonPool()} never terminates until program shutdown, when
3088 >     * applied to the common pool, this method is equivalent to {@link
3089 >     * #awaitQuiescence} but always returns {@code false}.
3090       *
3091       * @param timeout the maximum time to wait
3092       * @param unit the time unit of the timeout argument
# Line 3105 | Line 3096 | public class ForkJoinPool extends Abstra
3096       */
3097      public boolean awaitTermination(long timeout, TimeUnit unit)
3098          throws InterruptedException {
3099 +        if (Thread.interrupted())
3100 +            throw new InterruptedException();
3101 +        if (this == common) {
3102 +            awaitQuiescence(timeout, unit);
3103 +            return false;
3104 +        }
3105          long nanos = unit.toNanos(timeout);
3106          if (isTerminated())
3107              return true;
# Line 3124 | Line 3121 | public class ForkJoinPool extends Abstra
3121      }
3122  
3123      /**
3124 +     * If called by a ForkJoinTask operating in this pool, equivalent
3125 +     * in effect to {@link ForkJoinTask#helpQuiesce}. Otherwise,
3126 +     * waits and/or attempts to assist performing tasks until this
3127 +     * pool {@link #isQuiescent} or the indicated timeout elapses.
3128 +     *
3129 +     * @param timeout the maximum time to wait
3130 +     * @param unit the time unit of the timeout argument
3131 +     * @return {@code true} if quiescent; {@code false} if the
3132 +     * timeout elapsed.
3133 +     */
3134 +    public boolean awaitQuiescence(long timeout, TimeUnit unit) {
3135 +        long nanos = unit.toNanos(timeout);
3136 +        ForkJoinWorkerThread wt;
3137 +        Thread thread = Thread.currentThread();
3138 +        if ((thread instanceof ForkJoinWorkerThread) &&
3139 +            (wt = (ForkJoinWorkerThread)thread).pool == this) {
3140 +            helpQuiescePool(wt.workQueue);
3141 +            return true;
3142 +        }
3143 +        long startTime = System.nanoTime();
3144 +        WorkQueue[] ws;
3145 +        int r = 0, m;
3146 +        boolean found = true;
3147 +        while (!isQuiescent() && (ws = workQueues) != null &&
3148 +               (m = ws.length - 1) >= 0) {
3149 +            if (!found) {
3150 +                if ((System.nanoTime() - startTime) > nanos)
3151 +                    return false;
3152 +                Thread.yield(); // cannot block
3153 +            }
3154 +            found = false;
3155 +            for (int j = (m + 1) << 2; j >= 0; --j) {
3156 +                ForkJoinTask<?> t; WorkQueue q; int b;
3157 +                if ((q = ws[r++ & m]) != null && (b = q.base) - q.top < 0) {
3158 +                    found = true;
3159 +                    if ((t = q.pollAt(b)) != null) {
3160 +                        if (q.base - q.top < 0)
3161 +                            signalWork(q);
3162 +                        t.doExec();
3163 +                    }
3164 +                    break;
3165 +                }
3166 +            }
3167 +        }
3168 +        return true;
3169 +    }
3170 +
3171 +    /**
3172 +     * Waits and/or attempts to assist performing tasks indefinitely
3173 +     * until the {@link #commonPool()} {@link #isQuiescent}.
3174 +     */
3175 +    static void quiesceCommonPool() {
3176 +        common.awaitQuiescence(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
3177 +    }
3178 +
3179 +    /**
3180       * Interface for extending managed parallelism for tasks running
3181       * in {@link ForkJoinPool}s.
3182       *
# Line 3276 | Line 3329 | public class ForkJoinPool extends Abstra
3329      private static final long QLOCK;
3330  
3331      static {
3332 <        int s; // initialize field offsets for CAS etc
3332 >        // initialize field offsets for CAS etc
3333          try {
3334              U = getUnsafe();
3335              Class<?> k = ForkJoinPool.class;
# Line 3296 | Line 3349 | public class ForkJoinPool extends Abstra
3349                  (wk.getDeclaredField("qlock"));
3350              Class<?> ak = ForkJoinTask[].class;
3351              ABASE = U.arrayBaseOffset(ak);
3352 <            s = U.arrayIndexScale(ak);
3353 <            ASHIFT = 31 - Integer.numberOfLeadingZeros(s);
3352 >            int scale = U.arrayIndexScale(ak);
3353 >            if ((scale & (scale - 1)) != 0)
3354 >                throw new Error("data type scale not a power of two");
3355 >            ASHIFT = 31 - Integer.numberOfLeadingZeros(scale);
3356          } catch (Exception e) {
3357              throw new Error(e);
3358          }
3304        if ((s & (s-1)) != 0)
3305            throw new Error("data type scale not a power of two");
3359  
3360          submitters = new ThreadLocal<Submitter>();
3361          ForkJoinWorkerThreadFactory fac = defaultForkJoinWorkerThreadFactory =
# Line 3339 | Line 3392 | public class ForkJoinPool extends Abstra
3392              par = Runtime.getRuntime().availableProcessors();
3393          if (par > MAX_CAP)
3394              par = MAX_CAP;
3395 <        commonPoolParallelism = par;
3395 >        commonParallelism = par;
3396          long np = (long)(-par); // precompute initial ctl value
3397          long ct = ((np << AC_SHIFT) & AC_MASK) | ((np << TC_SHIFT) & TC_MASK);
3398  
3399 <        commonPool = new ForkJoinPool(par, ct, fac, handler);
3399 >        common = new ForkJoinPool(par, ct, fac, handler);
3400      }
3401  
3349
3402      /**
3403       * Returns a sun.misc.Unsafe.  Suitable for use in a 3rd party package.
3404       * Replace with a simple call to Unsafe.getUnsafe when integrating
# Line 3357 | Line 3409 | public class ForkJoinPool extends Abstra
3409      private static sun.misc.Unsafe getUnsafe() {
3410          try {
3411              return sun.misc.Unsafe.getUnsafe();
3412 <        } catch (SecurityException se) {
3413 <            try {
3414 <                return java.security.AccessController.doPrivileged
3415 <                    (new java.security
3416 <                     .PrivilegedExceptionAction<sun.misc.Unsafe>() {
3417 <                        public sun.misc.Unsafe run() throws Exception {
3418 <                            java.lang.reflect.Field f = sun.misc
3419 <                                .Unsafe.class.getDeclaredField("theUnsafe");
3420 <                            f.setAccessible(true);
3421 <                            return (sun.misc.Unsafe) f.get(null);
3422 <                        }});
3423 <            } catch (java.security.PrivilegedActionException e) {
3424 <                throw new RuntimeException("Could not initialize intrinsics",
3425 <                                           e.getCause());
3426 <            }
3412 >        } catch (SecurityException tryReflectionInstead) {}
3413 >        try {
3414 >            return java.security.AccessController.doPrivileged
3415 >            (new java.security.PrivilegedExceptionAction<sun.misc.Unsafe>() {
3416 >                public sun.misc.Unsafe run() throws Exception {
3417 >                    Class<sun.misc.Unsafe> k = sun.misc.Unsafe.class;
3418 >                    for (java.lang.reflect.Field f : k.getDeclaredFields()) {
3419 >                        f.setAccessible(true);
3420 >                        Object x = f.get(null);
3421 >                        if (k.isInstance(x))
3422 >                            return k.cast(x);
3423 >                    }
3424 >                    throw new NoSuchFieldError("the Unsafe");
3425 >                }});
3426 >        } catch (java.security.PrivilegedActionException e) {
3427 >            throw new RuntimeException("Could not initialize intrinsics",
3428 >                                       e.getCause());
3429          }
3430      }
3377
3431   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines