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.30 by dl, Wed Jul 29 12:05:55 2009 UTC vs.
Revision 1.40 by jsr166, Mon Aug 3 00:53:15 2009 UTC

# Line 21 | Line 21 | import java.util.concurrent.atomic.Atomi
21  
22   /**
23   * An {@link ExecutorService} for running {@link ForkJoinTask}s.
24 < * A 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.
24 > * A {@code ForkJoinPool} provides the entry point for submissions
25 > * from non-{@code ForkJoinTask}s, as well as management and
26 > * monitoring operations.  Normally a single {@code ForkJoinPool} is
27 > * used for a large number of submitted tasks. Otherwise, use would
28 > * not usually outweigh the construction and bookkeeping overhead of
29 > * creating a large set of threads.
30   *
31 < * <p>ForkJoinPools differ from other kinds of Executors mainly in
32 < * that they provide <em>work-stealing</em>: all threads in the pool
33 < * attempt to find and execute subtasks created by other active tasks
34 < * (eventually blocking if none exist). This makes them efficient when
35 < * most tasks spawn other subtasks (as do most ForkJoinTasks), as well
36 < * as the mixed execution of some plain Runnable- or Callable- based
37 < * activities along with ForkJoinTasks. When setting {@linkplain
38 < * #setAsyncMode async mode}, a ForkJoinPool may also be appropriate
39 < * for use with fine-grained tasks that are never joined. Otherwise,
40 < * other ExecutorService implementations are typically more
31 > * <p>{@code ForkJoinPool}s differ from other kinds of {@link
32 > * Executor}s mainly in that they provide <em>work-stealing</em>: all
33 > * threads in the pool attempt to find and execute subtasks created by
34 > * other active tasks (eventually blocking if none exist). This makes
35 > * them efficient when most tasks spawn other subtasks (as do most
36 > * {@code ForkJoinTask}s), as well as the mixed execution of some
37 > * plain {@code Runnable}- or {@code Callable}- based activities along
38 > * with {@code ForkJoinTask}s. When setting {@linkplain #setAsyncMode
39 > * async mode}, a {@code ForkJoinPool} may also be appropriate for use
40 > * with fine-grained tasks that are never joined. Otherwise, other
41 > * {@code ExecutorService} implementations are typically more
42   * appropriate choices.
43   *
44 < * <p>A ForkJoinPool may be constructed with a given parallelism level
45 < * (target pool size), which it attempts to maintain by dynamically
46 < * adding, suspending, or resuming threads, even if some tasks are
47 < * waiting to join others. However, no such adjustments are performed
48 < * in the face of blocked IO or other unmanaged synchronization. The
49 < * nested {@link ManagedBlocker} interface enables extension of
50 < * the kinds of synchronization accommodated.  The target parallelism
51 < * level may also be changed dynamically ({@link #setParallelism})
52 < * and thread construction can be limited using methods
53 < * {@link #setMaximumPoolSize} and/or
54 < * {@link #setMaintainsParallelism}.
44 > * <p>A {@code ForkJoinPool} may be constructed with a given
45 > * parallelism level (target pool size), which it attempts to maintain
46 > * by dynamically adding, suspending, or resuming threads, even if
47 > * some tasks are waiting to join others. However, no such adjustments
48 > * are performed in the face of blocked IO or other unmanaged
49 > * synchronization. The nested {@link ManagedBlocker} interface
50 > * enables extension of the kinds of synchronization accommodated.
51 > * The target parallelism level may also be changed dynamically
52 > * ({@link #setParallelism}) and thread construction can be limited
53 > * using methods {@link #setMaximumPoolSize} and/or {@link
54 > * #setMaintainsParallelism}.
55   *
56   * <p>In addition to execution and lifecycle control methods, this
57   * class provides status check methods (for example
# Line 62 | Line 63 | import java.util.concurrent.atomic.Atomi
63   * <p><b>Implementation notes</b>: This implementation restricts the
64   * maximum number of running threads to 32767. Attempts to create
65   * pools with greater than the maximum result in
66 < * IllegalArgumentExceptions.
66 > * {@code IllegalArgumentException}.
67   *
68   * @since 1.7
69   * @author Doug Lea
# Line 81 | Line 82 | public class ForkJoinPool extends Abstra
82      private static final int MAX_THREADS =  0x7FFF;
83  
84      /**
85 <     * Factory for creating new ForkJoinWorkerThreads.  A
86 <     * ForkJoinWorkerThreadFactory must be defined and used for
87 <     * ForkJoinWorkerThread subclasses that extend base functionality
88 <     * or initialize threads with different contexts.
85 >     * Factory for creating new {@link ForkJoinWorkerThread}s.
86 >     * A {@code ForkJoinWorkerThreadFactory} must be defined and used
87 >     * for {@code ForkJoinWorkerThread} subclasses that extend base
88 >     * functionality or initialize threads with different contexts.
89       */
90      public static interface ForkJoinWorkerThreadFactory {
91          /**
# Line 578 | Line 579 | public class ForkJoinPool extends Abstra
579       * @throws NullPointerException if task is null
580       * @throws RejectedExecutionException if pool is shut down
581       */
582 <    public <T> void execute(ForkJoinTask<T> task) {
582 >    public void execute(ForkJoinTask<?> task) {
583          doSubmit(task);
584      }
585  
# Line 589 | Line 590 | public class ForkJoinPool extends Abstra
590          if (task instanceof ForkJoinTask<?>) // avoid re-wrap
591              job = (ForkJoinTask<?>) task;
592          else
593 <            job = new AdaptedRunnable<Void>(task, null);
593 >            job = ForkJoinTask.adapt(task, null);
594          doSubmit(job);
595      }
596  
597      public <T> ForkJoinTask<T> submit(Callable<T> task) {
598 <        ForkJoinTask<T> job = new AdaptedCallable<T>(task);
598 >        ForkJoinTask<T> job = ForkJoinTask.adapt(task);
599          doSubmit(job);
600          return job;
601      }
602  
603      public <T> ForkJoinTask<T> submit(Runnable task, T result) {
604 <        ForkJoinTask<T> job = new AdaptedRunnable<T>(task, result);
604 >        ForkJoinTask<T> job = ForkJoinTask.adapt(task, result);
605          doSubmit(job);
606          return job;
607      }
# Line 610 | Line 611 | public class ForkJoinPool extends Abstra
611          if (task instanceof ForkJoinTask<?>) // avoid re-wrap
612              job = (ForkJoinTask<?>) task;
613          else
614 <            job = new AdaptedRunnable<Void>(task, null);
614 >            job = ForkJoinTask.adapt(task, null);
615          doSubmit(job);
616          return job;
617      }
# Line 629 | Line 630 | public class ForkJoinPool extends Abstra
630          return task;
631      }
632  
632    /**
633     * Adaptor for Runnables. This implements RunnableFuture
634     * to be compliant with AbstractExecutorService constraints.
635     */
636    static final class AdaptedRunnable<T> extends ForkJoinTask<T>
637        implements RunnableFuture<T> {
638        final Runnable runnable;
639        final T resultOnCompletion;
640        T result;
641        AdaptedRunnable(Runnable runnable, T result) {
642            if (runnable == null) throw new NullPointerException();
643            this.runnable = runnable;
644            this.resultOnCompletion = result;
645        }
646        public T getRawResult() { return result; }
647        public void setRawResult(T v) { result = v; }
648        public boolean exec() {
649            runnable.run();
650            result = resultOnCompletion;
651            return true;
652        }
653        public void run() { invoke(); }
654        private static final long serialVersionUID = 5232453952276885070L;
655    }
656
657    /**
658     * Adaptor for Callables
659     */
660    static final class AdaptedCallable<T> extends ForkJoinTask<T>
661        implements RunnableFuture<T> {
662        final Callable<T> callable;
663        T result;
664        AdaptedCallable(Callable<T> callable) {
665            if (callable == null) throw new NullPointerException();
666            this.callable = callable;
667        }
668        public T getRawResult() { return result; }
669        public void setRawResult(T v) { result = v; }
670        public boolean exec() {
671            try {
672                result = callable.call();
673                return true;
674            } catch (Error err) {
675                throw err;
676            } catch (RuntimeException rex) {
677                throw rex;
678            } catch (Exception ex) {
679                throw new RuntimeException(ex);
680            }
681        }
682        public void run() { invoke(); }
683        private static final long serialVersionUID = 2838392045355241008L;
684    }
633  
634      public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) {
635          ArrayList<ForkJoinTask<T>> forkJoinTasks =
636              new ArrayList<ForkJoinTask<T>>(tasks.size());
637          for (Callable<T> task : tasks)
638 <            forkJoinTasks.add(new AdaptedCallable<T>(task));
638 >            forkJoinTasks.add(ForkJoinTask.adapt(task));
639          invoke(new InvokeAll<T>(forkJoinTasks));
640  
641          @SuppressWarnings({"unchecked", "rawtypes"})
# Line 840 | Line 788 | public class ForkJoinPool extends Abstra
788       * Setting this value has no effect on current pool size. It
789       * controls construction of new threads.
790       *
791 <     * @throws IllegalArgumentException if negative or greater then
791 >     * @throws IllegalArgumentException if negative or greater than
792       * internal implementation limit
793       */
794      public void setMaximumPoolSize(int newMax) {
# Line 1008 | Line 956 | public class ForkJoinPool extends Abstra
956      }
957  
958      /**
959 <     * Returns an estimate of the number tasks submitted to this pool
960 <     * that have not yet begun executing. This method takes time
959 >     * Returns an estimate of the number of tasks submitted to this
960 >     * pool that have not yet begun executing.  This method takes time
961       * proportional to the number of submissions.
962       *
963       * @return the number of queued submissions
# Line 1122 | Line 1070 | public class ForkJoinPool extends Abstra
1070      public void shutdown() {
1071          checkPermission();
1072          transitionRunStateTo(SHUTDOWN);
1073 <        if (canTerminateOnShutdown(runControl))
1073 >        if (canTerminateOnShutdown(runControl)) {
1074 >            if (workers == null) { // shutting down before workers created
1075 >                final ReentrantLock lock = this.workerLock;
1076 >                lock.lock();
1077 >                try {
1078 >                    if (workers == null) {
1079 >                        terminate();
1080 >                        transitionRunStateTo(TERMINATED);
1081 >                        termination.signalAll();
1082 >                    }
1083 >                } finally {
1084 >                    lock.unlock();
1085 >                }
1086 >            }
1087              terminateOnShutdown();
1088 +        }
1089      }
1090  
1091      /**
# Line 1774 | Line 1736 | public class ForkJoinPool extends Abstra
1736  
1737      /**
1738       * Interface for extending managed parallelism for tasks running
1739 <     * in ForkJoinPools. A ManagedBlocker provides two methods.
1739 >     * in {@link ForkJoinPool}s.
1740 >     *
1741 >     * <p>A {@code ManagedBlocker} provides two methods.
1742       * Method {@code isReleasable} must return {@code true} if
1743       * blocking is not necessary. Method {@code block} blocks the
1744       * current thread if necessary (perhaps internally invoking
1745 <     * {@code isReleasable} before actually blocking.).
1745 >     * {@code isReleasable} before actually blocking).
1746       *
1747       * <p>For example, here is a ManagedBlocker based on a
1748       * ReentrantLock:
# Line 1817 | Line 1781 | public class ForkJoinPool extends Abstra
1781  
1782      /**
1783       * Blocks in accord with the given blocker.  If the current thread
1784 <     * is a ForkJoinWorkerThread, this method possibly arranges for a
1785 <     * spare thread to be activated if necessary to ensure parallelism
1786 <     * while the current thread is blocked.  If
1787 <     * {@code maintainParallelism} is {@code true} and the pool supports
1788 <     * it ({@link #getMaintainsParallelism}), this method attempts to
1789 <     * maintain the pool's nominal parallelism. Otherwise it activates
1790 <     * a thread only if necessary to avoid complete starvation. This
1791 <     * option may be preferable when blockages use timeouts, or are
1792 <     * almost always brief.
1784 >     * is a {@link ForkJoinWorkerThread}, this method possibly
1785 >     * arranges for a spare thread to be activated if necessary to
1786 >     * ensure parallelism while the current thread is blocked.
1787 >     *
1788 >     * <p>If {@code maintainParallelism} is {@code true} and the pool
1789 >     * supports it ({@link #getMaintainsParallelism}), this method
1790 >     * attempts to maintain the pool's nominal parallelism. Otherwise
1791 >     * it activates a thread only if necessary to avoid complete
1792 >     * starvation. This option may be preferable when blockages use
1793 >     * timeouts, or are almost always brief.
1794       *
1795 <     * <p> If the caller is not a ForkJoinTask, this method is behaviorally
1796 <     * equivalent to
1795 >     * <p>If the caller is not a {@link ForkJoinTask}, this method is
1796 >     * behaviorally equivalent to
1797       *  <pre> {@code
1798       * while (!blocker.isReleasable())
1799       *   if (blocker.block())
1800       *     return;
1801       * }</pre>
1802 <     * If the caller is a ForkJoinTask, then the pool may first
1803 <     * be expanded to ensure parallelism, and later adjusted.
1802 >     *
1803 >     * If the caller is a {@code ForkJoinTask}, then the pool may
1804 >     * first be expanded to ensure parallelism, and later adjusted.
1805       *
1806       * @param blocker the blocker
1807       * @param maintainParallelism if {@code true} and supported by
# Line 1867 | Line 1833 | public class ForkJoinPool extends Abstra
1833          do {} while (!blocker.isReleasable() && !blocker.block());
1834      }
1835  
1836 <    // AbstractExecutorService overrides
1836 >    // AbstractExecutorService overrides.  These rely on undocumented
1837 >    // fact that ForkJoinTask.adapt returns ForkJoinTasks that also
1838 >    // implement RunnableFuture.
1839  
1840      protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
1841 <        return new AdaptedRunnable<T>(runnable, value);
1841 >        return (RunnableFuture<T>) ForkJoinTask.adapt(runnable, value);
1842      }
1843  
1844      protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
1845 <        return new AdaptedCallable<T>(callable);
1845 >        return (RunnableFuture<T>) ForkJoinTask.adapt(callable);
1846      }
1847  
1848      // Unsafe mechanics

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines