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.21 by jsr166, Fri Jul 24 23:47:01 2009 UTC vs.
Revision 1.47 by jsr166, Wed Aug 5 15:40:09 2009 UTC

# Line 5 | Line 5
5   */
6  
7   package jsr166y;
8 < import java.util.*;
8 >
9   import java.util.concurrent.*;
10 < import java.util.concurrent.locks.*;
11 < import java.util.concurrent.atomic.*;
10 >
11 > import java.util.ArrayList;
12 > import java.util.Arrays;
13 > import java.util.Collection;
14 > import java.util.Collections;
15 > import java.util.List;
16 > import java.util.concurrent.locks.Condition;
17 > import java.util.concurrent.locks.LockSupport;
18 > import java.util.concurrent.locks.ReentrantLock;
19 > import java.util.concurrent.atomic.AtomicInteger;
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
18 < * submitted tasks. Otherwise, use would not usually outweigh the
19 < * construction and bookkeeping overhead of creating a large set of
20 < * 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 72 | 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 302 | 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 333 | 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 348 | 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
387 >     *         equal to zero, or greater than implementation limit
388       * @throws SecurityException if a security manager exists and
389       *         the caller is not permitted to modify threads
390       *         because it does not hold {@link
# Line 364 | 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 380 | 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
420 >     *         equal to zero, or greater than implementation limit
421       * @throws NullPointerException if factory is null
422       * @throws SecurityException if a security manager exists and
423       *         the caller is not permitted to modify threads
# Line 414 | 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 435 | 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 539 | Line 579 | public class ForkJoinPool extends Abstra
579       * Common code for execute, invoke and submit
580       */
581      private <T> void doSubmit(ForkJoinTask<T> task) {
582 +        if (task == null)
583 +            throw new NullPointerException();
584          if (isShutdown())
585              throw new RejectedExecutionException();
586          if (workers == null)
# Line 567 | 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  
616      // AbstractExecutorService methods
617  
618      public void execute(Runnable task) {
619 <        doSubmit(new AdaptedRunnable<Void>(task, null));
619 >        ForkJoinTask<?> job;
620 >        if (task instanceof ForkJoinTask<?>) // avoid re-wrap
621 >            job = (ForkJoinTask<?>) task;
622 >        else
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      }
638  
639      public ForkJoinTask<?> submit(Runnable task) {
640 <        ForkJoinTask<Void> job = new AdaptedRunnable<Void>(task, null);
640 >        ForkJoinTask<?> job;
641 >        if (task instanceof ForkJoinTask<?>) // avoid re-wrap
642 >            job = (ForkJoinTask<?>) task;
643 >        else
644 >            job = ForkJoinTask.adapt(task, null);
645          doSubmit(job);
646          return job;
647      }
648  
649      /**
650 <     * Adaptor for Runnables. This implements RunnableFuture
651 <     * to be compliant with AbstractExecutorService constraints.
650 >     * Submits a ForkJoinTask for execution.
651 >     *
652 >     * @param task the task to submit
653 >     * @return the task
654 >     * @throws RejectedExecutionException if the task cannot be
655 >     *         scheduled for execution
656 >     * @throws NullPointerException if the task is null
657       */
658 <    static final class AdaptedRunnable<T> extends ForkJoinTask<T>
659 <        implements RunnableFuture<T> {
660 <        final Runnable runnable;
605 <        final T resultOnCompletion;
606 <        T result;
607 <        AdaptedRunnable(Runnable runnable, T result) {
608 <            if (runnable == null) throw new NullPointerException();
609 <            this.runnable = runnable;
610 <            this.resultOnCompletion = result;
611 <        }
612 <        public T getRawResult() { return result; }
613 <        public void setRawResult(T v) { result = v; }
614 <        public boolean exec() {
615 <            runnable.run();
616 <            result = resultOnCompletion;
617 <            return true;
618 <        }
619 <        public void run() { invoke(); }
620 <        private static final long serialVersionUID = 5232453952276885070L;
658 >    public <T> ForkJoinTask<T> submit(ForkJoinTask<T> task) {
659 >        doSubmit(task);
660 >        return task;
661      }
662  
623    /**
624     * Adaptor for Callables
625     */
626    static final class AdaptedCallable<T> extends ForkJoinTask<T>
627        implements RunnableFuture<T> {
628        final Callable<T> callable;
629        T result;
630        AdaptedCallable(Callable<T> callable) {
631            if (callable == null) throw new NullPointerException();
632            this.callable = callable;
633        }
634        public T getRawResult() { return result; }
635        public void setRawResult(T v) { result = v; }
636        public boolean exec() {
637            try {
638                result = callable.call();
639                return true;
640            } catch (Error err) {
641                throw err;
642            } catch (RuntimeException rex) {
643                throw rex;
644            } catch (Exception ex) {
645                throw new RuntimeException(ex);
646            }
647        }
648        public void run() { invoke(); }
649        private static final long serialVersionUID = 2838392045355241008L;
650    }
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 686 | 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 707 | 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 755 | 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 770 | 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 781 | 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 792 | 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 802 | 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
821 <     * controls construction of new threads.
819 >     * pool. The given value should normally be greater than or equal
820 >     * to the {@link #getParallelism parallelism} level. Setting this
821 >     * value has no effect on current pool size. It controls
822 >     * construction of new threads.
823       *
824 <     * @throws IllegalArgumentException if negative or greater then
824 >     * @throws IllegalArgumentException if negative or greater than
825       * internal implementation limit
826       */
827      public void setMaximumPoolSize(int newMax) {
# Line 817 | Line 832 | public class ForkJoinPool extends Abstra
832  
833  
834      /**
835 <     * Returns true if this pool dynamically maintains its target
836 <     * parallelism level. If false, new threads are added only to
837 <     * avoid possible starvation.
823 <     * This setting is by default true.
835 >     * Returns {@code true} if this pool dynamically maintains its
836 >     * target parallelism level. If false, new threads are added only
837 >     * to avoid possible starvation.  This setting is by default true.
838       *
839 <     * @return true if maintains parallelism
839 >     * @return {@code true} if maintains parallelism
840       */
841      public boolean getMaintainsParallelism() {
842          return maintainsParallelism;
# Line 833 | Line 847 | public class ForkJoinPool extends Abstra
847       * parallelism level. If false, new threads are added only to
848       * avoid possible starvation.
849       *
850 <     * @param enable true to maintains parallelism
850 >     * @param enable {@code true} to maintain parallelism
851       */
852      public void setMaintainsParallelism(boolean enable) {
853          maintainsParallelism = enable;
# Line 844 | Line 858 | public class ForkJoinPool extends Abstra
858       * tasks that are never joined. This mode may be more appropriate
859       * than default locally stack-based mode in applications in which
860       * worker threads only process asynchronous tasks.  This method is
861 <     * designed to be invoked only when pool is quiescent, and
861 >     * designed to be invoked only when the pool is quiescent, and
862       * typically only before any tasks are submitted. The effects of
863       * invocations at other times may be unpredictable.
864       *
865 <     * @param async if true, use locally FIFO scheduling
865 >     * @param async if {@code true}, use locally FIFO scheduling
866       * @return the previous mode
867 +     * @see #getAsyncMode
868       */
869      public boolean setAsyncMode(boolean async) {
870          boolean oldMode = locallyFifo;
# Line 866 | Line 881 | public class ForkJoinPool extends Abstra
881      }
882  
883      /**
884 <     * Returns true if this pool uses local first-in-first-out
884 >     * Returns {@code true} if this pool uses local first-in-first-out
885       * scheduling mode for forked tasks that are never joined.
886       *
887 <     * @return true if this pool uses async mode
887 >     * @return {@code true} if this pool uses async mode
888 >     * @see #setAsyncMode
889       */
890      public boolean getAsyncMode() {
891          return locallyFifo;
# Line 910 | Line 926 | public class ForkJoinPool extends Abstra
926      }
927  
928      /**
929 <     * Returns true if all worker threads are currently idle. An idle
930 <     * worker is one that cannot obtain a task to execute because none
931 <     * are available to steal from other threads, and there are no
932 <     * pending submissions to the pool. This method is conservative;
933 <     * it might not return true immediately upon idleness of all
934 <     * threads, but will eventually become true if threads remain
935 <     * inactive.
929 >     * Returns {@code true} if all worker threads are currently idle.
930 >     * An idle worker is one that cannot obtain a task to execute
931 >     * because none are available to steal from other threads, and
932 >     * there are no pending submissions to the pool. This method is
933 >     * conservative; it might not return {@code true} immediately upon
934 >     * idleness of all threads, but will eventually become true if
935 >     * threads remain inactive.
936       *
937 <     * @return true if all threads are currently idle
937 >     * @return {@code true} if all threads are currently idle
938       */
939      public boolean isQuiescent() {
940          return activeCountOf(runControl) == 0;
# Line 973 | Line 989 | public class ForkJoinPool extends Abstra
989      }
990  
991      /**
992 <     * Returns an estimate of the number tasks submitted to this pool
993 <     * that have not yet begun executing. This method takes time
992 >     * Returns an estimate of the number of tasks submitted to this
993 >     * pool that have not yet begun executing.  This method takes time
994       * proportional to the number of submissions.
995       *
996       * @return the number of queued submissions
# Line 984 | Line 1000 | public class ForkJoinPool extends Abstra
1000      }
1001  
1002      /**
1003 <     * Returns true if there are any tasks submitted to this pool
1004 <     * that have not yet begun executing.
1003 >     * Returns {@code true} if there are any tasks submitted to this
1004 >     * pool that have not yet begun executing.
1005       *
1006       * @return {@code true} if there are any queued submissions
1007       */
# Line 998 | Line 1014 | public class ForkJoinPool extends Abstra
1014       * available.  This method may be useful in extensions to this
1015       * class that re-assign work in systems with multiple pools.
1016       *
1017 <     * @return the next submission, or null if none
1017 >     * @return the next submission, or {@code null} if none
1018       */
1019      protected ForkJoinTask<?> pollSubmission() {
1020          return submissionQueue.poll();
# Line 1008 | Line 1024 | public class ForkJoinPool extends Abstra
1024       * Removes all available unexecuted submitted and forked tasks
1025       * from scheduling queues and adds them to the given collection,
1026       * without altering their execution status. These may include
1027 <     * artificially generated or wrapped tasks. This method is designed
1028 <     * to be invoked only when the pool is known to be
1027 >     * artificially generated or wrapped tasks. This method is
1028 >     * designed to be invoked only when the pool is known to be
1029       * quiescent. Invocations at other times may not remove all
1030       * tasks. A failure encountered while attempting to add elements
1031       * to collection {@code c} may result in elements being in
# Line 1021 | Line 1037 | public class ForkJoinPool extends Abstra
1037       * @param c the collection to transfer elements into
1038       * @return the number of elements transferred
1039       */
1040 <    protected int drainTasksTo(Collection<ForkJoinTask<?>> c) {
1040 >    protected int drainTasksTo(Collection<? super ForkJoinTask<?>> c) {
1041          int n = submissionQueue.drainTo(c);
1042          ForkJoinWorkerThread[] ws = workers;
1043          if (ws != null) {
# Line 1087 | Line 1103 | public class ForkJoinPool extends Abstra
1103      public void shutdown() {
1104          checkPermission();
1105          transitionRunStateTo(SHUTDOWN);
1106 <        if (canTerminateOnShutdown(runControl))
1106 >        if (canTerminateOnShutdown(runControl)) {
1107 >            if (workers == null) { // shutting down before workers created
1108 >                final ReentrantLock lock = this.workerLock;
1109 >                lock.lock();
1110 >                try {
1111 >                    if (workers == null) {
1112 >                        terminate();
1113 >                        transitionRunStateTo(TERMINATED);
1114 >                        termination.signalAll();
1115 >                    }
1116 >                } finally {
1117 >                    lock.unlock();
1118 >                }
1119 >            }
1120              terminateOnShutdown();
1121 +        }
1122      }
1123  
1124      /**
1125 <     * Attempts to stop all actively executing tasks, and cancels all
1126 <     * waiting tasks.  Tasks that are in the process of being
1127 <     * submitted or executed concurrently during the course of this
1128 <     * method may or may not be rejected. Unlike some other executors,
1129 <     * this method cancels rather than collects non-executed tasks
1130 <     * upon termination, so always returns an empty list. However, you
1131 <     * can use method {@code drainTasksTo} before invoking this
1132 <     * method to transfer unexecuted tasks to another collection.
1125 >     * Attempts to cancel and/or stop all tasks, and reject all
1126 >     * subsequently submitted tasks.  Tasks that are in the process of
1127 >     * being submitted or executed concurrently during the course of
1128 >     * this method may or may not be rejected. This method cancels
1129 >     * both existing and unexecuted tasks, in order to permit
1130 >     * termination in the presence of task dependencies. So the method
1131 >     * always returns an empty list (unlike the case for some other
1132 >     * Executors).
1133       *
1134       * @return an empty list
1135       * @throws SecurityException if a security manager exists and
# Line 1124 | Line 1154 | public class ForkJoinPool extends Abstra
1154  
1155      /**
1156       * Returns {@code true} if the process of termination has
1157 <     * commenced but possibly not yet completed.
1157 >     * commenced but not yet completed.  This method may be useful for
1158 >     * debugging. A return of {@code true} reported a sufficient
1159 >     * period after shutdown may indicate that submitted tasks have
1160 >     * ignored or suppressed interruption, causing this executor not
1161 >     * to properly terminate.
1162       *
1163 <     * @return {@code true} if terminating
1163 >     * @return {@code true} if terminating but not yet terminated
1164       */
1165      public boolean isTerminating() {
1166 <        return runStateOf(runControl) >= TERMINATING;
1166 >        return runStateOf(runControl) == TERMINATING;
1167      }
1168  
1169      /**
# Line 1142 | Line 1176 | public class ForkJoinPool extends Abstra
1176      }
1177  
1178      /**
1179 +     * Returns true if pool is not terminating or terminated.
1180 +     * Used internally to suppress execution when terminating.
1181 +     */
1182 +    final boolean isProcessingTasks() {
1183 +        return runStateOf(runControl) < TERMINATING;
1184 +    }
1185 +
1186 +    /**
1187       * Blocks until all tasks have completed execution after a shutdown
1188       * request, or the timeout occurs, or the current thread is
1189       * interrupted, whichever happens first.
# Line 1195 | Line 1237 | public class ForkJoinPool extends Abstra
1237                      transitionRunStateTo(TERMINATED);
1238                      termination.signalAll();
1239                  }
1240 <                else if (!isTerminating()) {
1240 >                else if (isProcessingTasks()) {
1241                      tryShrinkWorkerArray();
1242                      tryResumeSpare(true); // allow replacement
1243                  }
# Line 1436 | Line 1478 | public class ForkJoinPool extends Abstra
1478      final void sync(ForkJoinWorkerThread w) {
1479          updateStealCount(w); // Transfer w's count while it is idle
1480  
1481 <        while (!w.isShutdown() && !isTerminating() && !suspendIfSpare(w)) {
1481 >        while (!w.isShutdown() && isProcessingTasks() && !suspendIfSpare(w)) {
1482              long prev = w.lastEventCount;
1483              WaitQueueNode node = null;
1484              WaitQueueNode h;
# Line 1458 | Line 1500 | public class ForkJoinPool extends Abstra
1500      }
1501  
1502      /**
1503 <     * Returns true if worker waiting on sync can proceed:
1503 >     * Returns {@code true} if worker waiting on sync can proceed:
1504       *  - on signal (thread == null)
1505       *  - on event count advance (winning race to notify vs signaller)
1506       *  - on interrupt
# Line 1466 | Line 1508 | public class ForkJoinPool extends Abstra
1508       * If node was not signalled and event count not advanced on exit,
1509       * then we also help advance event count.
1510       *
1511 <     * @return true if node can be released
1511 >     * @return {@code true} if node can be released
1512       */
1513      final boolean syncIsReleasable(WaitQueueNode node) {
1514          long prev = node.count;
# Line 1485 | Line 1527 | public class ForkJoinPool extends Abstra
1527      }
1528  
1529      /**
1530 <     * Returns true if a new sync event occurred since last call to
1531 <     * sync or this method, if so, updating caller's count.
1530 >     * Returns {@code true} if a new sync event occurred since last
1531 >     * call to sync or this method, if so, updating caller's count.
1532       */
1533      final boolean hasNewSyncEvent(ForkJoinWorkerThread w) {
1534          long lc = w.lastEventCount;
# Line 1536 | Line 1578 | public class ForkJoinPool extends Abstra
1578          while (spareStack == null || !tryResumeSpare(dec)) {
1579              int counts = workerCounts;
1580              if (dec || (dec = casWorkerCounts(counts, --counts))) {
1539                // CAS cheat
1581                  if (!needSpare(counts, maintainParallelism))
1582                      break;
1583                  if (joinMe.status < 0)
# Line 1570 | Line 1611 | public class ForkJoinPool extends Abstra
1611      }
1612  
1613      /**
1614 <     * Returns true if a spare thread appears to be needed.  If
1615 <     * maintaining parallelism, returns true when the deficit in
1614 >     * Returns {@code true} if a spare thread appears to be needed.
1615 >     * If maintaining parallelism, returns true when the deficit in
1616       * running threads is more than the surplus of total threads, and
1617       * there is apparently some work to do.  This self-limiting rule
1618       * means that the more threads that have already been added, the
# Line 1641 | Line 1682 | public class ForkJoinPool extends Abstra
1682              for (k = 0; k < len && ws[k] != null; ++k)
1683                  ;
1684          }
1685 <        if (k < len && !isTerminating() && (w = createWorker(k)) != null) {
1685 >        if (k < len && isProcessingTasks() && (w = createWorker(k)) != null) {
1686              ws[k] = w;
1687              w.start();
1688          }
# Line 1739 | Line 1780 | public class ForkJoinPool extends Abstra
1780  
1781      /**
1782       * Interface for extending managed parallelism for tasks running
1783 <     * in ForkJoinPools. A ManagedBlocker provides two methods.
1784 <     * Method {@code isReleasable} must return true if blocking is not
1785 <     * necessary. Method {@code block} blocks the current thread if
1786 <     * necessary (perhaps internally invoking {@code isReleasable}
1787 <     * before actually blocking.).
1783 >     * in {@link ForkJoinPool}s.
1784 >     *
1785 >     * <p>A {@code ManagedBlocker} provides two methods.
1786 >     * Method {@code isReleasable} must return {@code true} if
1787 >     * blocking is not necessary. Method {@code block} blocks the
1788 >     * current thread if necessary (perhaps internally invoking
1789 >     * {@code isReleasable} before actually blocking).
1790       *
1791       * <p>For example, here is a ManagedBlocker based on a
1792       * ReentrantLock:
# Line 1767 | Line 1810 | public class ForkJoinPool extends Abstra
1810           * Possibly blocks the current thread, for example waiting for
1811           * a lock or condition.
1812           *
1813 <         * @return true if no additional blocking is necessary (i.e.,
1814 <         * if isReleasable would return true)
1813 >         * @return {@code true} if no additional blocking is necessary
1814 >         * (i.e., if isReleasable would return true)
1815           * @throws InterruptedException if interrupted while waiting
1816           * (the method is not required to do so, but is allowed to)
1817           */
1818          boolean block() throws InterruptedException;
1819  
1820          /**
1821 <         * Returns true if blocking is unnecessary.
1821 >         * Returns {@code true} if blocking is unnecessary.
1822           */
1823          boolean isReleasable();
1824      }
1825  
1826      /**
1827       * Blocks in accord with the given blocker.  If the current thread
1828 <     * is a ForkJoinWorkerThread, this method possibly arranges for a
1829 <     * spare thread to be activated if necessary to ensure parallelism
1830 <     * while the current thread is blocked.  If
1831 <     * {@code maintainParallelism} is true and the pool supports
1832 <     * it ({@link #getMaintainsParallelism}), this method attempts to
1833 <     * maintain the pool's nominal parallelism. Otherwise it activates
1834 <     * a thread only if necessary to avoid complete starvation. This
1835 <     * option may be preferable when blockages use timeouts, or are
1836 <     * almost always brief.
1828 >     * is a {@link ForkJoinWorkerThread}, this method possibly
1829 >     * arranges for a spare thread to be activated if necessary to
1830 >     * ensure parallelism while the current thread is blocked.
1831 >     *
1832 >     * <p>If {@code maintainParallelism} is {@code true} and the pool
1833 >     * supports it ({@link #getMaintainsParallelism}), this method
1834 >     * attempts to maintain the pool's nominal parallelism. Otherwise
1835 >     * it activates a thread only if necessary to avoid complete
1836 >     * starvation. This option may be preferable when blockages use
1837 >     * timeouts, or are almost always brief.
1838       *
1839 <     * <p> If the caller is not a ForkJoinTask, this method is behaviorally
1840 <     * equivalent to
1839 >     * <p>If the caller is not a {@link ForkJoinTask}, this method is
1840 >     * behaviorally equivalent to
1841       *  <pre> {@code
1842       * while (!blocker.isReleasable())
1843       *   if (blocker.block())
1844       *     return;
1845       * }</pre>
1846 <     * If the caller is a ForkJoinTask, then the pool may first
1847 <     * be expanded to ensure parallelism, and later adjusted.
1846 >     *
1847 >     * If the caller is a {@code ForkJoinTask}, then the pool may
1848 >     * first be expanded to ensure parallelism, and later adjusted.
1849       *
1850       * @param blocker the blocker
1851 <     * @param maintainParallelism if true and supported by this pool,
1852 <     * attempt to maintain the pool's nominal parallelism; otherwise
1853 <     * activate a thread only if necessary to avoid complete
1854 <     * starvation.
1851 >     * @param maintainParallelism if {@code true} and supported by
1852 >     * this pool, attempt to maintain the pool's nominal parallelism;
1853 >     * otherwise activate a thread only if necessary to avoid
1854 >     * complete starvation.
1855       * @throws InterruptedException if blocker.block did so
1856       */
1857      public static void managedBlock(ManagedBlocker blocker,
# Line 1832 | Line 1877 | public class ForkJoinPool extends Abstra
1877          do {} while (!blocker.isReleasable() && !blocker.block());
1878      }
1879  
1880 <    // AbstractExecutorService overrides
1880 >    // AbstractExecutorService overrides.  These rely on undocumented
1881 >    // fact that ForkJoinTask.adapt returns ForkJoinTasks that also
1882 >    // implement RunnableFuture.
1883  
1884      protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
1885 <        return new AdaptedRunnable<T>(runnable, value);
1885 >        return (RunnableFuture<T>) ForkJoinTask.adapt(runnable, value);
1886      }
1887  
1888      protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
1889 <        return new AdaptedCallable<T>(callable);
1889 >        return (RunnableFuture<T>) ForkJoinTask.adapt(callable);
1890      }
1891  
1892 <
1846 <    // Unsafe mechanics for jsr166y 3rd party package.
1847 <    private static sun.misc.Unsafe getUnsafe() {
1848 <        try {
1849 <            return sun.misc.Unsafe.getUnsafe();
1850 <        } catch (SecurityException se) {
1851 <            try {
1852 <                return java.security.AccessController.doPrivileged
1853 <                    (new java.security.PrivilegedExceptionAction<sun.misc.Unsafe>() {
1854 <                        public sun.misc.Unsafe run() throws Exception {
1855 <                            return getUnsafeByReflection();
1856 <                        }});
1857 <            } catch (java.security.PrivilegedActionException e) {
1858 <                throw new RuntimeException("Could not initialize intrinsics",
1859 <                                           e.getCause());
1860 <            }
1861 <        }
1862 <    }
1863 <
1864 <    private static sun.misc.Unsafe getUnsafeByReflection()
1865 <            throws NoSuchFieldException, IllegalAccessException {
1866 <        java.lang.reflect.Field f =
1867 <            sun.misc.Unsafe.class.getDeclaredField("theUnsafe");
1868 <        f.setAccessible(true);
1869 <        return (sun.misc.Unsafe) f.get(null);
1870 <    }
1871 <
1872 <    private static long fieldOffset(String fieldName, Class<?> klazz) {
1873 <        try {
1874 <            return UNSAFE.objectFieldOffset(klazz.getDeclaredField(fieldName));
1875 <        } catch (NoSuchFieldException e) {
1876 <            // Convert Exception to Error
1877 <            NoSuchFieldError error = new NoSuchFieldError(fieldName);
1878 <            error.initCause(e);
1879 <            throw error;
1880 <        }
1881 <    }
1892 >    // Unsafe mechanics
1893  
1894      private static final sun.misc.Unsafe UNSAFE = getUnsafe();
1895 <    static final long eventCountOffset =
1896 <        fieldOffset("eventCount", ForkJoinPool.class);
1897 <    static final long workerCountsOffset =
1898 <        fieldOffset("workerCounts", ForkJoinPool.class);
1899 <    static final long runControlOffset =
1900 <        fieldOffset("runControl", ForkJoinPool.class);
1901 <    static final long syncStackOffset =
1902 <        fieldOffset("syncStack",ForkJoinPool.class);
1903 <    static final long spareStackOffset =
1904 <        fieldOffset("spareStack", ForkJoinPool.class);
1895 >    private static final long eventCountOffset =
1896 >        objectFieldOffset("eventCount", ForkJoinPool.class);
1897 >    private static final long workerCountsOffset =
1898 >        objectFieldOffset("workerCounts", ForkJoinPool.class);
1899 >    private static final long runControlOffset =
1900 >        objectFieldOffset("runControl", ForkJoinPool.class);
1901 >    private static final long syncStackOffset =
1902 >        objectFieldOffset("syncStack",ForkJoinPool.class);
1903 >    private static final long spareStackOffset =
1904 >        objectFieldOffset("spareStack", ForkJoinPool.class);
1905  
1906      private boolean casEventCount(long cmp, long val) {
1907          return UNSAFE.compareAndSwapLong(this, eventCountOffset, cmp, val);
# Line 1907 | Line 1918 | public class ForkJoinPool extends Abstra
1918      private boolean casBarrierStack(WaitQueueNode cmp, WaitQueueNode val) {
1919          return UNSAFE.compareAndSwapObject(this, syncStackOffset, cmp, val);
1920      }
1921 +
1922 +    private static long objectFieldOffset(String field, Class<?> klazz) {
1923 +        try {
1924 +            return UNSAFE.objectFieldOffset(klazz.getDeclaredField(field));
1925 +        } catch (NoSuchFieldException e) {
1926 +            // Convert Exception to corresponding Error
1927 +            NoSuchFieldError error = new NoSuchFieldError(field);
1928 +            error.initCause(e);
1929 +            throw error;
1930 +        }
1931 +    }
1932 +
1933 +    /**
1934 +     * Returns a sun.misc.Unsafe.  Suitable for use in a 3rd party package.
1935 +     * Replace with a simple call to Unsafe.getUnsafe when integrating
1936 +     * into a jdk.
1937 +     *
1938 +     * @return a sun.misc.Unsafe
1939 +     */
1940 +    private static sun.misc.Unsafe getUnsafe() {
1941 +        try {
1942 +            return sun.misc.Unsafe.getUnsafe();
1943 +        } catch (SecurityException se) {
1944 +            try {
1945 +                return java.security.AccessController.doPrivileged
1946 +                    (new java.security
1947 +                     .PrivilegedExceptionAction<sun.misc.Unsafe>() {
1948 +                        public sun.misc.Unsafe run() throws Exception {
1949 +                            java.lang.reflect.Field f = sun.misc
1950 +                                .Unsafe.class.getDeclaredField("theUnsafe");
1951 +                            f.setAccessible(true);
1952 +                            return (sun.misc.Unsafe) f.get(null);
1953 +                        }});
1954 +            } catch (java.security.PrivilegedActionException e) {
1955 +                throw new RuntimeException("Could not initialize intrinsics",
1956 +                                           e.getCause());
1957 +            }
1958 +        }
1959 +    }
1960   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines