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.70 by dl, Sat Sep 4 11:33:53 2010 UTC vs.
Revision 1.81 by jsr166, Mon Sep 20 20:42:36 2010 UTC

# Line 6 | Line 6
6  
7   package jsr166y;
8  
9 import java.util.concurrent.*;
9   import java.util.ArrayList;
10   import java.util.Arrays;
11   import java.util.Collection;
12   import java.util.Collections;
13   import java.util.List;
14 + import java.util.concurrent.AbstractExecutorService;
15 + import java.util.concurrent.Callable;
16 + import java.util.concurrent.ExecutorService;
17 + import java.util.concurrent.Future;
18 + import java.util.concurrent.RejectedExecutionException;
19 + import java.util.concurrent.RunnableFuture;
20 + import java.util.concurrent.TimeUnit;
21 + import java.util.concurrent.TimeoutException;
22 + import java.util.concurrent.atomic.AtomicInteger;
23   import java.util.concurrent.locks.LockSupport;
24   import java.util.concurrent.locks.ReentrantLock;
17 import java.util.concurrent.atomic.AtomicInteger;
18 import java.util.concurrent.CountDownLatch;
25  
26   /**
27   * An {@link ExecutorService} for running {@link ForkJoinTask}s.
# Line 300 | Line 306 | public class ForkJoinPool extends Abstra
306       * about the same time as another is needlessly being created. We
307       * counteract this and related slop in part by requiring resumed
308       * spares to immediately recheck (in preStep) to see whether they
309 <     * they should re-suspend.
309 >     * should re-suspend.
310       *
311       * 6. Killing off unneeded workers. A timeout mechanism is used to
312       * shed unused workers: The oldest (first) event queue waiter uses
# Line 429 | Line 435 | public class ForkJoinPool extends Abstra
435  
436      /**
437       * The wakeup interval (in nanoseconds) for the oldest worker
438 <     * worker waiting for an event invokes tryShutdownUnusedWorker to shrink
439 <     * the number of workers.  The exact value does not matter too
440 <     * much, but should be long enough to slowly release resources
441 <     * during long periods without use without disrupting normal use.
438 >     * waiting for an event to invoke tryShutdownUnusedWorker to
439 >     * shrink the number of workers.  The exact value does not matter
440 >     * too much. It must be short enough to release resources during
441 >     * sustained periods of idleness, but not so short that threads
442 >     * are continually re-created.
443       */
444      private static final long SHRINK_RATE_NANOS =
445          30L * 1000L * 1000L * 1000L; // 2 per minute
# Line 515 | Line 522 | public class ForkJoinPool extends Abstra
522       * Lifecycle control. The low word contains the number of workers
523       * that are (probably) executing tasks. This value is atomically
524       * incremented before a worker gets a task to run, and decremented
525 <     * when worker has no tasks and cannot find any.  Bits 16-18
525 >     * when a worker has no tasks and cannot find any.  Bits 16-18
526       * contain runLevel value. When all are zero, the pool is
527       * running. Level transitions are monotonic (running -> shutdown
528       * -> terminating -> terminated) so each transition adds a bit.
# Line 604 | Line 611 | public class ForkJoinPool extends Abstra
611       * (rarely) necessary when other count updates lag.
612       *
613       * @param dr -- either zero or ONE_RUNNING
614 <     * @param dt == either zero or ONE_TOTAL
614 >     * @param dt -- either zero or ONE_TOTAL
615       */
616      private void decrementWorkerCounts(int dr, int dt) {
617          for (;;) {
# Line 673 | Line 680 | public class ForkJoinPool extends Abstra
680      }
681  
682      /**
683 <     * Nulls out record of worker in workers array
683 >     * Nulls out record of worker in workers array.
684       */
685      private void forgetWorker(ForkJoinWorkerThread w) {
686          int idx = w.poolIndex;
# Line 786 | Line 793 | public class ForkJoinPool extends Abstra
793                                     (workerCounts & RUNNING_COUNT_MASK) <= 1);
794                  long startTime = untimed? 0 : System.nanoTime();
795                  Thread.interrupted();         // clear/ignore interrupt
796 <                if (eventCount != ec || w.runState != 0 ||
797 <                    runState >= TERMINATING)  // recheck after clear
791 <                    break;
796 >                if (eventCount != ec || w.isTerminating())
797 >                    break;                    // recheck after clear
798                  if (untimed)
799                      LockSupport.park(w);
800                  else {
801                      LockSupport.parkNanos(w, SHRINK_RATE_NANOS);
802 <                    if (eventCount != ec || w.runState != 0 ||
797 <                        runState >= TERMINATING)
802 >                    if (eventCount != ec || w.isTerminating())
803                          break;
804                      if (System.nanoTime() - startTime >= SHRINK_RATE_NANOS)
805                          tryShutdownUnusedWorker(ec);
# Line 806 | Line 811 | public class ForkJoinPool extends Abstra
811      // Maintaining parallelism
812  
813      /**
814 <     * Pushes worker onto the spare stack
814 >     * Pushes worker onto the spare stack.
815       */
816      final void pushSpare(ForkJoinWorkerThread w) {
817          int ns = (++w.spareCount << SPARE_COUNT_SHIFT) | (w.poolIndex + 1);
# Line 862 | Line 867 | public class ForkJoinPool extends Abstra
867                       UNSAFE.compareAndSwapInt(this, workerCountsOffset, wc,
868                                                wc + (ONE_RUNNING|ONE_TOTAL))) {
869                  ForkJoinWorkerThread w = null;
870 +                Throwable fail = null;
871                  try {
872                      w = factory.newThread(this);
873 <                } finally { // adjust on null or exceptional factory return
874 <                    if (w == null) {
869 <                        decrementWorkerCounts(ONE_RUNNING, ONE_TOTAL);
870 <                        tryTerminate(false); // handle failure during shutdown
871 <                    }
873 >                } catch (Throwable ex) {
874 >                    fail = ex;
875                  }
876 <                if (w == null)
876 >                if (w == null) { // null or exceptional factory return
877 >                    decrementWorkerCounts(ONE_RUNNING, ONE_TOTAL);
878 >                    tryTerminate(false); // handle failure during shutdown
879 >                    // If originating from an external caller,
880 >                    // propagate exception, else ignore
881 >                    if (fail != null && runState < TERMINATING &&
882 >                        !(Thread.currentThread() instanceof
883 >                          ForkJoinWorkerThread))
884 >                        UNSAFE.throwException(fail);
885                      break;
886 +                }
887                  w.start(recordWorker(w), ueh);
888                  if ((workerCounts >>> TOTAL_COUNT_SHIFT) >= pc) {
889                      int c; // advance event count
# Line 960 | Line 972 | public class ForkJoinPool extends Abstra
972          boolean active = w.active;
973          boolean inactivate = false;
974          int pc = parallelism;
975 <        int rs;
976 <        while (w.runState == 0 && (rs = runState) < TERMINATING) {
975 >        while (w.runState == 0) {
976 >            int rs = runState;
977 >            if (rs >= TERMINATING) { // propagate shutdown
978 >                w.shutdown();
979 >                break;
980 >            }
981              if ((inactivate || (active && (rs & ACTIVE_COUNT_MASK) >= pc)) &&
982                  UNSAFE.compareAndSwapInt(this, runStateOffset, rs, rs - 1))
983                  inactivate = active = w.active = false;
# Line 1089 | Line 1105 | public class ForkJoinPool extends Abstra
1105          return true;
1106      }
1107  
1108 +
1109      /**
1110       * Actions on transition to TERMINATING
1111       *
# Line 1106 | Line 1123 | public class ForkJoinPool extends Abstra
1123                                       c = eventCount, c+1);
1124              eventWaiters = 0L; // clobber lists
1125              spareWaiters = 0;
1126 <            ForkJoinWorkerThread[] ws = workers;
1110 <            int n = ws.length;
1111 <            for (int i = 0; i < n; ++i) {
1112 <                ForkJoinWorkerThread w = ws[i];
1126 >            for (ForkJoinWorkerThread w : workers) {
1127                  if (w != null) {
1128                      w.shutdown();
1129                      if (passes > 0 && !w.isTerminated()) {
1130                          w.cancelTasks();
1131                          LockSupport.unpark(w);
1132 <                        if (passes > 1) {
1132 >                        if (passes > 1 && !w.isInterrupted()) {
1133                              try {
1134                                  w.interrupt();
1135                              } catch (SecurityException ignore) {
# Line 1128 | Line 1142 | public class ForkJoinPool extends Abstra
1142      }
1143  
1144      /**
1145 <     * Clear out and cancel submissions, ignoring exceptions
1145 >     * Clears out and cancels submissions, ignoring exceptions.
1146       */
1147      private void cancelSubmissions() {
1148          ForkJoinTask<?> task;
# Line 1143 | Line 1157 | public class ForkJoinPool extends Abstra
1157      // misc support for ForkJoinWorkerThread
1158  
1159      /**
1160 <     * Returns pool number
1160 >     * Returns pool number.
1161       */
1162      final int getPoolNumber() {
1163          return poolNumber;
1164      }
1165  
1166      /**
1167 <     * Tries to accumulates steal count from a worker, clearing
1168 <     * the worker's value.
1167 >     * Tries to accumulate steal count from a worker, clearing
1168 >     * the worker's value if successful.
1169       *
1170       * @return true if worker steal count now zero
1171       */
# Line 1175 | Line 1189 | public class ForkJoinPool extends Abstra
1189          int pc = parallelism; // use parallelism, not rc
1190          int ac = runState;    // no mask -- artificially boosts during shutdown
1191          // Use exact results for small values, saturate past 4
1192 <        return pc <= ac? 0 : pc >>> 1 <= ac? 1 : pc >>> 2 <= ac? 3 : pc >>> 3;
1192 >        return ((pc <= ac) ? 0 :
1193 >                (pc >>> 1 <= ac) ? 1 :
1194 >                (pc >>> 2 <= ac) ? 3 :
1195 >                pc >>> 3);
1196      }
1197  
1198      // Public and protected methods
# Line 1225 | Line 1242 | public class ForkJoinPool extends Abstra
1242       * use {@link #defaultForkJoinWorkerThreadFactory}.
1243       * @param handler the handler for internal worker threads that
1244       * terminate due to unrecoverable errors encountered while executing
1245 <     * tasks. For default value, use <code>null</code>.
1245 >     * tasks. For default value, use {@code null}.
1246       * @param asyncMode if true,
1247       * establishes local first-in-first-out scheduling mode for forked
1248       * tasks that are never joined. This mode may be more appropriate
1249       * than default locally stack-based mode in applications in which
1250       * worker threads only process event-style asynchronous tasks.
1251 <     * For default value, use <code>false</code>.
1251 >     * For default value, use {@code false}.
1252       * @throws IllegalArgumentException if parallelism less than or
1253       *         equal to zero, or greater than implementation limit
1254       * @throws NullPointerException if the factory is null
# Line 1441 | Line 1458 | public class ForkJoinPool extends Abstra
1458  
1459      /**
1460       * Returns the number of worker threads that have started but not
1461 <     * yet terminated.  This result returned by this method may differ
1461 >     * yet terminated.  The result returned by this method may differ
1462       * from {@link #getParallelism} when threads are created to
1463       * maintain parallelism when others are cooperatively blocked.
1464       *
# Line 1526 | Line 1543 | public class ForkJoinPool extends Abstra
1543       */
1544      public long getQueuedTaskCount() {
1545          long count = 0;
1546 <        ForkJoinWorkerThread[] ws = workers;
1530 <        int n = ws.length;
1531 <        for (int i = 0; i < n; ++i) {
1532 <            ForkJoinWorkerThread w = ws[i];
1546 >        for (ForkJoinWorkerThread w : workers)
1547              if (w != null)
1548                  count += w.getQueueSize();
1535        }
1549          return count;
1550      }
1551  
# Line 1587 | Line 1600 | public class ForkJoinPool extends Abstra
1600       */
1601      protected int drainTasksTo(Collection<? super ForkJoinTask<?>> c) {
1602          int count = submissionQueue.drainTo(c);
1603 <        ForkJoinWorkerThread[] ws = workers;
1591 <        int n = ws.length;
1592 <        for (int i = 0; i < n; ++i) {
1593 <            ForkJoinWorkerThread w = ws[i];
1603 >        for (ForkJoinWorkerThread w : workers)
1604              if (w != null)
1605                  count += w.drainTasksTo(c);
1596        }
1606          return count;
1607      }
1608  
# Line 1697 | Line 1706 | public class ForkJoinPool extends Abstra
1706      }
1707  
1708      /**
1709 +     * Returns true if terminating or terminated. Used by ForkJoinWorkerThread.
1710 +     */
1711 +    final boolean isAtLeastTerminating() {
1712 +        return runState >= TERMINATING;
1713 +    }
1714 +
1715 +    /**
1716       * Returns {@code true} if this pool has been shut down.
1717       *
1718       * @return {@code true} if this pool has been shut down
# Line 1850 | Line 1866 | public class ForkJoinPool extends Abstra
1866      private static final long eventCountOffset =
1867          objectFieldOffset("eventCount", ForkJoinPool.class);
1868      private static final long eventWaitersOffset =
1869 <        objectFieldOffset("eventWaiters",ForkJoinPool.class);
1869 >        objectFieldOffset("eventWaiters", ForkJoinPool.class);
1870      private static final long stealCountOffset =
1871 <        objectFieldOffset("stealCount",ForkJoinPool.class);
1871 >        objectFieldOffset("stealCount", ForkJoinPool.class);
1872      private static final long spareWaitersOffset =
1873 <        objectFieldOffset("spareWaiters",ForkJoinPool.class);
1873 >        objectFieldOffset("spareWaiters", ForkJoinPool.class);
1874  
1875      private static long objectFieldOffset(String field, Class<?> klazz) {
1876          try {

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines