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.25 by jsr166, Sun Jul 26 05:55:34 2009 UTC vs.
Revision 1.48 by jsr166, Thu Aug 6 06:41:34 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.
85 > * pools with greater than the maximum number result in
86 > * {@code IllegalArgumentException}.
87 > *
88 > * <p>This implementation rejects submitted tasks (that is, by throwing
89 > * {@link RejectedExecutionException}) only when the pool is shut down.
90   *
91   * @since 1.7
92   * @author Doug Lea
# Line 81 | Line 105 | public class ForkJoinPool extends Abstra
105      private static final int MAX_THREADS =  0x7FFF;
106  
107      /**
108 <     * Factory for creating new ForkJoinWorkerThreads.  A
109 <     * ForkJoinWorkerThreadFactory must be defined and used for
110 <     * ForkJoinWorkerThread subclasses that extend base functionality
111 <     * or initialize threads with different contexts.
108 >     * Factory for creating new {@link ForkJoinWorkerThread}s.
109 >     * A {@code ForkJoinWorkerThreadFactory} must be defined and used
110 >     * for {@code ForkJoinWorkerThread} subclasses that extend base
111 >     * functionality or initialize threads with different contexts.
112       */
113      public static interface ForkJoinWorkerThreadFactory {
114          /**
115           * Returns a new worker thread operating in the given pool.
116           *
117           * @param pool the pool this thread works in
118 <         * @throws NullPointerException if pool is null
118 >         * @throws NullPointerException if the pool is null
119           */
120          public ForkJoinWorkerThread newThread(ForkJoinPool pool);
121      }
# Line 311 | Line 335 | public class ForkJoinPool extends Abstra
335      }
336  
337      /**
338 <     * Returns true if argument represents zero active count and
339 <     * nonzero runstate, which is the triggering condition for
338 >     * Returns {@code true} if argument represents zero active count
339 >     * and nonzero runstate, which is the triggering condition for
340       * terminating on shutdown.
341       */
342      private static boolean canTerminateOnShutdown(int c) {
# Line 342 | Line 366 | public class ForkJoinPool extends Abstra
366      // Constructors
367  
368      /**
369 <     * Creates a ForkJoinPool with a pool size equal to the number of
370 <     * processors available on the system, using the default
371 <     * ForkJoinWorkerThreadFactory.
369 >     * Creates a {@code ForkJoinPool} with parallelism equal to {@link
370 >     * java.lang.Runtime#availableProcessors}, and using the {@linkplain
371 >     * #defaultForkJoinWorkerThreadFactory default thread factory}.
372       *
373       * @throws SecurityException if a security manager exists and
374       *         the caller is not permitted to modify threads
# Line 357 | Line 381 | public class ForkJoinPool extends Abstra
381      }
382  
383      /**
384 <     * Creates a ForkJoinPool with the indicated parallelism level
385 <     * threads and using the default ForkJoinWorkerThreadFactory.
384 >     * Creates a {@code ForkJoinPool} with the indicated parallelism
385 >     * level and using the {@linkplain
386 >     * #defaultForkJoinWorkerThreadFactory default thread factory}.
387       *
388 <     * @param parallelism the number of worker threads
388 >     * @param parallelism the parallelism level
389       * @throws IllegalArgumentException if parallelism less than or
390 <     * equal to zero
390 >     *         equal to zero, or greater than implementation limit
391       * @throws SecurityException if a security manager exists and
392       *         the caller is not permitted to modify threads
393       *         because it does not hold {@link
# Line 373 | Line 398 | public class ForkJoinPool extends Abstra
398      }
399  
400      /**
401 <     * Creates a ForkJoinPool with parallelism equal to the number of
402 <     * processors available on the system and using the given
403 <     * ForkJoinWorkerThreadFactory.
401 >     * Creates a {@code ForkJoinPool} with parallelism equal to {@link
402 >     * java.lang.Runtime#availableProcessors}, and using the given
403 >     * thread factory.
404       *
405       * @param factory the factory for creating new threads
406 <     * @throws NullPointerException if factory is null
406 >     * @throws NullPointerException if the factory is null
407       * @throws SecurityException if a security manager exists and
408       *         the caller is not permitted to modify threads
409       *         because it does not hold {@link
# Line 389 | Line 414 | public class ForkJoinPool extends Abstra
414      }
415  
416      /**
417 <     * Creates a ForkJoinPool with the given parallelism and factory.
417 >     * Creates a {@code ForkJoinPool} with the given parallelism and
418 >     * thread factory.
419       *
420 <     * @param parallelism the targeted number of worker threads
420 >     * @param parallelism the parallelism level
421       * @param factory the factory for creating new threads
422       * @throws IllegalArgumentException if parallelism less than or
423 <     * equal to zero, or greater than implementation limit
424 <     * @throws NullPointerException if factory is null
423 >     *         equal to zero, or greater than implementation limit
424 >     * @throws NullPointerException if the factory is null
425       * @throws SecurityException if a security manager exists and
426       *         the caller is not permitted to modify threads
427       *         because it does not hold {@link
# Line 423 | Line 449 | public class ForkJoinPool extends Abstra
449       * Creates a new worker thread using factory.
450       *
451       * @param index the index to assign worker
452 <     * @return new worker, or null of factory failed
452 >     * @return new worker, or null if factory failed
453       */
454      private ForkJoinWorkerThread createWorker(int index) {
455          Thread.UncaughtExceptionHandler h = ueh;
# Line 444 | Line 470 | public class ForkJoinPool extends Abstra
470       * Currently requires size to be a power of two.
471       */
472      private static int arraySizeFor(int poolSize) {
473 <        return (poolSize <= 1) ? 1 :
474 <            (1 << (32 - Integer.numberOfLeadingZeros(poolSize-1)));
473 >        if (poolSize <= 1)
474 >            return 1;
475 >        // See Hackers Delight, sec 3.2
476 >        int c = poolSize >= MAX_THREADS ? MAX_THREADS : (poolSize - 1);
477 >        c |= c >>>  1;
478 >        c |= c >>>  2;
479 >        c |= c >>>  4;
480 >        c |= c >>>  8;
481 >        c |= c >>> 16;
482 >        return c + 1;
483      }
484  
485      /**
# Line 563 | Line 597 | public class ForkJoinPool extends Abstra
597       *
598       * @param task the task
599       * @return the task's result
600 <     * @throws NullPointerException if task is null
601 <     * @throws RejectedExecutionException if pool is shut down
600 >     * @throws NullPointerException if the task is null
601 >     * @throws RejectedExecutionException if the task cannot be
602 >     *         scheduled for execution
603       */
604      public <T> T invoke(ForkJoinTask<T> task) {
605          doSubmit(task);
# Line 575 | Line 610 | public class ForkJoinPool extends Abstra
610       * Arranges for (asynchronous) execution of the given task.
611       *
612       * @param task the task
613 <     * @throws NullPointerException if task is null
614 <     * @throws RejectedExecutionException if pool is shut down
613 >     * @throws NullPointerException if the task is null
614 >     * @throws RejectedExecutionException if the task cannot be
615 >     *         scheduled for execution
616       */
617 <    public <T> void execute(ForkJoinTask<T> task) {
617 >    public void execute(ForkJoinTask<?> task) {
618          doSubmit(task);
619      }
620  
621      // AbstractExecutorService methods
622  
623 +    /**
624 +     * @throws NullPointerException if the task is null
625 +     * @throws RejectedExecutionException if the task cannot be
626 +     *         scheduled for execution
627 +     */
628      public void execute(Runnable task) {
629          ForkJoinTask<?> job;
630 <        if (task instanceof ForkJoinTask) // avoid re-wrap
631 <            job = (ForkJoinTask<?>)task;
630 >        if (task instanceof ForkJoinTask<?>) // avoid re-wrap
631 >            job = (ForkJoinTask<?>) task;
632          else
633 <            job = new AdaptedRunnable<Void>(task, null);
633 >            job = ForkJoinTask.adapt(task, null);
634          doSubmit(job);
635      }
636  
637 +    /**
638 +     * @throws NullPointerException if the task is null
639 +     * @throws RejectedExecutionException if the task cannot be
640 +     *         scheduled for execution
641 +     */
642      public <T> ForkJoinTask<T> submit(Callable<T> task) {
643 <        ForkJoinTask<T> job = new AdaptedCallable<T>(task);
643 >        ForkJoinTask<T> job = ForkJoinTask.adapt(task);
644          doSubmit(job);
645          return job;
646      }
647  
648 +    /**
649 +     * @throws NullPointerException if the task is null
650 +     * @throws RejectedExecutionException if the task cannot be
651 +     *         scheduled for execution
652 +     */
653      public <T> ForkJoinTask<T> submit(Runnable task, T result) {
654 <        ForkJoinTask<T> job = new AdaptedRunnable<T>(task, result);
654 >        ForkJoinTask<T> job = ForkJoinTask.adapt(task, result);
655          doSubmit(job);
656          return job;
657      }
658  
659 +    /**
660 +     * @throws NullPointerException if the task is null
661 +     * @throws RejectedExecutionException if the task cannot be
662 +     *         scheduled for execution
663 +     */
664      public ForkJoinTask<?> submit(Runnable task) {
665          ForkJoinTask<?> job;
666 <        if (task instanceof ForkJoinTask) // avoid re-wrap
667 <            job = (ForkJoinTask<?>)task;
666 >        if (task instanceof ForkJoinTask<?>) // avoid re-wrap
667 >            job = (ForkJoinTask<?>) task;
668          else
669 <            job = new AdaptedRunnable<Void>(task, null);
669 >            job = ForkJoinTask.adapt(task, null);
670          doSubmit(job);
671          return job;
672      }
# Line 620 | Line 676 | public class ForkJoinPool extends Abstra
676       *
677       * @param task the task to submit
678       * @return the task
679 +     * @throws NullPointerException if the task is null
680       * @throws RejectedExecutionException if the task cannot be
681       *         scheduled for execution
625     * @throws NullPointerException if the task is null
682       */
683      public <T> ForkJoinTask<T> submit(ForkJoinTask<T> task) {
684          doSubmit(task);
685          return task;
686      }
687  
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    }
688  
689      /**
690 <     * Adaptor for Callables
690 >     * @throws NullPointerException       {@inheritDoc}
691 >     * @throws RejectedExecutionException {@inheritDoc}
692       */
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    }
685
693      public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) {
694          ArrayList<ForkJoinTask<T>> forkJoinTasks =
695              new ArrayList<ForkJoinTask<T>>(tasks.size());
696          for (Callable<T> task : tasks)
697 <            forkJoinTasks.add(new AdaptedCallable<T>(task));
697 >            forkJoinTasks.add(ForkJoinTask.adapt(task));
698          invoke(new InvokeAll<T>(forkJoinTasks));
699  
700          @SuppressWarnings({"unchecked", "rawtypes"})
# Line 720 | Line 727 | public class ForkJoinPool extends Abstra
727       * Returns the handler for internal worker threads that terminate
728       * due to unrecoverable errors encountered while executing tasks.
729       *
730 <     * @return the handler, or null if none
730 >     * @return the handler, or {@code null} if none
731       */
732      public Thread.UncaughtExceptionHandler getUncaughtExceptionHandler() {
733          Thread.UncaughtExceptionHandler h;
# Line 741 | Line 748 | public class ForkJoinPool extends Abstra
748       * as handler.
749       *
750       * @param h the new handler
751 <     * @return the old handler, or null if none
751 >     * @return the old handler, or {@code null} if none
752       * @throws SecurityException if a security manager exists and
753       *         the caller is not permitted to modify threads
754       *         because it does not hold {@link
# Line 789 | Line 796 | public class ForkJoinPool extends Abstra
796          final ReentrantLock lock = this.workerLock;
797          lock.lock();
798          try {
799 <            if (!isTerminating()) {
799 >            if (isProcessingTasks()) {
800                  int p = this.parallelism;
801                  this.parallelism = parallelism;
802                  if (parallelism > p)
# Line 804 | Line 811 | public class ForkJoinPool extends Abstra
811      }
812  
813      /**
814 <     * Returns the targeted number of worker threads in this pool.
814 >     * Returns the targeted parallelism level of this pool.
815       *
816 <     * @return the targeted number of worker threads in this pool
816 >     * @return the targeted parallelism level of this pool
817       */
818      public int getParallelism() {
819          return parallelism;
# Line 815 | Line 822 | public class ForkJoinPool extends Abstra
822      /**
823       * Returns the number of worker threads that have started but not
824       * yet terminated.  This result returned by this method may differ
825 <     * from {@code getParallelism} when threads are created to
825 >     * from {@link #getParallelism} when threads are created to
826       * maintain parallelism when others are cooperatively blocked.
827       *
828       * @return the number of worker threads
# Line 826 | Line 833 | public class ForkJoinPool extends Abstra
833  
834      /**
835       * Returns the maximum number of threads allowed to exist in the
836 <     * pool, even if there are insufficient unblocked running threads.
836 >     * pool. Unless set using {@link #setMaximumPoolSize}, the
837 >     * maximum is an implementation-defined value designed only to
838 >     * prevent runaway growth.
839       *
840       * @return the maximum
841       */
# Line 836 | Line 845 | public class ForkJoinPool extends Abstra
845  
846      /**
847       * Sets the maximum number of threads allowed to exist in the
848 <     * pool, even if there are insufficient unblocked running threads.
849 <     * Setting this value has no effect on current pool size. It
850 <     * controls construction of new threads.
848 >     * pool. The given value should normally be greater than or equal
849 >     * to the {@link #getParallelism parallelism} level. Setting this
850 >     * value has no effect on current pool size. It controls
851 >     * construction of new threads.
852       *
853 <     * @throws IllegalArgumentException if negative or greater then
853 >     * @throws IllegalArgumentException if negative or greater than
854       * internal implementation limit
855       */
856      public void setMaximumPoolSize(int newMax) {
# Line 851 | Line 861 | public class ForkJoinPool extends Abstra
861  
862  
863      /**
864 <     * Returns true if this pool dynamically maintains its target
865 <     * parallelism level. If false, new threads are added only to
866 <     * avoid possible starvation.
857 <     * This setting is by default true.
864 >     * Returns {@code true} if this pool dynamically maintains its
865 >     * target parallelism level. If false, new threads are added only
866 >     * to avoid possible starvation.  This setting is by default true.
867       *
868 <     * @return true if maintains parallelism
868 >     * @return {@code true} if maintains parallelism
869       */
870      public boolean getMaintainsParallelism() {
871          return maintainsParallelism;
# Line 867 | Line 876 | public class ForkJoinPool extends Abstra
876       * parallelism level. If false, new threads are added only to
877       * avoid possible starvation.
878       *
879 <     * @param enable true to maintains parallelism
879 >     * @param enable {@code true} to maintain parallelism
880       */
881      public void setMaintainsParallelism(boolean enable) {
882          maintainsParallelism = enable;
# Line 878 | Line 887 | public class ForkJoinPool extends Abstra
887       * tasks that are never joined. This mode may be more appropriate
888       * than default locally stack-based mode in applications in which
889       * worker threads only process asynchronous tasks.  This method is
890 <     * designed to be invoked only when pool is quiescent, and
890 >     * designed to be invoked only when the pool is quiescent, and
891       * typically only before any tasks are submitted. The effects of
892       * invocations at other times may be unpredictable.
893       *
894 <     * @param async if true, use locally FIFO scheduling
894 >     * @param async if {@code true}, use locally FIFO scheduling
895       * @return the previous mode
896 +     * @see #getAsyncMode
897       */
898      public boolean setAsyncMode(boolean async) {
899          boolean oldMode = locallyFifo;
# Line 900 | Line 910 | public class ForkJoinPool extends Abstra
910      }
911  
912      /**
913 <     * Returns true if this pool uses local first-in-first-out
913 >     * Returns {@code true} if this pool uses local first-in-first-out
914       * scheduling mode for forked tasks that are never joined.
915       *
916 <     * @return true if this pool uses async mode
916 >     * @return {@code true} if this pool uses async mode
917 >     * @see #setAsyncMode
918       */
919      public boolean getAsyncMode() {
920          return locallyFifo;
# Line 944 | Line 955 | public class ForkJoinPool extends Abstra
955      }
956  
957      /**
958 <     * Returns true if all worker threads are currently idle. An idle
959 <     * worker is one that cannot obtain a task to execute because none
960 <     * are available to steal from other threads, and there are no
961 <     * pending submissions to the pool. This method is conservative;
962 <     * it might not return true immediately upon idleness of all
963 <     * threads, but will eventually become true if threads remain
964 <     * inactive.
958 >     * Returns {@code true} if all worker threads are currently idle.
959 >     * An idle worker is one that cannot obtain a task to execute
960 >     * because none are available to steal from other threads, and
961 >     * there are no pending submissions to the pool. This method is
962 >     * conservative; it might not return {@code true} immediately upon
963 >     * idleness of all threads, but will eventually become true if
964 >     * threads remain inactive.
965       *
966 <     * @return true if all threads are currently idle
966 >     * @return {@code true} if all threads are currently idle
967       */
968      public boolean isQuiescent() {
969          return activeCountOf(runControl) == 0;
# Line 1007 | Line 1018 | public class ForkJoinPool extends Abstra
1018      }
1019  
1020      /**
1021 <     * Returns an estimate of the number tasks submitted to this pool
1022 <     * that have not yet begun executing. This method takes time
1021 >     * Returns an estimate of the number of tasks submitted to this
1022 >     * pool that have not yet begun executing.  This method takes time
1023       * proportional to the number of submissions.
1024       *
1025       * @return the number of queued submissions
# Line 1018 | Line 1029 | public class ForkJoinPool extends Abstra
1029      }
1030  
1031      /**
1032 <     * Returns true if there are any tasks submitted to this pool
1033 <     * that have not yet begun executing.
1032 >     * Returns {@code true} if there are any tasks submitted to this
1033 >     * pool that have not yet begun executing.
1034       *
1035       * @return {@code true} if there are any queued submissions
1036       */
# Line 1032 | Line 1043 | public class ForkJoinPool extends Abstra
1043       * available.  This method may be useful in extensions to this
1044       * class that re-assign work in systems with multiple pools.
1045       *
1046 <     * @return the next submission, or null if none
1046 >     * @return the next submission, or {@code null} if none
1047       */
1048      protected ForkJoinTask<?> pollSubmission() {
1049          return submissionQueue.poll();
# Line 1042 | Line 1053 | public class ForkJoinPool extends Abstra
1053       * Removes all available unexecuted submitted and forked tasks
1054       * from scheduling queues and adds them to the given collection,
1055       * without altering their execution status. These may include
1056 <     * artificially generated or wrapped tasks. This method is designed
1057 <     * to be invoked only when the pool is known to be
1056 >     * artificially generated or wrapped tasks. This method is
1057 >     * designed to be invoked only when the pool is known to be
1058       * quiescent. Invocations at other times may not remove all
1059       * tasks. A failure encountered while attempting to add elements
1060       * to collection {@code c} may result in elements being in
# Line 1055 | Line 1066 | public class ForkJoinPool extends Abstra
1066       * @param c the collection to transfer elements into
1067       * @return the number of elements transferred
1068       */
1069 <    protected int drainTasksTo(Collection<ForkJoinTask<?>> c) {
1069 >    protected int drainTasksTo(Collection<? super ForkJoinTask<?>> c) {
1070          int n = submissionQueue.drainTo(c);
1071          ForkJoinWorkerThread[] ws = workers;
1072          if (ws != null) {
# Line 1121 | Line 1132 | public class ForkJoinPool extends Abstra
1132      public void shutdown() {
1133          checkPermission();
1134          transitionRunStateTo(SHUTDOWN);
1135 <        if (canTerminateOnShutdown(runControl))
1135 >        if (canTerminateOnShutdown(runControl)) {
1136 >            if (workers == null) { // shutting down before workers created
1137 >                final ReentrantLock lock = this.workerLock;
1138 >                lock.lock();
1139 >                try {
1140 >                    if (workers == null) {
1141 >                        terminate();
1142 >                        transitionRunStateTo(TERMINATED);
1143 >                        termination.signalAll();
1144 >                    }
1145 >                } finally {
1146 >                    lock.unlock();
1147 >                }
1148 >            }
1149              terminateOnShutdown();
1150 +        }
1151      }
1152  
1153      /**
1154 <     * Attempts to stop all actively executing tasks, and cancels all
1155 <     * waiting tasks.  Tasks that are in the process of being
1156 <     * submitted or executed concurrently during the course of this
1157 <     * method may or may not be rejected. Unlike some other executors,
1158 <     * this method cancels rather than collects non-executed tasks
1159 <     * upon termination, so always returns an empty list. However, you
1160 <     * can use method {@code drainTasksTo} before invoking this
1161 <     * method to transfer unexecuted tasks to another collection.
1154 >     * Attempts to cancel and/or stop all tasks, and reject all
1155 >     * subsequently submitted tasks.  Tasks that are in the process of
1156 >     * being submitted or executed concurrently during the course of
1157 >     * this method may or may not be rejected. This method cancels
1158 >     * both existing and unexecuted tasks, in order to permit
1159 >     * termination in the presence of task dependencies. So the method
1160 >     * always returns an empty list (unlike the case for some other
1161 >     * Executors).
1162       *
1163       * @return an empty list
1164       * @throws SecurityException if a security manager exists and
# Line 1158 | Line 1183 | public class ForkJoinPool extends Abstra
1183  
1184      /**
1185       * Returns {@code true} if the process of termination has
1186 <     * commenced but possibly not yet completed.
1186 >     * commenced but not yet completed.  This method may be useful for
1187 >     * debugging. A return of {@code true} reported a sufficient
1188 >     * period after shutdown may indicate that submitted tasks have
1189 >     * ignored or suppressed interruption, causing this executor not
1190 >     * to properly terminate.
1191       *
1192 <     * @return {@code true} if terminating
1192 >     * @return {@code true} if terminating but not yet terminated
1193       */
1194      public boolean isTerminating() {
1195 <        return runStateOf(runControl) >= TERMINATING;
1195 >        return runStateOf(runControl) == TERMINATING;
1196      }
1197  
1198      /**
# Line 1176 | Line 1205 | public class ForkJoinPool extends Abstra
1205      }
1206  
1207      /**
1208 +     * Returns true if pool is not terminating or terminated.
1209 +     * Used internally to suppress execution when terminating.
1210 +     */
1211 +    final boolean isProcessingTasks() {
1212 +        return runStateOf(runControl) < TERMINATING;
1213 +    }
1214 +
1215 +    /**
1216       * Blocks until all tasks have completed execution after a shutdown
1217       * request, or the timeout occurs, or the current thread is
1218       * interrupted, whichever happens first.
# Line 1229 | Line 1266 | public class ForkJoinPool extends Abstra
1266                      transitionRunStateTo(TERMINATED);
1267                      termination.signalAll();
1268                  }
1269 <                else if (!isTerminating()) {
1269 >                else if (isProcessingTasks()) {
1270                      tryShrinkWorkerArray();
1271                      tryResumeSpare(true); // allow replacement
1272                  }
# Line 1470 | Line 1507 | public class ForkJoinPool extends Abstra
1507      final void sync(ForkJoinWorkerThread w) {
1508          updateStealCount(w); // Transfer w's count while it is idle
1509  
1510 <        while (!w.isShutdown() && !isTerminating() && !suspendIfSpare(w)) {
1510 >        while (!w.isShutdown() && isProcessingTasks() && !suspendIfSpare(w)) {
1511              long prev = w.lastEventCount;
1512              WaitQueueNode node = null;
1513              WaitQueueNode h;
# Line 1492 | Line 1529 | public class ForkJoinPool extends Abstra
1529      }
1530  
1531      /**
1532 <     * Returns true if worker waiting on sync can proceed:
1532 >     * Returns {@code true} if worker waiting on sync can proceed:
1533       *  - on signal (thread == null)
1534       *  - on event count advance (winning race to notify vs signaller)
1535       *  - on interrupt
# Line 1500 | Line 1537 | public class ForkJoinPool extends Abstra
1537       * If node was not signalled and event count not advanced on exit,
1538       * then we also help advance event count.
1539       *
1540 <     * @return true if node can be released
1540 >     * @return {@code true} if node can be released
1541       */
1542      final boolean syncIsReleasable(WaitQueueNode node) {
1543          long prev = node.count;
# Line 1519 | Line 1556 | public class ForkJoinPool extends Abstra
1556      }
1557  
1558      /**
1559 <     * Returns true if a new sync event occurred since last call to
1560 <     * sync or this method, if so, updating caller's count.
1559 >     * Returns {@code true} if a new sync event occurred since last
1560 >     * call to sync or this method, if so, updating caller's count.
1561       */
1562      final boolean hasNewSyncEvent(ForkJoinWorkerThread w) {
1563          long lc = w.lastEventCount;
# Line 1570 | Line 1607 | public class ForkJoinPool extends Abstra
1607          while (spareStack == null || !tryResumeSpare(dec)) {
1608              int counts = workerCounts;
1609              if (dec || (dec = casWorkerCounts(counts, --counts))) {
1573                // CAS cheat
1610                  if (!needSpare(counts, maintainParallelism))
1611                      break;
1612                  if (joinMe.status < 0)
# Line 1604 | Line 1640 | public class ForkJoinPool extends Abstra
1640      }
1641  
1642      /**
1643 <     * Returns true if a spare thread appears to be needed.  If
1644 <     * maintaining parallelism, returns true when the deficit in
1643 >     * Returns {@code true} if a spare thread appears to be needed.
1644 >     * If maintaining parallelism, returns true when the deficit in
1645       * running threads is more than the surplus of total threads, and
1646       * there is apparently some work to do.  This self-limiting rule
1647       * means that the more threads that have already been added, the
# Line 1675 | Line 1711 | public class ForkJoinPool extends Abstra
1711              for (k = 0; k < len && ws[k] != null; ++k)
1712                  ;
1713          }
1714 <        if (k < len && !isTerminating() && (w = createWorker(k)) != null) {
1714 >        if (k < len && isProcessingTasks() && (w = createWorker(k)) != null) {
1715              ws[k] = w;
1716              w.start();
1717          }
# Line 1773 | Line 1809 | public class ForkJoinPool extends Abstra
1809  
1810      /**
1811       * Interface for extending managed parallelism for tasks running
1812 <     * in ForkJoinPools. A ManagedBlocker provides two methods.
1813 <     * Method {@code isReleasable} must return true if blocking is not
1814 <     * necessary. Method {@code block} blocks the current thread if
1815 <     * necessary (perhaps internally invoking {@code isReleasable}
1816 <     * before actually blocking.).
1812 >     * in {@link ForkJoinPool}s.
1813 >     *
1814 >     * <p>A {@code ManagedBlocker} provides two methods.
1815 >     * Method {@code isReleasable} must return {@code true} if
1816 >     * blocking is not necessary. Method {@code block} blocks the
1817 >     * current thread if necessary (perhaps internally invoking
1818 >     * {@code isReleasable} before actually blocking).
1819       *
1820       * <p>For example, here is a ManagedBlocker based on a
1821       * ReentrantLock:
# Line 1801 | Line 1839 | public class ForkJoinPool extends Abstra
1839           * Possibly blocks the current thread, for example waiting for
1840           * a lock or condition.
1841           *
1842 <         * @return true if no additional blocking is necessary (i.e.,
1843 <         * if isReleasable would return true)
1842 >         * @return {@code true} if no additional blocking is necessary
1843 >         * (i.e., if isReleasable would return true)
1844           * @throws InterruptedException if interrupted while waiting
1845           * (the method is not required to do so, but is allowed to)
1846           */
1847          boolean block() throws InterruptedException;
1848  
1849          /**
1850 <         * Returns true if blocking is unnecessary.
1850 >         * Returns {@code true} if blocking is unnecessary.
1851           */
1852          boolean isReleasable();
1853      }
1854  
1855      /**
1856       * Blocks in accord with the given blocker.  If the current thread
1857 <     * is a ForkJoinWorkerThread, this method possibly arranges for a
1858 <     * spare thread to be activated if necessary to ensure parallelism
1859 <     * while the current thread is blocked.  If
1860 <     * {@code maintainParallelism} is true and the pool supports
1861 <     * it ({@link #getMaintainsParallelism}), this method attempts to
1862 <     * maintain the pool's nominal parallelism. Otherwise it activates
1863 <     * a thread only if necessary to avoid complete starvation. This
1864 <     * option may be preferable when blockages use timeouts, or are
1865 <     * almost always brief.
1857 >     * is a {@link ForkJoinWorkerThread}, this method possibly
1858 >     * arranges for a spare thread to be activated if necessary to
1859 >     * ensure parallelism while the current thread is blocked.
1860 >     *
1861 >     * <p>If {@code maintainParallelism} is {@code true} and the pool
1862 >     * supports it ({@link #getMaintainsParallelism}), this method
1863 >     * attempts to maintain the pool's nominal parallelism. Otherwise
1864 >     * it activates a thread only if necessary to avoid complete
1865 >     * starvation. This option may be preferable when blockages use
1866 >     * timeouts, or are almost always brief.
1867       *
1868 <     * <p> If the caller is not a ForkJoinTask, this method is behaviorally
1869 <     * equivalent to
1868 >     * <p>If the caller is not a {@link ForkJoinTask}, this method is
1869 >     * behaviorally equivalent to
1870       *  <pre> {@code
1871       * while (!blocker.isReleasable())
1872       *   if (blocker.block())
1873       *     return;
1874       * }</pre>
1875 <     * If the caller is a ForkJoinTask, then the pool may first
1876 <     * be expanded to ensure parallelism, and later adjusted.
1875 >     *
1876 >     * If the caller is a {@code ForkJoinTask}, then the pool may
1877 >     * first be expanded to ensure parallelism, and later adjusted.
1878       *
1879       * @param blocker the blocker
1880 <     * @param maintainParallelism if true and supported by this pool,
1881 <     * attempt to maintain the pool's nominal parallelism; otherwise
1882 <     * activate a thread only if necessary to avoid complete
1883 <     * starvation.
1880 >     * @param maintainParallelism if {@code true} and supported by
1881 >     * this pool, attempt to maintain the pool's nominal parallelism;
1882 >     * otherwise activate a thread only if necessary to avoid
1883 >     * complete starvation.
1884       * @throws InterruptedException if blocker.block did so
1885       */
1886      public static void managedBlock(ManagedBlocker blocker,
# Line 1866 | Line 1906 | public class ForkJoinPool extends Abstra
1906          do {} while (!blocker.isReleasable() && !blocker.block());
1907      }
1908  
1909 <    // AbstractExecutorService overrides
1909 >    // AbstractExecutorService overrides.  These rely on undocumented
1910 >    // fact that ForkJoinTask.adapt returns ForkJoinTasks that also
1911 >    // implement RunnableFuture.
1912  
1913      protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
1914 <        return new AdaptedRunnable<T>(runnable, value);
1914 >        return (RunnableFuture<T>) ForkJoinTask.adapt(runnable, value);
1915      }
1916  
1917      protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
1918 <        return new AdaptedCallable<T>(callable);
1877 <    }
1878 <
1879 <
1880 <    // Unsafe mechanics for jsr166y 3rd party package.
1881 <    private static sun.misc.Unsafe getUnsafe() {
1882 <        try {
1883 <            return sun.misc.Unsafe.getUnsafe();
1884 <        } catch (SecurityException se) {
1885 <            try {
1886 <                return java.security.AccessController.doPrivileged
1887 <                    (new java.security.PrivilegedExceptionAction<sun.misc.Unsafe>() {
1888 <                        public sun.misc.Unsafe run() throws Exception {
1889 <                            return getUnsafeByReflection();
1890 <                        }});
1891 <            } catch (java.security.PrivilegedActionException e) {
1892 <                throw new RuntimeException("Could not initialize intrinsics",
1893 <                                           e.getCause());
1894 <            }
1895 <        }
1918 >        return (RunnableFuture<T>) ForkJoinTask.adapt(callable);
1919      }
1920  
1921 <    private static sun.misc.Unsafe getUnsafeByReflection()
1899 <            throws NoSuchFieldException, IllegalAccessException {
1900 <        java.lang.reflect.Field f =
1901 <            sun.misc.Unsafe.class.getDeclaredField("theUnsafe");
1902 <        f.setAccessible(true);
1903 <        return (sun.misc.Unsafe) f.get(null);
1904 <    }
1905 <
1906 <    private static long fieldOffset(String fieldName, Class<?> klazz) {
1907 <        try {
1908 <            return UNSAFE.objectFieldOffset(klazz.getDeclaredField(fieldName));
1909 <        } catch (NoSuchFieldException e) {
1910 <            // Convert Exception to Error
1911 <            NoSuchFieldError error = new NoSuchFieldError(fieldName);
1912 <            error.initCause(e);
1913 <            throw error;
1914 <        }
1915 <    }
1921 >    // Unsafe mechanics
1922  
1923      private static final sun.misc.Unsafe UNSAFE = getUnsafe();
1924      private static final long eventCountOffset =
1925 <        fieldOffset("eventCount", ForkJoinPool.class);
1925 >        objectFieldOffset("eventCount", ForkJoinPool.class);
1926      private static final long workerCountsOffset =
1927 <        fieldOffset("workerCounts", ForkJoinPool.class);
1927 >        objectFieldOffset("workerCounts", ForkJoinPool.class);
1928      private static final long runControlOffset =
1929 <        fieldOffset("runControl", ForkJoinPool.class);
1929 >        objectFieldOffset("runControl", ForkJoinPool.class);
1930      private static final long syncStackOffset =
1931 <        fieldOffset("syncStack",ForkJoinPool.class);
1931 >        objectFieldOffset("syncStack",ForkJoinPool.class);
1932      private static final long spareStackOffset =
1933 <        fieldOffset("spareStack", ForkJoinPool.class);
1933 >        objectFieldOffset("spareStack", ForkJoinPool.class);
1934  
1935      private boolean casEventCount(long cmp, long val) {
1936          return UNSAFE.compareAndSwapLong(this, eventCountOffset, cmp, val);
# Line 1941 | Line 1947 | public class ForkJoinPool extends Abstra
1947      private boolean casBarrierStack(WaitQueueNode cmp, WaitQueueNode val) {
1948          return UNSAFE.compareAndSwapObject(this, syncStackOffset, cmp, val);
1949      }
1950 +
1951 +    private static long objectFieldOffset(String field, Class<?> klazz) {
1952 +        try {
1953 +            return UNSAFE.objectFieldOffset(klazz.getDeclaredField(field));
1954 +        } catch (NoSuchFieldException e) {
1955 +            // Convert Exception to corresponding Error
1956 +            NoSuchFieldError error = new NoSuchFieldError(field);
1957 +            error.initCause(e);
1958 +            throw error;
1959 +        }
1960 +    }
1961 +
1962 +    /**
1963 +     * Returns a sun.misc.Unsafe.  Suitable for use in a 3rd party package.
1964 +     * Replace with a simple call to Unsafe.getUnsafe when integrating
1965 +     * into a jdk.
1966 +     *
1967 +     * @return a sun.misc.Unsafe
1968 +     */
1969 +    private static sun.misc.Unsafe getUnsafe() {
1970 +        try {
1971 +            return sun.misc.Unsafe.getUnsafe();
1972 +        } catch (SecurityException se) {
1973 +            try {
1974 +                return java.security.AccessController.doPrivileged
1975 +                    (new java.security
1976 +                     .PrivilegedExceptionAction<sun.misc.Unsafe>() {
1977 +                        public sun.misc.Unsafe run() throws Exception {
1978 +                            java.lang.reflect.Field f = sun.misc
1979 +                                .Unsafe.class.getDeclaredField("theUnsafe");
1980 +                            f.setAccessible(true);
1981 +                            return (sun.misc.Unsafe) f.get(null);
1982 +                        }});
1983 +            } catch (java.security.PrivilegedActionException e) {
1984 +                throw new RuntimeException("Could not initialize intrinsics",
1985 +                                           e.getCause());
1986 +            }
1987 +        }
1988 +    }
1989   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines