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.27 by jsr166, Sun Jul 26 17:33:37 2009 UTC vs.
Revision 1.44 by dl, Tue Aug 4 11:44:33 2009 UTC

# Line 20 | Line 20 | import java.util.concurrent.atomic.Atomi
20   import java.util.concurrent.atomic.AtomicLong;
21  
22   /**
23 < * An {@link ExecutorService} for running {@link ForkJoinTask}s.  A
24 < * ForkJoinPool provides the entry point for submissions from
25 < * non-ForkJoinTasks, as well as management and monitoring operations.
26 < * Normally a single ForkJoinPool is used for a large number of
27 < * submitted tasks. Otherwise, use would not usually outweigh the
28 < * construction and bookkeeping overhead of creating a large set of
29 < * threads.
23 > * An {@link ExecutorService} for running {@link ForkJoinTask}s.
24 > * A {@code ForkJoinPool} provides the entry point for submissions
25 > * from non-{@code ForkJoinTask}s, as well as management and
26 > * monitoring operations.  
27   *
28 < * <p>ForkJoinPools differ from other kinds of Executors mainly in
29 < * that they provide <em>work-stealing</em>: all threads in the pool
30 < * attempt to find and execute subtasks created by other active tasks
31 < * (eventually blocking if none exist). This makes them efficient when
32 < * most tasks spawn other subtasks (as do most ForkJoinTasks), as well
33 < * as the mixed execution of some plain Runnable- or Callable- based
34 < * activities along with ForkJoinTasks. When setting
35 < * {@code setAsyncMode}, a ForkJoinPools may also be appropriate for
36 < * use with fine-grained tasks that are never joined. Otherwise, other
37 < * ExecutorService implementations are typically more appropriate
38 < * choices.
28 > * <p>A {@code ForkJoinPool} differs from other kinds of {@link
29 > * ExecutorService} mainly by virtue of employing
30 > * <em>work-stealing</em>: all threads in the pool attempt to find and
31 > * execute subtasks created by other active tasks (eventually blocking
32 > * waiting for work if none exist). This enables efficient processing
33 > * when most tasks spawn other subtasks (as do most {@code
34 > * ForkJoinTask}s). A {@code ForkJoinPool} may also be used for mixed
35 > * execution of some plain {@code Runnable}- or {@code Callable}-
36 > * based activities along with {@code ForkJoinTask}s. When setting
37 > * {@linkplain #setAsyncMode async mode}, a {@code ForkJoinPool} may
38 > * also be appropriate for use with fine-grained tasks of any form
39 > * that are never joined. Otherwise, other {@code ExecutorService}
40 > * implementations are typically more appropriate choices.
41   *
42 < * <p>A ForkJoinPool may be constructed with a given parallelism level
43 < * (target pool size), which it attempts to maintain by dynamically
44 < * adding, suspending, or resuming threads, even if some tasks are
45 < * waiting to join others. However, no such adjustments are performed
46 < * in the face of blocked IO or other unmanaged synchronization. The
47 < * nested {@code ManagedBlocker} interface enables extension of
48 < * the kinds of synchronization accommodated.  The target parallelism
49 < * level may also be changed dynamically ({@code setParallelism})
50 < * and thread construction can be limited using methods
51 < * {@code setMaximumPoolSize} and/or
52 < * {@code setMaintainsParallelism}.
42 > * <p>A {@code ForkJoinPool} is constructed with a given target
43 > * parallelism level; by default, equal to the number of available
44 > * processors. Unless configured otherwise via {@link
45 > * #setMaintainsParallelism}, the pool attempts to maintain this
46 > * number of active (or available) threads by dynamically adding,
47 > * suspending, or resuming internal worker threads, even if some tasks
48 > * are stalled waiting to join others. However, no such adjustments
49 > * are performed in the face of blocked IO or other unmanaged
50 > * synchronization. The nested {@link ManagedBlocker} interface
51 > * enables extension of the kinds of synchronization accommodated.
52 > * The target parallelism level may also be changed dynamically
53 > * ({@link #setParallelism}). The total number of threads may be
54 > * limited using method {@link #setMaximumPoolSize}, in which case it
55 > * may become possible for the activities of a pool to stall due to
56 > * the lack of available threads to process new tasks.
57   *
58   * <p>In addition to execution and lifecycle control methods, this
59   * class provides status check methods (for example
60 < * {@code getStealCount}) that are intended to aid in developing,
60 > * {@link #getStealCount}) that are intended to aid in developing,
61   * tuning, and monitoring fork/join applications. Also, method
62 < * {@code toString} returns indications of pool state in a
62 > * {@link #toString} returns indications of pool state in a
63   * convenient form for informal monitoring.
64   *
65 + * <p><b>Sample Usage.</b> Normally a single {@code ForkJoinPool} is
66 + * used for all parallel task execution in a program or subsystem.
67 + * Otherwise, use would not usually outweigh the construction and
68 + * bookkeeping overhead of creating a large set of threads. For
69 + * example, a common pool could be used for the {@code SortTasks}
70 + * illustrated in {@link RecursiveAction}. Because {@code
71 + * ForkJoinPool} uses threads in {@linkplain java.lang.Thread#isDaemon
72 + * daemon} mode, there is typically no need to explicitly {@link
73 + * #shutdown} such a pool upon program exit.
74 + *
75 + * <pre>
76 + * static final ForkJoinPool mainPool = new ForkJoinPool();
77 + * ...
78 + * public void sort(long[] array) {
79 + *   mainPool.invoke(new SortTask(array, 0, array.length));
80 + * }
81 + * </pre>
82 + *
83   * <p><b>Implementation notes</b>: This implementation restricts the
84   * maximum number of running threads to 32767. Attempts to create
85   * pools with greater than the maximum result in
86 < * IllegalArgumentExceptions.
86 > * {@code IllegalArgumentException}.
87   *
88   * @since 1.7
89   * @author Doug Lea
# Line 81 | Line 102 | public class ForkJoinPool extends Abstra
102      private static final int MAX_THREADS =  0x7FFF;
103  
104      /**
105 <     * Factory for creating new ForkJoinWorkerThreads.  A
106 <     * ForkJoinWorkerThreadFactory must be defined and used for
107 <     * ForkJoinWorkerThread subclasses that extend base functionality
108 <     * or initialize threads with different contexts.
105 >     * Factory for creating new {@link ForkJoinWorkerThread}s.
106 >     * A {@code ForkJoinWorkerThreadFactory} must be defined and used
107 >     * for {@code ForkJoinWorkerThread} subclasses that extend base
108 >     * functionality or initialize threads with different contexts.
109       */
110      public static interface ForkJoinWorkerThreadFactory {
111          /**
# Line 311 | Line 332 | public class ForkJoinPool extends Abstra
332      }
333  
334      /**
335 <     * Returns true if argument represents zero active count and
336 <     * nonzero runstate, which is the triggering condition for
335 >     * Returns {@code true} if argument represents zero active count
336 >     * and nonzero runstate, which is the triggering condition for
337       * terminating on shutdown.
338       */
339      private static boolean canTerminateOnShutdown(int c) {
# Line 342 | Line 363 | public class ForkJoinPool extends Abstra
363      // Constructors
364  
365      /**
366 <     * Creates a ForkJoinPool with a pool size equal to the number of
367 <     * processors available on the system, using the default
368 <     * ForkJoinWorkerThreadFactory.
366 >     * Creates a {@code ForkJoinPool} with parallelism equal to {@link
367 >     * java.lang.Runtime#availableProcessors}, and using the {@linkplain
368 >     * #defaultForkJoinWorkerThreadFactory default thread factory}.
369       *
370       * @throws SecurityException if a security manager exists and
371       *         the caller is not permitted to modify threads
# Line 357 | Line 378 | public class ForkJoinPool extends Abstra
378      }
379  
380      /**
381 <     * Creates a ForkJoinPool with the indicated parallelism level
382 <     * threads and using the default ForkJoinWorkerThreadFactory.
381 >     * Creates a {@code ForkJoinPool} with the indicated parallelism
382 >     * level and using the {@linkplain
383 >     * #defaultForkJoinWorkerThreadFactory default thread factory}.
384       *
385 <     * @param parallelism the number of worker threads
385 >     * @param parallelism the parallelism level
386       * @throws IllegalArgumentException if parallelism less than or
387       * equal to zero
388       * @throws SecurityException if a security manager exists and
# Line 373 | Line 395 | public class ForkJoinPool extends Abstra
395      }
396  
397      /**
398 <     * Creates a ForkJoinPool with parallelism equal to the number of
399 <     * processors available on the system and using the given
400 <     * ForkJoinWorkerThreadFactory.
398 >     * Creates a {@code ForkJoinPool} with parallelism equal to {@link
399 >     * java.lang.Runtime#availableProcessors}, and using the given
400 >     * thread factory.
401       *
402       * @param factory the factory for creating new threads
403       * @throws NullPointerException if factory is null
# Line 389 | Line 411 | public class ForkJoinPool extends Abstra
411      }
412  
413      /**
414 <     * Creates a ForkJoinPool with the given parallelism and factory.
414 >     * Creates a {@code ForkJoinPool} with the given parallelism and
415 >     * thread factory.
416       *
417 <     * @param parallelism the targeted number of worker threads
417 >     * @param parallelism the parallelism level
418       * @param factory the factory for creating new threads
419       * @throws IllegalArgumentException if parallelism less than or
420       * equal to zero, or greater than implementation limit
# Line 423 | Line 446 | public class ForkJoinPool extends Abstra
446       * Creates a new worker thread using factory.
447       *
448       * @param index the index to assign worker
449 <     * @return new worker, or null of factory failed
449 >     * @return new worker, or null if factory failed
450       */
451      private ForkJoinWorkerThread createWorker(int index) {
452          Thread.UncaughtExceptionHandler h = ueh;
# Line 444 | Line 467 | public class ForkJoinPool extends Abstra
467       * Currently requires size to be a power of two.
468       */
469      private static int arraySizeFor(int poolSize) {
470 <        return (poolSize <= 1) ? 1 :
471 <            (1 << (32 - Integer.numberOfLeadingZeros(poolSize-1)));
470 >        if (poolSize <= 1)
471 >            return 1;
472 >        // See Hackers Delight, sec 3.2
473 >        int c = poolSize >= MAX_THREADS ? MAX_THREADS : (poolSize - 1);
474 >        c |= c >>>  1;
475 >        c |= c >>>  2;
476 >        c |= c >>>  4;
477 >        c |= c >>>  8;
478 >        c |= c >>> 16;
479 >        return c + 1;
480      }
481  
482      /**
# Line 578 | Line 609 | public class ForkJoinPool extends Abstra
609       * @throws NullPointerException if task is null
610       * @throws RejectedExecutionException if pool is shut down
611       */
612 <    public <T> void execute(ForkJoinTask<T> task) {
612 >    public void execute(ForkJoinTask<?> task) {
613          doSubmit(task);
614      }
615  
# Line 589 | Line 620 | public class ForkJoinPool extends Abstra
620          if (task instanceof ForkJoinTask<?>) // avoid re-wrap
621              job = (ForkJoinTask<?>) task;
622          else
623 <            job = new AdaptedRunnable<Void>(task, null);
623 >            job = ForkJoinTask.adapt(task, null);
624          doSubmit(job);
625      }
626  
627      public <T> ForkJoinTask<T> submit(Callable<T> task) {
628 <        ForkJoinTask<T> job = new AdaptedCallable<T>(task);
628 >        ForkJoinTask<T> job = ForkJoinTask.adapt(task);
629          doSubmit(job);
630          return job;
631      }
632  
633      public <T> ForkJoinTask<T> submit(Runnable task, T result) {
634 <        ForkJoinTask<T> job = new AdaptedRunnable<T>(task, result);
634 >        ForkJoinTask<T> job = ForkJoinTask.adapt(task, result);
635          doSubmit(job);
636          return job;
637      }
# Line 610 | Line 641 | public class ForkJoinPool extends Abstra
641          if (task instanceof ForkJoinTask<?>) // avoid re-wrap
642              job = (ForkJoinTask<?>) task;
643          else
644 <            job = new AdaptedRunnable<Void>(task, null);
644 >            job = ForkJoinTask.adapt(task, null);
645          doSubmit(job);
646          return job;
647      }
# Line 629 | Line 660 | public class ForkJoinPool extends Abstra
660          return task;
661      }
662  
632    /**
633     * Adaptor for Runnables. This implements RunnableFuture
634     * to be compliant with AbstractExecutorService constraints.
635     */
636    static final class AdaptedRunnable<T> extends ForkJoinTask<T>
637        implements RunnableFuture<T> {
638        final Runnable runnable;
639        final T resultOnCompletion;
640        T result;
641        AdaptedRunnable(Runnable runnable, T result) {
642            if (runnable == null) throw new NullPointerException();
643            this.runnable = runnable;
644            this.resultOnCompletion = result;
645        }
646        public T getRawResult() { return result; }
647        public void setRawResult(T v) { result = v; }
648        public boolean exec() {
649            runnable.run();
650            result = resultOnCompletion;
651            return true;
652        }
653        public void run() { invoke(); }
654        private static final long serialVersionUID = 5232453952276885070L;
655    }
656
657    /**
658     * Adaptor for Callables
659     */
660    static final class AdaptedCallable<T> extends ForkJoinTask<T>
661        implements RunnableFuture<T> {
662        final Callable<T> callable;
663        T result;
664        AdaptedCallable(Callable<T> callable) {
665            if (callable == null) throw new NullPointerException();
666            this.callable = callable;
667        }
668        public T getRawResult() { return result; }
669        public void setRawResult(T v) { result = v; }
670        public boolean exec() {
671            try {
672                result = callable.call();
673                return true;
674            } catch (Error err) {
675                throw err;
676            } catch (RuntimeException rex) {
677                throw rex;
678            } catch (Exception ex) {
679                throw new RuntimeException(ex);
680            }
681        }
682        public void run() { invoke(); }
683        private static final long serialVersionUID = 2838392045355241008L;
684    }
663  
664      public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) {
665          ArrayList<ForkJoinTask<T>> forkJoinTasks =
666              new ArrayList<ForkJoinTask<T>>(tasks.size());
667          for (Callable<T> task : tasks)
668 <            forkJoinTasks.add(new AdaptedCallable<T>(task));
668 >            forkJoinTasks.add(ForkJoinTask.adapt(task));
669          invoke(new InvokeAll<T>(forkJoinTasks));
670  
671          @SuppressWarnings({"unchecked", "rawtypes"})
# Line 720 | Line 698 | public class ForkJoinPool extends Abstra
698       * Returns the handler for internal worker threads that terminate
699       * due to unrecoverable errors encountered while executing tasks.
700       *
701 <     * @return the handler, or null if none
701 >     * @return the handler, or {@code null} if none
702       */
703      public Thread.UncaughtExceptionHandler getUncaughtExceptionHandler() {
704          Thread.UncaughtExceptionHandler h;
# Line 741 | Line 719 | public class ForkJoinPool extends Abstra
719       * as handler.
720       *
721       * @param h the new handler
722 <     * @return the old handler, or null if none
722 >     * @return the old handler, or {@code null} if none
723       * @throws SecurityException if a security manager exists and
724       *         the caller is not permitted to modify threads
725       *         because it does not hold {@link
# Line 789 | Line 767 | public class ForkJoinPool extends Abstra
767          final ReentrantLock lock = this.workerLock;
768          lock.lock();
769          try {
770 <            if (!isTerminating()) {
770 >            if (isProcessingTasks()) {
771                  int p = this.parallelism;
772                  this.parallelism = parallelism;
773                  if (parallelism > p)
# Line 804 | Line 782 | public class ForkJoinPool extends Abstra
782      }
783  
784      /**
785 <     * Returns the targeted number of worker threads in this pool.
785 >     * Returns the targeted parallelism level of this pool.
786       *
787 <     * @return the targeted number of worker threads in this pool
787 >     * @return the targeted parallelism level of this pool
788       */
789      public int getParallelism() {
790          return parallelism;
# Line 815 | Line 793 | public class ForkJoinPool extends Abstra
793      /**
794       * Returns the number of worker threads that have started but not
795       * yet terminated.  This result returned by this method may differ
796 <     * from {@code getParallelism} when threads are created to
796 >     * from {@link #getParallelism} when threads are created to
797       * maintain parallelism when others are cooperatively blocked.
798       *
799       * @return the number of worker threads
# Line 826 | Line 804 | public class ForkJoinPool extends Abstra
804  
805      /**
806       * Returns the maximum number of threads allowed to exist in the
807 <     * pool, even if there are insufficient unblocked running threads.
807 >     * pool.  Unless set using {@link #setMaximumPoolSize}, the
808 >     * maximum is an implementation-defined value designed only to
809 >     * prevent runaway growth.
810       *
811       * @return the maximum
812       */
# Line 836 | Line 816 | public class ForkJoinPool extends Abstra
816  
817      /**
818       * Sets the maximum number of threads allowed to exist in the
819 <     * pool, even if there are insufficient unblocked running threads.
820 <     * Setting this value has no effect on current pool size. It
841 <     * controls construction of new threads.
819 >     * pool.  Setting this value has no effect on current pool
820 >     * size. It controls construction of new threads.
821       *
822 <     * @throws IllegalArgumentException if negative or greater then
822 >     * @throws IllegalArgumentException if negative or greater than
823       * internal implementation limit
824       */
825      public void setMaximumPoolSize(int newMax) {
# Line 851 | Line 830 | public class ForkJoinPool extends Abstra
830  
831  
832      /**
833 <     * Returns true if this pool dynamically maintains its target
834 <     * parallelism level. If false, new threads are added only to
835 <     * avoid possible starvation.
857 <     * This setting is by default true.
833 >     * Returns {@code true} if this pool dynamically maintains its
834 >     * target parallelism level. If false, new threads are added only
835 >     * to avoid possible starvation.  This setting is by default true.
836       *
837 <     * @return true if maintains parallelism
837 >     * @return {@code true} if maintains parallelism
838       */
839      public boolean getMaintainsParallelism() {
840          return maintainsParallelism;
# Line 867 | Line 845 | public class ForkJoinPool extends Abstra
845       * parallelism level. If false, new threads are added only to
846       * avoid possible starvation.
847       *
848 <     * @param enable true to maintains parallelism
848 >     * @param enable {@code true} to maintain parallelism
849       */
850      public void setMaintainsParallelism(boolean enable) {
851          maintainsParallelism = enable;
# Line 878 | Line 856 | public class ForkJoinPool extends Abstra
856       * tasks that are never joined. This mode may be more appropriate
857       * than default locally stack-based mode in applications in which
858       * worker threads only process asynchronous tasks.  This method is
859 <     * designed to be invoked only when pool is quiescent, and
859 >     * designed to be invoked only when the pool is quiescent, and
860       * typically only before any tasks are submitted. The effects of
861       * invocations at other times may be unpredictable.
862       *
863 <     * @param async if true, use locally FIFO scheduling
863 >     * @param async if {@code true}, use locally FIFO scheduling
864       * @return the previous mode
865 +     * @see #getAsyncMode
866       */
867      public boolean setAsyncMode(boolean async) {
868          boolean oldMode = locallyFifo;
# Line 900 | Line 879 | public class ForkJoinPool extends Abstra
879      }
880  
881      /**
882 <     * Returns true if this pool uses local first-in-first-out
882 >     * Returns {@code true} if this pool uses local first-in-first-out
883       * scheduling mode for forked tasks that are never joined.
884       *
885 <     * @return true if this pool uses async mode
885 >     * @return {@code true} if this pool uses async mode
886 >     * @see #setAsyncMode
887       */
888      public boolean getAsyncMode() {
889          return locallyFifo;
# Line 944 | Line 924 | public class ForkJoinPool extends Abstra
924      }
925  
926      /**
927 <     * Returns true if all worker threads are currently idle. An idle
928 <     * worker is one that cannot obtain a task to execute because none
929 <     * are available to steal from other threads, and there are no
930 <     * pending submissions to the pool. This method is conservative;
931 <     * it might not return true immediately upon idleness of all
932 <     * threads, but will eventually become true if threads remain
933 <     * inactive.
927 >     * Returns {@code true} if all worker threads are currently idle.
928 >     * An idle worker is one that cannot obtain a task to execute
929 >     * because none are available to steal from other threads, and
930 >     * there are no pending submissions to the pool. This method is
931 >     * conservative; it might not return {@code true} immediately upon
932 >     * idleness of all threads, but will eventually become true if
933 >     * threads remain inactive.
934       *
935 <     * @return true if all threads are currently idle
935 >     * @return {@code true} if all threads are currently idle
936       */
937      public boolean isQuiescent() {
938          return activeCountOf(runControl) == 0;
# Line 1007 | Line 987 | public class ForkJoinPool extends Abstra
987      }
988  
989      /**
990 <     * Returns an estimate of the number tasks submitted to this pool
991 <     * that have not yet begun executing. This method takes time
990 >     * Returns an estimate of the number of tasks submitted to this
991 >     * pool that have not yet begun executing.  This method takes time
992       * proportional to the number of submissions.
993       *
994       * @return the number of queued submissions
# Line 1018 | Line 998 | public class ForkJoinPool extends Abstra
998      }
999  
1000      /**
1001 <     * Returns true if there are any tasks submitted to this pool
1002 <     * that have not yet begun executing.
1001 >     * Returns {@code true} if there are any tasks submitted to this
1002 >     * pool that have not yet begun executing.
1003       *
1004       * @return {@code true} if there are any queued submissions
1005       */
# Line 1032 | Line 1012 | public class ForkJoinPool extends Abstra
1012       * available.  This method may be useful in extensions to this
1013       * class that re-assign work in systems with multiple pools.
1014       *
1015 <     * @return the next submission, or null if none
1015 >     * @return the next submission, or {@code null} if none
1016       */
1017      protected ForkJoinTask<?> pollSubmission() {
1018          return submissionQueue.poll();
# Line 1042 | Line 1022 | public class ForkJoinPool extends Abstra
1022       * Removes all available unexecuted submitted and forked tasks
1023       * from scheduling queues and adds them to the given collection,
1024       * without altering their execution status. These may include
1025 <     * artificially generated or wrapped tasks. This method is designed
1026 <     * to be invoked only when the pool is known to be
1025 >     * artificially generated or wrapped tasks. This method is
1026 >     * designed to be invoked only when the pool is known to be
1027       * quiescent. Invocations at other times may not remove all
1028       * tasks. A failure encountered while attempting to add elements
1029       * to collection {@code c} may result in elements being in
# Line 1055 | Line 1035 | public class ForkJoinPool extends Abstra
1035       * @param c the collection to transfer elements into
1036       * @return the number of elements transferred
1037       */
1038 <    protected int drainTasksTo(Collection<ForkJoinTask<?>> c) {
1038 >    protected int drainTasksTo(Collection<? super ForkJoinTask<?>> c) {
1039          int n = submissionQueue.drainTo(c);
1040          ForkJoinWorkerThread[] ws = workers;
1041          if (ws != null) {
# Line 1121 | Line 1101 | public class ForkJoinPool extends Abstra
1101      public void shutdown() {
1102          checkPermission();
1103          transitionRunStateTo(SHUTDOWN);
1104 <        if (canTerminateOnShutdown(runControl))
1104 >        if (canTerminateOnShutdown(runControl)) {
1105 >            if (workers == null) { // shutting down before workers created
1106 >                final ReentrantLock lock = this.workerLock;
1107 >                lock.lock();
1108 >                try {
1109 >                    if (workers == null) {
1110 >                        terminate();
1111 >                        transitionRunStateTo(TERMINATED);
1112 >                        termination.signalAll();
1113 >                    }
1114 >                } finally {
1115 >                    lock.unlock();
1116 >                }
1117 >            }
1118              terminateOnShutdown();
1119 +        }
1120      }
1121  
1122      /**
1123 <     * Attempts to stop all actively executing tasks, and cancels all
1124 <     * waiting tasks.  Tasks that are in the process of being
1125 <     * submitted or executed concurrently during the course of this
1126 <     * method may or may not be rejected. Unlike some other executors,
1127 <     * this method cancels rather than collects non-executed tasks
1128 <     * upon termination, so always returns an empty list. However, you
1129 <     * can use method {@code drainTasksTo} before invoking this
1130 <     * method to transfer unexecuted tasks to another collection.
1123 >     * Attempts to cancel and/or stop all tasks, and reject all
1124 >     * subsequently submitted tasks.  Tasks that are in the process of
1125 >     * being submitted or executed concurrently during the course of
1126 >     * this method may or may not be rejected. This method cancels
1127 >     * both existing and unexecuted tasks, in order to permit
1128 >     * termination in the presence of task dependencies. So the method
1129 >     * always returns an empty list (unlike the case for some other
1130 >     * Executors).
1131       *
1132       * @return an empty list
1133       * @throws SecurityException if a security manager exists and
# Line 1158 | Line 1152 | public class ForkJoinPool extends Abstra
1152  
1153      /**
1154       * Returns {@code true} if the process of termination has
1155 <     * commenced but possibly not yet completed.
1155 >     * commenced but not yet completed.  This method may be useful for
1156 >     * debugging. A return of {@code true} reported a sufficient
1157 >     * period after shutdown may indicate that submitted tasks have
1158 >     * ignored or suppressed interruption, causing this executor not
1159 >     * to properly terminate.
1160       *
1161 <     * @return {@code true} if terminating
1161 >     * @return {@code true} if terminating but not yet terminated
1162       */
1163      public boolean isTerminating() {
1164 <        return runStateOf(runControl) >= TERMINATING;
1164 >        return runStateOf(runControl) == TERMINATING;
1165      }
1166  
1167      /**
# Line 1176 | Line 1174 | public class ForkJoinPool extends Abstra
1174      }
1175  
1176      /**
1177 +     * Returns true if pool is not terminating or terminated.
1178 +     * Used internally to suppress execution when terminating.
1179 +     */
1180 +    final boolean isProcessingTasks() {
1181 +        return runStateOf(runControl) < TERMINATING;
1182 +    }
1183 +
1184 +    /**
1185       * Blocks until all tasks have completed execution after a shutdown
1186       * request, or the timeout occurs, or the current thread is
1187       * interrupted, whichever happens first.
# Line 1229 | Line 1235 | public class ForkJoinPool extends Abstra
1235                      transitionRunStateTo(TERMINATED);
1236                      termination.signalAll();
1237                  }
1238 <                else if (!isTerminating()) {
1238 >                else if (isProcessingTasks()) {
1239                      tryShrinkWorkerArray();
1240                      tryResumeSpare(true); // allow replacement
1241                  }
# Line 1470 | Line 1476 | public class ForkJoinPool extends Abstra
1476      final void sync(ForkJoinWorkerThread w) {
1477          updateStealCount(w); // Transfer w's count while it is idle
1478  
1479 <        while (!w.isShutdown() && !isTerminating() && !suspendIfSpare(w)) {
1479 >        while (!w.isShutdown() && isProcessingTasks() && !suspendIfSpare(w)) {
1480              long prev = w.lastEventCount;
1481              WaitQueueNode node = null;
1482              WaitQueueNode h;
# Line 1492 | Line 1498 | public class ForkJoinPool extends Abstra
1498      }
1499  
1500      /**
1501 <     * Returns true if worker waiting on sync can proceed:
1501 >     * Returns {@code true} if worker waiting on sync can proceed:
1502       *  - on signal (thread == null)
1503       *  - on event count advance (winning race to notify vs signaller)
1504       *  - on interrupt
# Line 1500 | Line 1506 | public class ForkJoinPool extends Abstra
1506       * If node was not signalled and event count not advanced on exit,
1507       * then we also help advance event count.
1508       *
1509 <     * @return true if node can be released
1509 >     * @return {@code true} if node can be released
1510       */
1511      final boolean syncIsReleasable(WaitQueueNode node) {
1512          long prev = node.count;
# Line 1519 | Line 1525 | public class ForkJoinPool extends Abstra
1525      }
1526  
1527      /**
1528 <     * Returns true if a new sync event occurred since last call to
1529 <     * sync or this method, if so, updating caller's count.
1528 >     * Returns {@code true} if a new sync event occurred since last
1529 >     * call to sync or this method, if so, updating caller's count.
1530       */
1531      final boolean hasNewSyncEvent(ForkJoinWorkerThread w) {
1532          long lc = w.lastEventCount;
# Line 1604 | Line 1610 | public class ForkJoinPool extends Abstra
1610      }
1611  
1612      /**
1613 <     * Returns true if a spare thread appears to be needed.  If
1614 <     * maintaining parallelism, returns true when the deficit in
1613 >     * Returns {@code true} if a spare thread appears to be needed.
1614 >     * If maintaining parallelism, returns true when the deficit in
1615       * running threads is more than the surplus of total threads, and
1616       * there is apparently some work to do.  This self-limiting rule
1617       * means that the more threads that have already been added, the
# Line 1675 | Line 1681 | public class ForkJoinPool extends Abstra
1681              for (k = 0; k < len && ws[k] != null; ++k)
1682                  ;
1683          }
1684 <        if (k < len && !isTerminating() && (w = createWorker(k)) != null) {
1684 >        if (k < len && isProcessingTasks() && (w = createWorker(k)) != null) {
1685              ws[k] = w;
1686              w.start();
1687          }
# Line 1773 | Line 1779 | public class ForkJoinPool extends Abstra
1779  
1780      /**
1781       * Interface for extending managed parallelism for tasks running
1782 <     * in ForkJoinPools. A ManagedBlocker provides two methods.
1783 <     * Method {@code isReleasable} must return true if blocking is not
1784 <     * necessary. Method {@code block} blocks the current thread if
1785 <     * necessary (perhaps internally invoking {@code isReleasable}
1786 <     * before actually blocking.).
1782 >     * in {@link ForkJoinPool}s.
1783 >     *
1784 >     * <p>A {@code ManagedBlocker} provides two methods.
1785 >     * Method {@code isReleasable} must return {@code true} if
1786 >     * blocking is not necessary. Method {@code block} blocks the
1787 >     * current thread if necessary (perhaps internally invoking
1788 >     * {@code isReleasable} before actually blocking).
1789       *
1790       * <p>For example, here is a ManagedBlocker based on a
1791       * ReentrantLock:
# Line 1801 | Line 1809 | public class ForkJoinPool extends Abstra
1809           * Possibly blocks the current thread, for example waiting for
1810           * a lock or condition.
1811           *
1812 <         * @return true if no additional blocking is necessary (i.e.,
1813 <         * if isReleasable would return true)
1812 >         * @return {@code true} if no additional blocking is necessary
1813 >         * (i.e., if isReleasable would return true)
1814           * @throws InterruptedException if interrupted while waiting
1815           * (the method is not required to do so, but is allowed to)
1816           */
1817          boolean block() throws InterruptedException;
1818  
1819          /**
1820 <         * Returns true if blocking is unnecessary.
1820 >         * Returns {@code true} if blocking is unnecessary.
1821           */
1822          boolean isReleasable();
1823      }
1824  
1825      /**
1826       * Blocks in accord with the given blocker.  If the current thread
1827 <     * is a ForkJoinWorkerThread, this method possibly arranges for a
1828 <     * spare thread to be activated if necessary to ensure parallelism
1829 <     * while the current thread is blocked.  If
1830 <     * {@code maintainParallelism} is true and the pool supports
1831 <     * it ({@link #getMaintainsParallelism}), this method attempts to
1832 <     * maintain the pool's nominal parallelism. Otherwise it activates
1833 <     * a thread only if necessary to avoid complete starvation. This
1834 <     * option may be preferable when blockages use timeouts, or are
1835 <     * almost always brief.
1827 >     * is a {@link ForkJoinWorkerThread}, this method possibly
1828 >     * arranges for a spare thread to be activated if necessary to
1829 >     * ensure parallelism while the current thread is blocked.
1830 >     *
1831 >     * <p>If {@code maintainParallelism} is {@code true} and the pool
1832 >     * supports it ({@link #getMaintainsParallelism}), this method
1833 >     * attempts to maintain the pool's nominal parallelism. Otherwise
1834 >     * it activates a thread only if necessary to avoid complete
1835 >     * starvation. This option may be preferable when blockages use
1836 >     * timeouts, or are almost always brief.
1837       *
1838 <     * <p> If the caller is not a ForkJoinTask, this method is behaviorally
1839 <     * equivalent to
1838 >     * <p>If the caller is not a {@link ForkJoinTask}, this method is
1839 >     * behaviorally equivalent to
1840       *  <pre> {@code
1841       * while (!blocker.isReleasable())
1842       *   if (blocker.block())
1843       *     return;
1844       * }</pre>
1845 <     * If the caller is a ForkJoinTask, then the pool may first
1846 <     * be expanded to ensure parallelism, and later adjusted.
1845 >     *
1846 >     * If the caller is a {@code ForkJoinTask}, then the pool may
1847 >     * first be expanded to ensure parallelism, and later adjusted.
1848       *
1849       * @param blocker the blocker
1850 <     * @param maintainParallelism if true and supported by this pool,
1851 <     * attempt to maintain the pool's nominal parallelism; otherwise
1852 <     * activate a thread only if necessary to avoid complete
1853 <     * starvation.
1850 >     * @param maintainParallelism if {@code true} and supported by
1851 >     * this pool, attempt to maintain the pool's nominal parallelism;
1852 >     * otherwise activate a thread only if necessary to avoid
1853 >     * complete starvation.
1854       * @throws InterruptedException if blocker.block did so
1855       */
1856      public static void managedBlock(ManagedBlocker blocker,
# Line 1866 | Line 1876 | public class ForkJoinPool extends Abstra
1876          do {} while (!blocker.isReleasable() && !blocker.block());
1877      }
1878  
1879 <    // AbstractExecutorService overrides
1879 >    // AbstractExecutorService overrides.  These rely on undocumented
1880 >    // fact that ForkJoinTask.adapt returns ForkJoinTasks that also
1881 >    // implement RunnableFuture.
1882  
1883      protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
1884 <        return new AdaptedRunnable<T>(runnable, value);
1884 >        return (RunnableFuture<T>) ForkJoinTask.adapt(runnable, value);
1885      }
1886  
1887      protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
1888 <        return new AdaptedCallable<T>(callable);
1888 >        return (RunnableFuture<T>) ForkJoinTask.adapt(callable);
1889      }
1890  
1891      // Unsafe mechanics

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines