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.5 by jsr166, Thu Mar 19 05:10:42 2009 UTC vs.
Revision 1.16 by jsr166, Thu Jul 23 19:44:46 2009 UTC

# Line 27 | Line 27 | import java.lang.reflect.*;
27   * (eventually blocking if none exist). This makes them efficient when
28   * most tasks spawn other subtasks (as do most ForkJoinTasks), as well
29   * as the mixed execution of some plain Runnable- or Callable- based
30 < * activities along with ForkJoinTasks. Otherwise, other
30 > * activities along with ForkJoinTasks. When setting
31 > * {@code setAsyncMode}, a ForkJoinPools may also be appropriate for
32 > * use with fine-grained tasks that are never joined. Otherwise, other
33   * ExecutorService implementations are typically more appropriate
34   * choices.
35   *
# Line 36 | Line 38 | import java.lang.reflect.*;
38   * adding, suspending, or resuming threads, even if some tasks are
39   * waiting to join others. However, no such adjustments are performed
40   * in the face of blocked IO or other unmanaged synchronization. The
41 < * nested <code>ManagedBlocker</code> interface enables extension of
41 > * nested {@code ManagedBlocker} interface enables extension of
42   * the kinds of synchronization accommodated.  The target parallelism
43 < * level may also be changed dynamically (<code>setParallelism</code>)
44 < * and dynamically thread construction can be limited using methods
45 < * <code>setMaximumPoolSize</code> and/or
46 < * <code>setMaintainsParallelism</code>.
43 > * level may also be changed dynamically ({@code setParallelism})
44 > * and thread construction can be limited using methods
45 > * {@code setMaximumPoolSize} and/or
46 > * {@code setMaintainsParallelism}.
47   *
48   * <p>In addition to execution and lifecycle control methods, this
49   * class provides status check methods (for example
50 < * <code>getStealCount</code>) that are intended to aid in developing,
50 > * {@code getStealCount}) that are intended to aid in developing,
51   * tuning, and monitoring fork/join applications. Also, method
52 < * <code>toString</code> returns indications of pool state in a
52 > * {@code toString} returns indications of pool state in a
53   * convenient form for informal monitoring.
54   *
55   * <p><b>Implementation notes</b>: This implementation restricts the
56   * maximum number of running threads to 32767. Attempts to create
57   * pools with greater than the maximum result in
58   * IllegalArgumentExceptions.
59 + *
60 + * @since 1.7
61 + * @author Doug Lea
62   */
63   public class ForkJoinPool extends AbstractExecutorService {
64  
# Line 79 | Line 84 | public class ForkJoinPool extends Abstra
84           * Returns a new worker thread operating in the given pool.
85           *
86           * @param pool the pool this thread works in
87 <         * @throws NullPointerException if pool is null;
87 >         * @throws NullPointerException if pool is null
88           */
89          public ForkJoinWorkerThread newThread(ForkJoinPool pool);
90      }
# Line 131 | Line 136 | public class ForkJoinPool extends Abstra
136          new AtomicInteger();
137  
138      /**
139 <     * Array holding all worker threads in the pool. Array size must
140 <     * be a power of two.  Updates and replacements are protected by
141 <     * workerLock, but it is always kept in a consistent enough state
142 <     * to be randomly accessed without locking by workers performing
143 <     * work-stealing.
139 >     * Array holding all worker threads in the pool. Initialized upon
140 >     * first use. Array size must be a power of two.  Updates and
141 >     * replacements are protected by workerLock, but it is always kept
142 >     * in a consistent enough state to be randomly accessed without
143 >     * locking by workers performing work-stealing.
144       */
145      volatile ForkJoinWorkerThread[] workers;
146  
# Line 151 | Line 156 | public class ForkJoinPool extends Abstra
156  
157      /**
158       * The uncaught exception handler used when any worker
159 <     * abrupty terminates
159 >     * abruptly terminates
160       */
161      private Thread.UncaughtExceptionHandler ueh;
162  
# Line 204 | Line 209 | public class ForkJoinPool extends Abstra
209      private volatile int parallelism;
210  
211      /**
212 +     * True if use local fifo, not default lifo, for local polling
213 +     */
214 +    private volatile boolean locallyFifo;
215 +
216 +    /**
217       * Holds number of total (i.e., created and not yet terminated)
218       * and running (i.e., not blocked on joins or other managed sync)
219       * threads, packed into one int to ensure consistent snapshot when
220       * making decisions about creating and suspending spare
221       * threads. Updated only by CAS.  Note: CASes in
222 <     * updateRunningCount and preJoin running active count is in low
223 <     * word, so need to be modified if this changes
222 >     * updateRunningCount and preJoin assume that running active count
223 >     * is in low word, so need to be modified if this changes.
224       */
225      private volatile int workerCounts;
226  
# Line 219 | Line 229 | public class ForkJoinPool extends Abstra
229      private static int workerCountsFor(int t, int r) { return (t << 16) + r; }
230  
231      /**
232 <     * Add delta (which may be negative) to running count.  This must
232 >     * Adds delta (which may be negative) to running count.  This must
233       * be called before (with negative arg) and after (with positive)
234 <     * any managed synchronization (i.e., mainly, joins)
234 >     * any managed synchronization (i.e., mainly, joins).
235       * @param delta the number to add
236       */
237      final void updateRunningCount(int delta) {
# Line 230 | Line 240 | public class ForkJoinPool extends Abstra
240      }
241  
242      /**
243 <     * Add delta (which may be negative) to both total and running
243 >     * Adds delta (which may be negative) to both total and running
244       * count.  This must be called upon creation and termination of
245       * worker threads.
246       * @param delta the number to add
# Line 266 | Line 276 | public class ForkJoinPool extends Abstra
276      /**
277       * Try incrementing active count; fail on contention. Called by
278       * workers before/during executing tasks.
279 <     * @return true on success;
279 >     * @return true on success
280       */
281      final boolean tryIncrementActiveCount() {
282          int c = runControl;
# Line 274 | Line 284 | public class ForkJoinPool extends Abstra
284      }
285  
286      /**
287 <     * Try decrementing active count; fail on contention.
288 <     * Possibly trigger termination on success
287 >     * Tries decrementing active count; fails on contention.
288 >     * Possibly triggers termination on success.
289       * Called by workers when they can't find tasks.
290       * @return true on success
291       */
# Line 290 | Line 300 | public class ForkJoinPool extends Abstra
300      }
301  
302      /**
303 <     * Return true if argument represents zero active count and
303 >     * Returns true if argument represents zero active count and
304       * nonzero runstate, which is the triggering condition for
305       * terminating on shutdown.
306       */
# Line 326 | Line 336 | public class ForkJoinPool extends Abstra
336       * @throws SecurityException if a security manager exists and
337       *         the caller is not permitted to modify threads
338       *         because it does not hold {@link
339 <     *         java.lang.RuntimePermission}<code>("modifyThread")</code>,
339 >     *         java.lang.RuntimePermission}{@code ("modifyThread")},
340       */
341      public ForkJoinPool() {
342          this(Runtime.getRuntime().availableProcessors(),
# Line 334 | Line 344 | public class ForkJoinPool extends Abstra
344      }
345  
346      /**
347 <     * Creates a ForkJoinPool with the indicated parellelism level
347 >     * Creates a ForkJoinPool with the indicated parallelism level
348       * threads, and using the default ForkJoinWorkerThreadFactory,
349       * @param parallelism the number of worker threads
350       * @throws IllegalArgumentException if parallelism less than or
# Line 342 | Line 352 | public class ForkJoinPool extends Abstra
352       * @throws SecurityException if a security manager exists and
353       *         the caller is not permitted to modify threads
354       *         because it does not hold {@link
355 <     *         java.lang.RuntimePermission}<code>("modifyThread")</code>,
355 >     *         java.lang.RuntimePermission}{@code ("modifyThread")},
356       */
357      public ForkJoinPool(int parallelism) {
358          this(parallelism, defaultForkJoinWorkerThreadFactory);
# Line 357 | Line 367 | public class ForkJoinPool extends Abstra
367       * @throws SecurityException if a security manager exists and
368       *         the caller is not permitted to modify threads
369       *         because it does not hold {@link
370 <     *         java.lang.RuntimePermission}<code>("modifyThread")</code>,
370 >     *         java.lang.RuntimePermission}{@code ("modifyThread")},
371       */
372      public ForkJoinPool(ForkJoinWorkerThreadFactory factory) {
373          this(Runtime.getRuntime().availableProcessors(), factory);
# Line 369 | Line 379 | public class ForkJoinPool extends Abstra
379       * @param parallelism the targeted number of worker threads
380       * @param factory the factory for creating new threads
381       * @throws IllegalArgumentException if parallelism less than or
382 <     * equal to zero, or greater than implementation limit.
382 >     * equal to zero, or greater than implementation limit
383       * @throws NullPointerException if factory is null
384       * @throws SecurityException if a security manager exists and
385       *         the caller is not permitted to modify threads
386       *         because it does not hold {@link
387 <     *         java.lang.RuntimePermission}<code>("modifyThread")</code>,
387 >     *         java.lang.RuntimePermission}{@code ("modifyThread")},
388       */
389      public ForkJoinPool(int parallelism, ForkJoinWorkerThreadFactory factory) {
390          if (parallelism <= 0 || parallelism > MAX_THREADS)
# Line 391 | Line 401 | public class ForkJoinPool extends Abstra
401          this.termination = workerLock.newCondition();
402          this.stealCount = new AtomicLong();
403          this.submissionQueue = new LinkedTransferQueue<ForkJoinTask<?>>();
404 <        createAndStartInitialWorkers(parallelism);
404 >        // worker array and workers are lazily constructed
405      }
406  
407      /**
# Line 405 | Line 415 | public class ForkJoinPool extends Abstra
415          if (w != null) {
416              w.poolIndex = index;
417              w.setDaemon(true);
418 +            w.setAsyncMode(locallyFifo);
419              w.setName("ForkJoinPool-" + poolNumber + "-worker-" + index);
420              if (h != null)
421                  w.setUncaughtExceptionHandler(h);
# Line 413 | Line 424 | public class ForkJoinPool extends Abstra
424      }
425  
426      /**
427 <     * Return a good size for worker array given pool size.
427 >     * Returns a good size for worker array given pool size.
428       * Currently requires size to be a power of two.
429       */
430      private static int arraySizeFor(int ps) {
# Line 421 | Line 432 | public class ForkJoinPool extends Abstra
432      }
433  
434      /**
435 <     * Create or resize array if necessary to hold newLength
435 >     * Creates or resizes array if necessary to hold newLength.
436 >     * Call only under exclusion.
437 >     *
438       * @return the array
439       */
440      private ForkJoinWorkerThread[] ensureWorkerArrayCapacity(int newLength) {
# Line 439 | Line 452 | public class ForkJoinPool extends Abstra
452       */
453      private void tryShrinkWorkerArray() {
454          ForkJoinWorkerThread[] ws = workers;
455 <        int len = ws.length;
456 <        int last = len - 1;
457 <        while (last >= 0 && ws[last] == null)
458 <            --last;
459 <        int newLength = arraySizeFor(last+1);
460 <        if (newLength < len)
461 <            workers = Arrays.copyOf(ws, newLength);
455 >        if (ws != null) {
456 >            int len = ws.length;
457 >            int last = len - 1;
458 >            while (last >= 0 && ws[last] == null)
459 >                --last;
460 >            int newLength = arraySizeFor(last+1);
461 >            if (newLength < len)
462 >                workers = Arrays.copyOf(ws, newLength);
463 >        }
464      }
465  
466      /**
467 <     * Initial worker array and worker creation and startup. (This
453 <     * must be done under lock to avoid interference by some of the
454 <     * newly started threads while creating others.)
467 >     * Initialize workers if necessary
468       */
469 <    private void createAndStartInitialWorkers(int ps) {
470 <        final ReentrantLock lock = this.workerLock;
471 <        lock.lock();
472 <        try {
473 <            ForkJoinWorkerThread[] ws = ensureWorkerArrayCapacity(ps);
474 <            for (int i = 0; i < ps; ++i) {
475 <                ForkJoinWorkerThread w = createWorker(i);
476 <                if (w != null) {
477 <                    ws[i] = w;
478 <                    w.start();
479 <                    updateWorkerCount(1);
469 >    final void ensureWorkerInitialization() {
470 >        ForkJoinWorkerThread[] ws = workers;
471 >        if (ws == null) {
472 >            final ReentrantLock lock = this.workerLock;
473 >            lock.lock();
474 >            try {
475 >                ws = workers;
476 >                if (ws == null) {
477 >                    int ps = parallelism;
478 >                    ws = ensureWorkerArrayCapacity(ps);
479 >                    for (int i = 0; i < ps; ++i) {
480 >                        ForkJoinWorkerThread w = createWorker(i);
481 >                        if (w != null) {
482 >                            ws[i] = w;
483 >                            w.start();
484 >                            updateWorkerCount(1);
485 >                        }
486 >                    }
487                  }
488 +            } finally {
489 +                lock.unlock();
490              }
469        } finally {
470            lock.unlock();
491          }
492      }
493  
# Line 513 | Line 533 | public class ForkJoinPool extends Abstra
533      private <T> void doSubmit(ForkJoinTask<T> task) {
534          if (isShutdown())
535              throw new RejectedExecutionException();
536 +        if (workers == null)
537 +            ensureWorkerInitialization();
538          submissionQueue.offer(task);
539          signalIdleWorkers();
540      }
# Line 671 | Line 693 | public class ForkJoinPool extends Abstra
693       * @throws SecurityException if a security manager exists and
694       *         the caller is not permitted to modify threads
695       *         because it does not hold {@link
696 <     *         java.lang.RuntimePermission}<code>("modifyThread")</code>,
696 >     *         java.lang.RuntimePermission}{@code ("modifyThread")},
697       */
698      public Thread.UncaughtExceptionHandler
699          setUncaughtExceptionHandler(Thread.UncaughtExceptionHandler h) {
# Line 683 | Line 705 | public class ForkJoinPool extends Abstra
705              old = ueh;
706              ueh = h;
707              ForkJoinWorkerThread[] ws = workers;
708 <            for (int i = 0; i < ws.length; ++i) {
709 <                ForkJoinWorkerThread w = ws[i];
710 <                if (w != null)
711 <                    w.setUncaughtExceptionHandler(h);
708 >            if (ws != null) {
709 >                for (int i = 0; i < ws.length; ++i) {
710 >                    ForkJoinWorkerThread w = ws[i];
711 >                    if (w != null)
712 >                        w.setUncaughtExceptionHandler(h);
713 >                }
714              }
715          } finally {
716              lock.unlock();
# Line 696 | Line 720 | public class ForkJoinPool extends Abstra
720  
721  
722      /**
723 <     * Sets the target paralleism level of this pool.
723 >     * Sets the target parallelism level of this pool.
724       * @param parallelism the target parallelism
725       * @throws IllegalArgumentException if parallelism less than or
726 <     * equal to zero or greater than maximum size bounds.
726 >     * equal to zero or greater than maximum size bounds
727       * @throws SecurityException if a security manager exists and
728       *         the caller is not permitted to modify threads
729       *         because it does not hold {@link
730 <     *         java.lang.RuntimePermission}<code>("modifyThread")</code>,
730 >     *         java.lang.RuntimePermission}{@code ("modifyThread")},
731       */
732      public void setParallelism(int parallelism) {
733          checkPermission();
# Line 738 | Line 762 | public class ForkJoinPool extends Abstra
762      /**
763       * Returns the number of worker threads that have started but not
764       * yet terminated.  This result returned by this method may differ
765 <     * from <code>getParallelism</code> when threads are created to
765 >     * from {@code getParallelism} when threads are created to
766       * maintain parallelism when others are cooperatively blocked.
767       *
768       * @return the number of worker threads
# Line 762 | Line 786 | public class ForkJoinPool extends Abstra
786       * Setting this value has no effect on current pool size. It
787       * controls construction of new threads.
788       * @throws IllegalArgumentException if negative or greater then
789 <     * internal implementation limit.
789 >     * internal implementation limit
790       */
791      public void setMaximumPoolSize(int newMax) {
792          if (newMax < 0 || newMax > MAX_THREADS)
# Line 793 | Line 817 | public class ForkJoinPool extends Abstra
817      }
818  
819      /**
820 +     * Establishes local first-in-first-out scheduling mode for forked
821 +     * tasks that are never joined. This mode may be more appropriate
822 +     * than default locally stack-based mode in applications in which
823 +     * worker threads only process asynchronous tasks.  This method is
824 +     * designed to be invoked only when pool is quiescent, and
825 +     * typically only before any tasks are submitted. The effects of
826 +     * invocations at other times may be unpredictable.
827 +     *
828 +     * @param async if true, use locally FIFO scheduling
829 +     * @return the previous mode
830 +     */
831 +    public boolean setAsyncMode(boolean async) {
832 +        boolean oldMode = locallyFifo;
833 +        locallyFifo = async;
834 +        ForkJoinWorkerThread[] ws = workers;
835 +        if (ws != null) {
836 +            for (int i = 0; i < ws.length; ++i) {
837 +                ForkJoinWorkerThread t = ws[i];
838 +                if (t != null)
839 +                    t.setAsyncMode(async);
840 +            }
841 +        }
842 +        return oldMode;
843 +    }
844 +
845 +    /**
846 +     * Returns true if this pool uses local first-in-first-out
847 +     * scheduling mode for forked tasks that are never joined.
848 +     *
849 +     * @return true if this pool uses async mode
850 +     */
851 +    public boolean getAsyncMode() {
852 +        return locallyFifo;
853 +    }
854 +
855 +    /**
856       * Returns an estimate of the number of worker threads that are
857       * not blocked waiting to join tasks or for other managed
858       * synchronization.
# Line 807 | Line 867 | public class ForkJoinPool extends Abstra
867       * Returns an estimate of the number of threads that are currently
868       * stealing or executing tasks. This method may overestimate the
869       * number of active threads.
870 <     * @return the number of active threads.
870 >     * @return the number of active threads
871       */
872      public int getActiveThreadCount() {
873          return activeCountOf(runControl);
# Line 817 | Line 877 | public class ForkJoinPool extends Abstra
877       * Returns an estimate of the number of threads that are currently
878       * idle waiting for tasks. This method may underestimate the
879       * number of idle threads.
880 <     * @return the number of idle threads.
880 >     * @return the number of idle threads
881       */
882      final int getIdleThreadCount() {
883          int c = runningCountOf(workerCounts) - activeCountOf(runControl);
# Line 846 | Line 906 | public class ForkJoinPool extends Abstra
906       * tuning fork/join programs: In general, steal counts should be
907       * high enough to keep threads busy, but low enough to avoid
908       * overhead and contention across threads.
909 <     * @return the number of steals.
909 >     * @return the number of steals
910       */
911      public long getStealCount() {
912          return stealCount.get();
# Line 869 | Line 929 | public class ForkJoinPool extends Abstra
929       * an approximation, obtained by iterating across all threads in
930       * the pool. This method may be useful for tuning task
931       * granularities.
932 <     * @return the number of queued tasks.
932 >     * @return the number of queued tasks
933       */
934      public long getQueuedTaskCount() {
935          long count = 0;
936          ForkJoinWorkerThread[] ws = workers;
937 <        for (int i = 0; i < ws.length; ++i) {
938 <            ForkJoinWorkerThread t = ws[i];
939 <            if (t != null)
940 <                count += t.getQueueSize();
937 >        if (ws != null) {
938 >            for (int i = 0; i < ws.length; ++i) {
939 >                ForkJoinWorkerThread t = ws[i];
940 >                if (t != null)
941 >                    count += t.getQueueSize();
942 >            }
943          }
944          return count;
945      }
# Line 886 | Line 948 | public class ForkJoinPool extends Abstra
948       * Returns an estimate of the number tasks submitted to this pool
949       * that have not yet begun executing. This method takes time
950       * proportional to the number of submissions.
951 <     * @return the number of queued submissions.
951 >     * @return the number of queued submissions
952       */
953      public int getQueuedSubmissionCount() {
954          return submissionQueue.size();
# Line 895 | Line 957 | public class ForkJoinPool extends Abstra
957      /**
958       * Returns true if there are any tasks submitted to this pool
959       * that have not yet begun executing.
960 <     * @return <code>true</code> if there are any queued submissions.
960 >     * @return {@code true} if there are any queued submissions
961       */
962      public boolean hasQueuedSubmissions() {
963          return !submissionQueue.isEmpty();
# Line 912 | Line 974 | public class ForkJoinPool extends Abstra
974      }
975  
976      /**
977 +     * Removes all available unexecuted submitted and forked tasks
978 +     * from scheduling queues and adds them to the given collection,
979 +     * without altering their execution status. These may include
980 +     * artificially generated or wrapped tasks. This method is designed
981 +     * to be invoked only when the pool is known to be
982 +     * quiescent. Invocations at other times may not remove all
983 +     * tasks. A failure encountered while attempting to add elements
984 +     * to collection {@code c} may result in elements being in
985 +     * neither, either or both collections when the associated
986 +     * exception is thrown.  The behavior of this operation is
987 +     * undefined if the specified collection is modified while the
988 +     * operation is in progress.
989 +     * @param c the collection to transfer elements into
990 +     * @return the number of elements transferred
991 +     */
992 +    protected int drainTasksTo(Collection<ForkJoinTask<?>> c) {
993 +        int n = submissionQueue.drainTo(c);
994 +        ForkJoinWorkerThread[] ws = workers;
995 +        if (ws != null) {
996 +            for (int i = 0; i < ws.length; ++i) {
997 +                ForkJoinWorkerThread w = ws[i];
998 +                if (w != null)
999 +                    n += w.drainTasksTo(c);
1000 +            }
1001 +        }
1002 +        return n;
1003 +    }
1004 +
1005 +    /**
1006       * Returns a string identifying this pool, as well as its state,
1007       * including indications of run state, parallelism level, and
1008       * worker and task counts.
# Line 958 | Line 1049 | public class ForkJoinPool extends Abstra
1049       * @throws SecurityException if a security manager exists and
1050       *         the caller is not permitted to modify threads
1051       *         because it does not hold {@link
1052 <     *         java.lang.RuntimePermission}<code>("modifyThread")</code>,
1052 >     *         java.lang.RuntimePermission}{@code ("modifyThread")},
1053       */
1054      public void shutdown() {
1055          checkPermission();
# Line 972 | Line 1063 | public class ForkJoinPool extends Abstra
1063       * waiting tasks.  Tasks that are in the process of being
1064       * submitted or executed concurrently during the course of this
1065       * method may or may not be rejected. Unlike some other executors,
1066 <     * this method cancels rather than collects non-executed tasks,
1067 <     * so always returns an empty list.
1066 >     * this method cancels rather than collects non-executed tasks
1067 >     * upon termination, so always returns an empty list. However, you
1068 >     * can use method {@code drainTasksTo} before invoking this
1069 >     * method to transfer unexecuted tasks to another collection.
1070       * @return an empty list
1071       * @throws SecurityException if a security manager exists and
1072       *         the caller is not permitted to modify threads
1073       *         because it does not hold {@link
1074 <     *         java.lang.RuntimePermission}<code>("modifyThread")</code>,
1074 >     *         java.lang.RuntimePermission}{@code ("modifyThread")},
1075       */
1076      public List<Runnable> shutdownNow() {
1077          checkPermission();
# Line 987 | Line 1080 | public class ForkJoinPool extends Abstra
1080      }
1081  
1082      /**
1083 <     * Returns <code>true</code> if all tasks have completed following shut down.
1083 >     * Returns {@code true} if all tasks have completed following shut down.
1084       *
1085 <     * @return <code>true</code> if all tasks have completed following shut down
1085 >     * @return {@code true} if all tasks have completed following shut down
1086       */
1087      public boolean isTerminated() {
1088          return runStateOf(runControl) == TERMINATED;
1089      }
1090  
1091      /**
1092 <     * Returns <code>true</code> if the process of termination has
1092 >     * Returns {@code true} if the process of termination has
1093       * commenced but possibly not yet completed.
1094       *
1095 <     * @return <code>true</code> if terminating
1095 >     * @return {@code true} if terminating
1096       */
1097      public boolean isTerminating() {
1098          return runStateOf(runControl) >= TERMINATING;
1099      }
1100  
1101      /**
1102 <     * Returns <code>true</code> if this pool has been shut down.
1102 >     * Returns {@code true} if this pool has been shut down.
1103       *
1104 <     * @return <code>true</code> if this pool has been shut down
1104 >     * @return {@code true} if this pool has been shut down
1105       */
1106      public boolean isShutdown() {
1107          return runStateOf(runControl) >= SHUTDOWN;
# Line 1021 | Line 1114 | public class ForkJoinPool extends Abstra
1114       *
1115       * @param timeout the maximum time to wait
1116       * @param unit the time unit of the timeout argument
1117 <     * @return <code>true</code> if this executor terminated and
1118 <     *         <code>false</code> if the timeout elapsed before termination
1117 >     * @return {@code true} if this executor terminated and
1118 >     *         {@code false} if the timeout elapsed before termination
1119       * @throws InterruptedException if interrupted while waiting
1120       */
1121      public boolean awaitTermination(long timeout, TimeUnit unit)
# Line 1058 | Line 1151 | public class ForkJoinPool extends Abstra
1151          lock.lock();
1152          try {
1153              ForkJoinWorkerThread[] ws = workers;
1154 <            int idx = w.poolIndex;
1155 <            if (idx >= 0 && idx < ws.length && ws[idx] == w)
1156 <                ws[idx] = null;
1157 <            if (totalCountOf(workerCounts) == 0) {
1158 <                terminate(); // no-op if already terminating
1159 <                transitionRunStateTo(TERMINATED);
1160 <                termination.signalAll();
1161 <            }
1162 <            else if (!isTerminating()) {
1163 <                tryShrinkWorkerArray();
1164 <                tryResumeSpare(true); // allow replacement
1154 >            if (ws != null) {
1155 >                int idx = w.poolIndex;
1156 >                if (idx >= 0 && idx < ws.length && ws[idx] == w)
1157 >                    ws[idx] = null;
1158 >                if (totalCountOf(workerCounts) == 0) {
1159 >                    terminate(); // no-op if already terminating
1160 >                    transitionRunStateTo(TERMINATED);
1161 >                    termination.signalAll();
1162 >                }
1163 >                else if (!isTerminating()) {
1164 >                    tryShrinkWorkerArray();
1165 >                    tryResumeSpare(true); // allow replacement
1166 >                }
1167              }
1168          } finally {
1169              lock.unlock();
# Line 1092 | Line 1187 | public class ForkJoinPool extends Abstra
1187      }
1188  
1189      /**
1190 <     * Possibly terminate when on shutdown state
1190 >     * Possibly terminates when on shutdown state.
1191       */
1192      private void terminateOnShutdown() {
1193          if (!hasQueuedSubmissions() && canTerminateOnShutdown(runControl))
# Line 1100 | Line 1195 | public class ForkJoinPool extends Abstra
1195      }
1196  
1197      /**
1198 <     * Clear out and cancel submissions
1198 >     * Clears out and cancels submissions.
1199       */
1200      private void cancelQueuedSubmissions() {
1201          ForkJoinTask<?> task;
# Line 1109 | Line 1204 | public class ForkJoinPool extends Abstra
1204      }
1205  
1206      /**
1207 <     * Clean out worker queues.
1207 >     * Cleans out worker queues.
1208       */
1209      private void cancelQueuedWorkerTasks() {
1210          final ReentrantLock lock = this.workerLock;
1211          lock.lock();
1212          try {
1213              ForkJoinWorkerThread[] ws = workers;
1214 <            for (int i = 0; i < ws.length; ++i) {
1215 <                ForkJoinWorkerThread t = ws[i];
1216 <                if (t != null)
1217 <                    t.cancelTasks();
1214 >            if (ws != null) {
1215 >                for (int i = 0; i < ws.length; ++i) {
1216 >                    ForkJoinWorkerThread t = ws[i];
1217 >                    if (t != null)
1218 >                        t.cancelTasks();
1219 >                }
1220              }
1221          } finally {
1222              lock.unlock();
# Line 1127 | Line 1224 | public class ForkJoinPool extends Abstra
1224      }
1225  
1226      /**
1227 <     * Set each worker's status to terminating. Requires lock to avoid
1228 <     * conflicts with add/remove
1227 >     * Sets each worker's status to terminating. Requires lock to avoid
1228 >     * conflicts with add/remove.
1229       */
1230      private void stopAllWorkers() {
1231          final ReentrantLock lock = this.workerLock;
1232          lock.lock();
1233          try {
1234              ForkJoinWorkerThread[] ws = workers;
1235 <            for (int i = 0; i < ws.length; ++i) {
1236 <                ForkJoinWorkerThread t = ws[i];
1237 <                if (t != null)
1238 <                    t.shutdownNow();
1235 >            if (ws != null) {
1236 >                for (int i = 0; i < ws.length; ++i) {
1237 >                    ForkJoinWorkerThread t = ws[i];
1238 >                    if (t != null)
1239 >                        t.shutdownNow();
1240 >                }
1241              }
1242          } finally {
1243              lock.unlock();
# Line 1146 | Line 1245 | public class ForkJoinPool extends Abstra
1245      }
1246  
1247      /**
1248 <     * Interrupt all unterminated workers.  This is not required for
1248 >     * Interrupts all unterminated workers.  This is not required for
1249       * sake of internal control, but may help unstick user code during
1250       * shutdown.
1251       */
# Line 1155 | Line 1254 | public class ForkJoinPool extends Abstra
1254          lock.lock();
1255          try {
1256              ForkJoinWorkerThread[] ws = workers;
1257 <            for (int i = 0; i < ws.length; ++i) {
1258 <                ForkJoinWorkerThread t = ws[i];
1259 <                if (t != null && !t.isTerminated()) {
1260 <                    try {
1261 <                        t.interrupt();
1262 <                    } catch (SecurityException ignore) {
1257 >            if (ws != null) {
1258 >                for (int i = 0; i < ws.length; ++i) {
1259 >                    ForkJoinWorkerThread t = ws[i];
1260 >                    if (t != null && !t.isTerminated()) {
1261 >                        try {
1262 >                            t.interrupt();
1263 >                        } catch (SecurityException ignore) {
1264 >                        }
1265                      }
1266                  }
1267              }
# Line 1214 | Line 1315 | public class ForkJoinPool extends Abstra
1315          }
1316  
1317          /**
1318 <         * Wake up waiter, returning false if known to already
1318 >         * Wakes up waiter, returning false if known to already
1319           */
1320          boolean signal() {
1321              ForkJoinWorkerThread t = thread;
# Line 1226 | Line 1327 | public class ForkJoinPool extends Abstra
1327          }
1328  
1329          /**
1330 <         * Await release on sync
1330 >         * Awaits release on sync.
1331           */
1332          void awaitSyncRelease(ForkJoinPool p) {
1333              while (thread != null && !p.syncIsReleasable(this))
# Line 1234 | Line 1335 | public class ForkJoinPool extends Abstra
1335          }
1336  
1337          /**
1338 <         * Await resumption as spare
1338 >         * Awaits resumption as spare.
1339           */
1340          void awaitSpareRelease() {
1341              while (thread != null) {
# Line 1274 | Line 1375 | public class ForkJoinPool extends Abstra
1375      }
1376  
1377      /**
1378 <     * Signal threads waiting to poll a task. Because method sync
1378 >     * Signals threads waiting to poll a task. Because method sync
1379       * rechecks availability, it is OK to only proceed if queue
1380       * appears to be non-empty, and OK to skip under contention to
1381       * increment count (since some other thread succeeded).
# Line 1361 | Line 1462 | public class ForkJoinPool extends Abstra
1462      //  Parallelism maintenance
1463  
1464      /**
1465 <     * Decrement running count; if too low, add spare.
1465 >     * Decrements running count; if too low, adds spare.
1466       *
1467       * Conceptually, all we need to do here is add or resume a
1468       * spare thread when one is about to block (and remove or
# Line 1381 | Line 1482 | public class ForkJoinPool extends Abstra
1482       * only be suspended or removed when they are idle, not
1483       * immediately when they aren't needed. So adding threads will
1484       * raise parallelism level for longer than necessary.  Also,
1485 <     * FJ applications often enounter highly transient peaks when
1485 >     * FJ applications often encounter highly transient peaks when
1486       * many threads are blocked joining, but for less time than it
1487       * takes to create or resume spares.
1488       *
# Line 1451 | Line 1552 | public class ForkJoinPool extends Abstra
1552      }
1553  
1554      /**
1555 <     * Add a spare worker if lock available and no more than the
1556 <     * expected numbers of threads exist
1555 >     * Adds a spare worker if lock available and no more than the
1556 >     * expected numbers of threads exist.
1557       * @return true if successful
1558       */
1559      private boolean tryAddSpare(int expectedCounts) {
# Line 1485 | Line 1586 | public class ForkJoinPool extends Abstra
1586      }
1587  
1588      /**
1589 <     * Add the kth spare worker. On entry, pool coounts are already
1589 >     * Adds the kth spare worker. On entry, pool counts are already
1590       * adjusted to reflect addition.
1591       */
1592      private void createAndStartSpare(int k) {
# Line 1507 | Line 1608 | public class ForkJoinPool extends Abstra
1608      }
1609  
1610      /**
1611 <     * Suspend calling thread w if there are excess threads.  Called
1612 <     * only from sync.  Spares are enqueued in a Treiber stack
1613 <     * using the same WaitQueueNodes as barriers.  They are resumed
1614 <     * mainly in preJoin, but are also woken on pool events that
1615 <     * require all threads to check run state.
1611 >     * Suspends calling thread w if there are excess threads.  Called
1612 >     * only from sync.  Spares are enqueued in a Treiber stack using
1613 >     * the same WaitQueueNodes as barriers.  They are resumed mainly
1614 >     * in preJoin, but are also woken on pool events that require all
1615 >     * threads to check run state.
1616       * @param w the caller
1617       */
1618      private boolean suspendIfSpare(ForkJoinWorkerThread w) {
# Line 1532 | Line 1633 | public class ForkJoinPool extends Abstra
1633      }
1634  
1635      /**
1636 <     * Try to pop and resume a spare thread.
1636 >     * Tries to pop and resume a spare thread.
1637       * @param updateCount if true, increment running count on success
1638       * @return true if successful
1639       */
# Line 1550 | Line 1651 | public class ForkJoinPool extends Abstra
1651      }
1652  
1653      /**
1654 <     * Pop and resume all spare threads. Same idea as ensureSync.
1654 >     * Pops and resumes all spare threads. Same idea as ensureSync.
1655       * @return true if any spares released
1656       */
1657      private boolean resumeAllSpares() {
# Line 1568 | Line 1669 | public class ForkJoinPool extends Abstra
1669      }
1670  
1671      /**
1672 <     * Pop and shutdown excessive spare threads. Call only while
1672 >     * Pops and shuts down excessive spare threads. Call only while
1673       * holding lock. This is not guaranteed to eliminate all excess
1674       * threads, only those suspended as spares, which are the ones
1675       * unlikely to be needed in the future.
# Line 1593 | Line 1694 | public class ForkJoinPool extends Abstra
1694      /**
1695       * Interface for extending managed parallelism for tasks running
1696       * in ForkJoinPools. A ManagedBlocker provides two methods.
1697 <     * Method <code>isReleasable</code> must return true if blocking is not
1698 <     * necessary. Method <code>block</code> blocks the current thread
1697 >     * Method {@code isReleasable} must return true if blocking is not
1698 >     * necessary. Method {@code block} blocks the current thread
1699       * if necessary (perhaps internally invoking isReleasable before
1700       * actually blocking.).
1701       * <p>For example, here is a ManagedBlocker based on a
# Line 1620 | Line 1721 | public class ForkJoinPool extends Abstra
1721           * Possibly blocks the current thread, for example waiting for
1722           * a lock or condition.
1723           * @return true if no additional blocking is necessary (i.e.,
1724 <         * if isReleasable would return true).
1724 >         * if isReleasable would return true)
1725           * @throws InterruptedException if interrupted while waiting
1726 <         * (the method is not required to do so, but is allowe to).
1726 >         * (the method is not required to do so, but is allowed to).
1727           */
1728          boolean block() throws InterruptedException;
1729  
# Line 1637 | Line 1738 | public class ForkJoinPool extends Abstra
1738       * is a ForkJoinWorkerThread, this method possibly arranges for a
1739       * spare thread to be activated if necessary to ensure parallelism
1740       * while the current thread is blocked.  If
1741 <     * <code>maintainParallelism</code> is true and the pool supports
1741 >     * {@code maintainParallelism} is true and the pool supports
1742       * it ({@link #getMaintainsParallelism}), this method attempts to
1743       * maintain the pool's nominal parallelism. Otherwise if activates
1744       * a thread only if necessary to avoid complete starvation. This
# Line 1659 | Line 1760 | public class ForkJoinPool extends Abstra
1760       * attempt to maintain the pool's nominal parallelism; otherwise
1761       * activate a thread only if necessary to avoid complete
1762       * starvation.
1763 <     * @throws InterruptedException if blocker.block did so.
1763 >     * @throws InterruptedException if blocker.block did so
1764       */
1765      public static void managedBlock(ManagedBlocker blocker,
1766                                      boolean maintainParallelism)
# Line 1721 | Line 1822 | public class ForkJoinPool extends Abstra
1822  
1823      private static long fieldOffset(String fieldName)
1824              throws NoSuchFieldException {
1825 <        return _unsafe.objectFieldOffset
1825 >        return UNSAFE.objectFieldOffset
1826              (ForkJoinPool.class.getDeclaredField(fieldName));
1827      }
1828  
1829 <    static final Unsafe _unsafe;
1829 >    static final Unsafe UNSAFE;
1830      static final long eventCountOffset;
1831      static final long workerCountsOffset;
1832      static final long runControlOffset;
# Line 1734 | Line 1835 | public class ForkJoinPool extends Abstra
1835  
1836      static {
1837          try {
1838 <            _unsafe = getUnsafe();
1838 >            UNSAFE = getUnsafe();
1839              eventCountOffset = fieldOffset("eventCount");
1840              workerCountsOffset = fieldOffset("workerCounts");
1841              runControlOffset = fieldOffset("runControl");
# Line 1746 | Line 1847 | public class ForkJoinPool extends Abstra
1847      }
1848  
1849      private boolean casEventCount(long cmp, long val) {
1850 <        return _unsafe.compareAndSwapLong(this, eventCountOffset, cmp, val);
1850 >        return UNSAFE.compareAndSwapLong(this, eventCountOffset, cmp, val);
1851      }
1852      private boolean casWorkerCounts(int cmp, int val) {
1853 <        return _unsafe.compareAndSwapInt(this, workerCountsOffset, cmp, val);
1853 >        return UNSAFE.compareAndSwapInt(this, workerCountsOffset, cmp, val);
1854      }
1855      private boolean casRunControl(int cmp, int val) {
1856 <        return _unsafe.compareAndSwapInt(this, runControlOffset, cmp, val);
1856 >        return UNSAFE.compareAndSwapInt(this, runControlOffset, cmp, val);
1857      }
1858      private boolean casSpareStack(WaitQueueNode cmp, WaitQueueNode val) {
1859 <        return _unsafe.compareAndSwapObject(this, spareStackOffset, cmp, val);
1859 >        return UNSAFE.compareAndSwapObject(this, spareStackOffset, cmp, val);
1860      }
1861      private boolean casBarrierStack(WaitQueueNode cmp, WaitQueueNode val) {
1862 <        return _unsafe.compareAndSwapObject(this, syncStackOffset, cmp, val);
1862 >        return UNSAFE.compareAndSwapObject(this, syncStackOffset, cmp, val);
1863      }
1864   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines