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.66 by dl, Sun Aug 29 23:34:46 2010 UTC vs.
Revision 1.77 by dl, Tue Sep 7 14:43:31 2010 UTC

# Line 6 | Line 6
6  
7   package jsr166y;
8  
9 import java.util.concurrent.*;
10
9   import java.util.ArrayList;
10   import java.util.Arrays;
11   import java.util.Collection;
# Line 69 | Line 67 | import java.util.concurrent.CountDownLat
67   *    <td ALIGN=CENTER> <b>Call from within fork/join computations</b></td>
68   *  </tr>
69   *  <tr>
70 < *    <td> <b>Arange async execution</td>
70 > *    <td> <b>Arrange async execution</td>
71   *    <td> {@link #execute(ForkJoinTask)}</td>
72   *    <td> {@link ForkJoinTask#fork}</td>
73   *  </tr>
# Line 140 | Line 138 | public class ForkJoinPool extends Abstra
138       * Beyond work-stealing support and essential bookkeeping, the
139       * main responsibility of this framework is to take actions when
140       * one worker is waiting to join a task stolen (or always held by)
141 <     * another.  Becauae we are multiplexing many tasks on to a pool
141 >     * another.  Because we are multiplexing many tasks on to a pool
142       * of workers, we can't just let them block (as in Thread.join).
143       * We also cannot just reassign the joiner's run-time stack with
144       * another and replace it later, which would be a form of
# Line 157 | Line 155 | public class ForkJoinPool extends Abstra
155       *      links to try to find such a task.
156       *
157       *   Compensating: Unless there are already enough live threads,
158 <     *      method helpMaintainParallelism() may create or or
158 >     *      method helpMaintainParallelism() may create or
159       *      re-activate a spare thread to compensate for blocked
160       *      joiners until they unblock.
161       *
# Line 226 | Line 224 | public class ForkJoinPool extends Abstra
224       * ManagedBlocker), we may create or resume others to take their
225       * place until they unblock (see below). Implementing this
226       * requires counts of the number of "running" threads (i.e., those
227 <     * that are neither blocked nor artifically suspended) as well as
227 >     * that are neither blocked nor artificially suspended) as well as
228       * the total number.  These two values are packed into one field,
229       * "workerCounts" because we need accurate snapshots when deciding
230       * to create, resume or suspend.  Note however that the
231 <     * correspondance of these counts to reality is not guaranteed. In
231 >     * correspondence of these counts to reality is not guaranteed. In
232       * particular updates for unblocked threads may lag until they
233       * actually wake up.
234       *
# Line 301 | Line 299 | public class ForkJoinPool extends Abstra
299       * about the same time as another is needlessly being created. We
300       * counteract this and related slop in part by requiring resumed
301       * spares to immediately recheck (in preStep) to see whether they
302 <     * they should re-suspend.
302 >     * should re-suspend.
303       *
304       * 6. Killing off unneeded workers. A timeout mechanism is used to
305       * shed unused workers: The oldest (first) event queue waiter uses
# Line 315 | Line 313 | public class ForkJoinPool extends Abstra
313       * 7. Deciding when to create new workers. The main dynamic
314       * control in this class is deciding when to create extra threads
315       * in method helpMaintainParallelism. We would like to keep
316 <     * exactly #parallelism threads running, which is an impossble
316 >     * exactly #parallelism threads running, which is an impossible
317       * task. We always need to create one when the number of running
318       * threads would become zero and all workers are busy. Beyond
319 <     * this, we must rely on heuristics that work well in the the
320 <     * presence of transients phenomena such as GC stalls, dynamic
319 >     * this, we must rely on heuristics that work well in the
320 >     * presence of transient phenomena such as GC stalls, dynamic
321       * compilation, and wake-up lags. These transients are extremely
322       * common -- we are normally trying to fully saturate the CPUs on
323       * a machine, so almost any activity other than running tasks
# Line 346 | Line 344 | public class ForkJoinPool extends Abstra
344       * "while ((local = field) != 0)") which are usually the simplest
345       * way to ensure the required read orderings (which are sometimes
346       * critical). Also several occurrences of the unusual "do {}
347 <     * while(!cas...)" which is the simplest way to force an update of
347 >     * while (!cas...)" which is the simplest way to force an update of
348       * a CAS'ed variable. There are also other coding oddities that
349       * help some methods perform reasonably even when interpreted (not
350       * compiled), at the expense of some messy constructions that
# Line 420 | Line 418 | public class ForkJoinPool extends Abstra
418      /**
419       * The time to block in a join (see awaitJoin) before checking if
420       * a new worker should be (re)started to maintain parallelism
421 <     * level. The value should be short enough to maintain gloabal
421 >     * level. The value should be short enough to maintain global
422       * responsiveness and progress but long enough to avoid
423       * counterproductive firings during GC stalls or unrelated system
424       * activity, and to not bog down systems with continual re-firings
# Line 430 | Line 428 | public class ForkJoinPool extends Abstra
428  
429      /**
430       * The wakeup interval (in nanoseconds) for the oldest worker
431 <     * worker waiting for an event invokes tryShutdownUnusedWorker to shrink
432 <     * the number of workers.  The exact value does not matter too
433 <     * much, but should be long enough to slowly release resources
434 <     * during long periods without use without disrupting normal use.
431 >     * waiting for an event to invoke tryShutdownUnusedWorker to
432 >     * shrink the number of workers.  The exact value does not matter
433 >     * too much. It must be short enough to release resources during
434 >     * sustained periods of idleness, but not so short that threads
435 >     * are continually re-created.
436       */
437      private static final long SHRINK_RATE_NANOS =
438          30L * 1000L * 1000L * 1000L; // 2 per minute
# Line 483 | Line 482 | public class ForkJoinPool extends Abstra
482      private volatile long stealCount;
483  
484      /**
485 <     * Encoded record of top of treiber stack of threads waiting for
485 >     * Encoded record of top of Treiber stack of threads waiting for
486       * events. The top 32 bits contain the count being waited for. The
487       * bottom 16 bits contains one plus the pool index of waiting
488       * worker thread. (Bits 16-31 are unused.)
# Line 502 | Line 501 | public class ForkJoinPool extends Abstra
501      private volatile int eventCount;
502  
503      /**
504 <     * Encoded record of top of treiber stack of spare threads waiting
504 >     * Encoded record of top of Treiber stack of spare threads waiting
505       * for resumption. The top 16 bits contain an arbitrary count to
506       * avoid ABA effects. The bottom 16bits contains one plus the pool
507       * index of waiting worker thread.
# Line 605 | Line 604 | public class ForkJoinPool extends Abstra
604       * (rarely) necessary when other count updates lag.
605       *
606       * @param dr -- either zero or ONE_RUNNING
607 <     * @param dt == either zero or ONE_TOTAL
607 >     * @param dt -- either zero or ONE_TOTAL
608       */
609      private void decrementWorkerCounts(int dr, int dt) {
610          for (;;) {
# Line 674 | Line 673 | public class ForkJoinPool extends Abstra
673      }
674  
675      /**
676 <     * Nulls out record of worker in workers array
676 >     * Nulls out record of worker in workers array.
677       */
678      private void forgetWorker(ForkJoinWorkerThread w) {
679          int idx = w.poolIndex;
680 <        // Locking helps method recordWorker avoid unecessary expansion
680 >        // Locking helps method recordWorker avoid unnecessary expansion
681          final ReentrantLock lock = this.workerLock;
682          lock.lock();
683          try {
# Line 693 | Line 692 | public class ForkJoinPool extends Abstra
692      /**
693       * Final callback from terminating worker.  Removes record of
694       * worker from array, and adjusts counts. If pool is shutting
695 <     * down, tries to complete terminatation.
695 >     * down, tries to complete termination.
696       *
697       * @param w the worker
698       */
# Line 807 | Line 806 | public class ForkJoinPool extends Abstra
806      // Maintaining parallelism
807  
808      /**
809 <     * Pushes worker onto the spare stack
809 >     * Pushes worker onto the spare stack.
810       */
811      final void pushSpare(ForkJoinWorkerThread w) {
812          int ns = (++w.spareCount << SPARE_COUNT_SHIFT) | (w.poolIndex + 1);
# Line 832 | Line 831 | public class ForkJoinPool extends Abstra
831              UNSAFE.compareAndSwapInt(this, spareWaitersOffset,
832                                       sw, w.nextSpare)) {
833              int c; // increment running count before resume
834 <            do {} while(!UNSAFE.compareAndSwapInt
835 <                        (this, workerCountsOffset,
836 <                         c = workerCounts, c + ONE_RUNNING));
834 >            do {} while (!UNSAFE.compareAndSwapInt
835 >                         (this, workerCountsOffset,
836 >                          c = workerCounts, c + ONE_RUNNING));
837              if (w.tryUnsuspend())
838                  LockSupport.unpark(w);
839              else   // back out if w was shutdown
# Line 846 | Line 845 | public class ForkJoinPool extends Abstra
845       * Tries to increase the number of running workers if below target
846       * parallelism: If a spare exists tries to resume it via
847       * tryResumeSpare.  Otherwise, if not enough total workers or all
848 <     * existing workers are busy, adds a new worker. In all casses also
848 >     * existing workers are busy, adds a new worker. In all cases also
849       * helps wake up releasable workers waiting for work.
850       */
851      private void helpMaintainParallelism() {
# Line 985 | Line 984 | public class ForkJoinPool extends Abstra
984                      w.lastEventCount = ec;     // no need to wait
985                      break;
986                  }
987 <                else if (!(inactivate |= active))  
987 >                else if (!(inactivate |= active))
988                      eventSync(w, wec);         // must inactivate before sync
989              }
990              else
# Line 1107 | Line 1106 | public class ForkJoinPool extends Abstra
1106                                       c = eventCount, c+1);
1107              eventWaiters = 0L; // clobber lists
1108              spareWaiters = 0;
1109 <            ForkJoinWorkerThread[] ws = workers;
1111 <            int n = ws.length;
1112 <            for (int i = 0; i < n; ++i) {
1113 <                ForkJoinWorkerThread w = ws[i];
1109 >            for (ForkJoinWorkerThread w : workers) {
1110                  if (w != null) {
1111                      w.shutdown();
1112                      if (passes > 0 && !w.isTerminated()) {
# Line 1129 | Line 1125 | public class ForkJoinPool extends Abstra
1125      }
1126  
1127      /**
1128 <     * Clear out and cancel submissions, ignoring exceptions
1128 >     * Clears out and cancels submissions, ignoring exceptions.
1129       */
1130      private void cancelSubmissions() {
1131          ForkJoinTask<?> task;
# Line 1144 | Line 1140 | public class ForkJoinPool extends Abstra
1140      // misc support for ForkJoinWorkerThread
1141  
1142      /**
1143 <     * Returns pool number
1143 >     * Returns pool number.
1144       */
1145      final int getPoolNumber() {
1146          return poolNumber;
1147      }
1148  
1149      /**
1150 <     * Tries to accumulates steal count from a worker, clearing
1151 <     * the worker's value.
1150 >     * Tries to accumulate steal count from a worker, clearing
1151 >     * the worker's value if successful.
1152       *
1153       * @return true if worker steal count now zero
1154       */
# Line 1174 | Line 1170 | public class ForkJoinPool extends Abstra
1170       */
1171      final int idlePerActive() {
1172          int pc = parallelism; // use parallelism, not rc
1173 <        int ac = runState;    // no mask -- artifically boosts during shutdown
1173 >        int ac = runState;    // no mask -- artificially boosts during shutdown
1174          // Use exact results for small values, saturate past 4
1175 <        return pc <= ac? 0 : pc >>> 1 <= ac? 1 : pc >>> 2 <= ac? 3 : pc >>> 3;
1175 >        return ((pc <= ac) ? 0 :
1176 >                (pc >>> 1 <= ac) ? 1 :
1177 >                (pc >>> 2 <= ac) ? 3 :
1178 >                pc >>> 3);
1179      }
1180  
1181      // Public and protected methods
# Line 1226 | Line 1225 | public class ForkJoinPool extends Abstra
1225       * use {@link #defaultForkJoinWorkerThreadFactory}.
1226       * @param handler the handler for internal worker threads that
1227       * terminate due to unrecoverable errors encountered while executing
1228 <     * tasks. For default value, use <code>null</code>.
1228 >     * tasks. For default value, use {@code null}.
1229       * @param asyncMode if true,
1230       * establishes local first-in-first-out scheduling mode for forked
1231       * tasks that are never joined. This mode may be more appropriate
1232       * than default locally stack-based mode in applications in which
1233       * worker threads only process event-style asynchronous tasks.
1234 <     * For default value, use <code>false</code>.
1234 >     * For default value, use {@code false}.
1235       * @throws IllegalArgumentException if parallelism less than or
1236       *         equal to zero, or greater than implementation limit
1237       * @throws NullPointerException if the factory is null
# Line 1442 | Line 1441 | public class ForkJoinPool extends Abstra
1441  
1442      /**
1443       * Returns the number of worker threads that have started but not
1444 <     * yet terminated.  This result returned by this method may differ
1444 >     * yet terminated.  The result returned by this method may differ
1445       * from {@link #getParallelism} when threads are created to
1446       * maintain parallelism when others are cooperatively blocked.
1447       *
# Line 1527 | Line 1526 | public class ForkJoinPool extends Abstra
1526       */
1527      public long getQueuedTaskCount() {
1528          long count = 0;
1529 <        ForkJoinWorkerThread[] ws = workers;
1531 <        int n = ws.length;
1532 <        for (int i = 0; i < n; ++i) {
1533 <            ForkJoinWorkerThread w = ws[i];
1529 >        for (ForkJoinWorkerThread w : workers)
1530              if (w != null)
1531                  count += w.getQueueSize();
1536        }
1532          return count;
1533      }
1534  
# Line 1588 | Line 1583 | public class ForkJoinPool extends Abstra
1583       */
1584      protected int drainTasksTo(Collection<? super ForkJoinTask<?>> c) {
1585          int count = submissionQueue.drainTo(c);
1586 <        ForkJoinWorkerThread[] ws = workers;
1592 <        int n = ws.length;
1593 <        for (int i = 0; i < n; ++i) {
1594 <            ForkJoinWorkerThread w = ws[i];
1586 >        for (ForkJoinWorkerThread w : workers)
1587              if (w != null)
1588                  count += w.drainTasksTo(c);
1597        }
1589          return count;
1590      }
1591  
# Line 1721 | Line 1712 | public class ForkJoinPool extends Abstra
1712          throws InterruptedException {
1713          try {
1714              return termination.awaitAdvanceInterruptibly(0, timeout, unit) > 0;
1715 <        } catch(TimeoutException ex) {
1715 >        } catch (TimeoutException ex) {
1716              return false;
1717          }
1718      }
# Line 1851 | Line 1842 | public class ForkJoinPool extends Abstra
1842      private static final long eventCountOffset =
1843          objectFieldOffset("eventCount", ForkJoinPool.class);
1844      private static final long eventWaitersOffset =
1845 <        objectFieldOffset("eventWaiters",ForkJoinPool.class);
1845 >        objectFieldOffset("eventWaiters", ForkJoinPool.class);
1846      private static final long stealCountOffset =
1847 <        objectFieldOffset("stealCount",ForkJoinPool.class);
1847 >        objectFieldOffset("stealCount", ForkJoinPool.class);
1848      private static final long spareWaitersOffset =
1849 <        objectFieldOffset("spareWaiters",ForkJoinPool.class);
1849 >        objectFieldOffset("spareWaiters", ForkJoinPool.class);
1850  
1851      private static long objectFieldOffset(String field, Class<?> klazz) {
1852          try {

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines