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.19 by jsr166, Fri Jul 24 18:57:56 2009 UTC vs.
Revision 1.41 by jsr166, Mon Aug 3 01:11:58 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.*;
12 < import sun.misc.Unsafe;
13 < import java.lang.reflect.*;
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
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.  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
38 < * {@code setAsyncMode}, a ForkJoinPools may also be appropriate for
39 < * use with fine-grained tasks that are never joined. Otherwise, other
40 < * ExecutorService implementations are typically more appropriate
41 < * choices.
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 {@code ManagedBlocker} interface enables extension of
50 < * the kinds of synchronization accommodated.  The target parallelism
51 < * level may also be changed dynamically ({@code setParallelism})
52 < * and thread construction can be limited using methods
53 < * {@code setMaximumPoolSize} and/or
54 < * {@code 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
58 < * {@code getStealCount}) that are intended to aid in developing,
58 > * {@link #getStealCount}) that are intended to aid in developing,
59   * tuning, and monitoring fork/join applications. Also, method
60 < * {@code toString} returns indications of pool state in a
60 > * {@link #toString} returns indications of pool state in a
61   * convenient form for informal monitoring.
62   *
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 74 | 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 304 | Line 312 | public class ForkJoinPool extends Abstra
312      }
313  
314      /**
315 <     * Returns true if argument represents zero active count and
316 <     * nonzero runstate, which is the triggering condition for
315 >     * Returns {@code true} if argument represents zero active count
316 >     * and nonzero runstate, which is the triggering condition for
317       * terminating on shutdown.
318       */
319      private static boolean canTerminateOnShutdown(int c) {
# Line 335 | Line 343 | public class ForkJoinPool extends Abstra
343      // Constructors
344  
345      /**
346 <     * Creates a ForkJoinPool with a pool size equal to the number of
347 <     * processors available on the system, using the default
348 <     * ForkJoinWorkerThreadFactory.
346 >     * Creates a {@code ForkJoinPool} with a pool size equal to the
347 >     * number of processors available on the system, using the
348 >     * {@linkplain #defaultForkJoinWorkerThreadFactory default thread factory}.
349       *
350       * @throws SecurityException if a security manager exists and
351       *         the caller is not permitted to modify threads
# Line 350 | Line 358 | public class ForkJoinPool extends Abstra
358      }
359  
360      /**
361 <     * Creates a ForkJoinPool with the indicated parallelism level
362 <     * threads and using the default ForkJoinWorkerThreadFactory.
361 >     * Creates a {@code ForkJoinPool} with the indicated parallelism level
362 >     * threads and using the
363 >     * {@linkplain #defaultForkJoinWorkerThreadFactory default thread factory}.
364       *
365       * @param parallelism the number of worker threads
366       * @throws IllegalArgumentException if parallelism less than or
# Line 366 | Line 375 | public class ForkJoinPool extends Abstra
375      }
376  
377      /**
378 <     * Creates a ForkJoinPool with parallelism equal to the number of
379 <     * processors available on the system and using the given
380 <     * ForkJoinWorkerThreadFactory.
378 >     * Creates a {@code ForkJoinPool} with parallelism equal to the
379 >     * number of processors available on the system and using the
380 >     * given thread factory.
381       *
382       * @param factory the factory for creating new threads
383       * @throws NullPointerException if factory is null
# Line 382 | Line 391 | public class ForkJoinPool extends Abstra
391      }
392  
393      /**
394 <     * Creates a ForkJoinPool with the given parallelism and factory.
394 >     * Creates a {@code ForkJoinPool} with the given parallelism and
395 >     * thread factory.
396       *
397       * @param parallelism the targeted number of worker threads
398       * @param factory the factory for creating new threads
# Line 416 | Line 426 | public class ForkJoinPool extends Abstra
426       * Creates a new worker thread using factory.
427       *
428       * @param index the index to assign worker
429 <     * @return new worker, or null of factory failed
429 >     * @return new worker, or null if factory failed
430       */
431      private ForkJoinWorkerThread createWorker(int index) {
432          Thread.UncaughtExceptionHandler h = ueh;
# Line 541 | Line 551 | public class ForkJoinPool extends Abstra
551       * Common code for execute, invoke and submit
552       */
553      private <T> void doSubmit(ForkJoinTask<T> task) {
554 +        if (task == null)
555 +            throw new NullPointerException();
556          if (isShutdown())
557              throw new RejectedExecutionException();
558          if (workers == null)
# Line 569 | Line 581 | public class ForkJoinPool extends Abstra
581       * @throws NullPointerException if task is null
582       * @throws RejectedExecutionException if pool is shut down
583       */
584 <    public <T> void execute(ForkJoinTask<T> task) {
584 >    public void execute(ForkJoinTask<?> task) {
585          doSubmit(task);
586      }
587  
588      // AbstractExecutorService methods
589  
590      public void execute(Runnable task) {
591 <        doSubmit(new AdaptedRunnable<Void>(task, null));
591 >        ForkJoinTask<?> job;
592 >        if (task instanceof ForkJoinTask<?>) // avoid re-wrap
593 >            job = (ForkJoinTask<?>) task;
594 >        else
595 >            job = ForkJoinTask.adapt(task, null);
596 >        doSubmit(job);
597      }
598  
599      public <T> ForkJoinTask<T> submit(Callable<T> task) {
600 <        ForkJoinTask<T> job = new AdaptedCallable<T>(task);
600 >        ForkJoinTask<T> job = ForkJoinTask.adapt(task);
601          doSubmit(job);
602          return job;
603      }
604  
605      public <T> ForkJoinTask<T> submit(Runnable task, T result) {
606 <        ForkJoinTask<T> job = new AdaptedRunnable<T>(task, result);
606 >        ForkJoinTask<T> job = ForkJoinTask.adapt(task, result);
607          doSubmit(job);
608          return job;
609      }
610  
611      public ForkJoinTask<?> submit(Runnable task) {
612 <        ForkJoinTask<Void> job = new AdaptedRunnable<Void>(task, null);
612 >        ForkJoinTask<?> job;
613 >        if (task instanceof ForkJoinTask<?>) // avoid re-wrap
614 >            job = (ForkJoinTask<?>) task;
615 >        else
616 >            job = ForkJoinTask.adapt(task, null);
617          doSubmit(job);
618          return job;
619      }
620  
621      /**
622 <     * Adaptor for Runnables. This implements RunnableFuture
623 <     * to be compliant with AbstractExecutorService constraints.
622 >     * Submits a ForkJoinTask for execution.
623 >     *
624 >     * @param task the task to submit
625 >     * @return the task
626 >     * @throws RejectedExecutionException if the task cannot be
627 >     *         scheduled for execution
628 >     * @throws NullPointerException if the task is null
629       */
630 <    static final class AdaptedRunnable<T> extends ForkJoinTask<T>
631 <        implements RunnableFuture<T> {
632 <        final Runnable runnable;
607 <        final T resultOnCompletion;
608 <        T result;
609 <        AdaptedRunnable(Runnable runnable, T result) {
610 <            if (runnable == null) throw new NullPointerException();
611 <            this.runnable = runnable;
612 <            this.resultOnCompletion = result;
613 <        }
614 <        public T getRawResult() { return result; }
615 <        public void setRawResult(T v) { result = v; }
616 <        public boolean exec() {
617 <            runnable.run();
618 <            result = resultOnCompletion;
619 <            return true;
620 <        }
621 <        public void run() { invoke(); }
622 <        private static final long serialVersionUID = 5232453952276885070L;
630 >    public <T> ForkJoinTask<T> submit(ForkJoinTask<T> task) {
631 >        doSubmit(task);
632 >        return task;
633      }
634  
625    /**
626     * Adaptor for Callables
627     */
628    static final class AdaptedCallable<T> extends ForkJoinTask<T>
629        implements RunnableFuture<T> {
630        final Callable<T> callable;
631        T result;
632        AdaptedCallable(Callable<T> callable) {
633            if (callable == null) throw new NullPointerException();
634            this.callable = callable;
635        }
636        public T getRawResult() { return result; }
637        public void setRawResult(T v) { result = v; }
638        public boolean exec() {
639            try {
640                result = callable.call();
641                return true;
642            } catch (Error err) {
643                throw err;
644            } catch (RuntimeException rex) {
645                throw rex;
646            } catch (Exception ex) {
647                throw new RuntimeException(ex);
648            }
649        }
650        public void run() { invoke(); }
651        private static final long serialVersionUID = 2838392045355241008L;
652    }
635  
636      public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) {
637 <        ArrayList<ForkJoinTask<T>> ts =
637 >        ArrayList<ForkJoinTask<T>> forkJoinTasks =
638              new ArrayList<ForkJoinTask<T>>(tasks.size());
639 <        for (Callable<T> c : tasks)
640 <            ts.add(new AdaptedCallable<T>(c));
641 <        invoke(new InvokeAll<T>(ts));
642 <        return (List<Future<T>>) (List) ts;
639 >        for (Callable<T> task : tasks)
640 >            forkJoinTasks.add(ForkJoinTask.adapt(task));
641 >        invoke(new InvokeAll<T>(forkJoinTasks));
642 >
643 >        @SuppressWarnings({"unchecked", "rawtypes"})
644 >        List<Future<T>> futures = (List<Future<T>>) (List) forkJoinTasks;
645 >        return futures;
646      }
647  
648      static final class InvokeAll<T> extends RecursiveAction {
# Line 685 | Line 670 | public class ForkJoinPool extends Abstra
670       * Returns the handler for internal worker threads that terminate
671       * due to unrecoverable errors encountered while executing tasks.
672       *
673 <     * @return the handler, or null if none
673 >     * @return the handler, or {@code null} if none
674       */
675      public Thread.UncaughtExceptionHandler getUncaughtExceptionHandler() {
676          Thread.UncaughtExceptionHandler h;
# Line 706 | Line 691 | public class ForkJoinPool extends Abstra
691       * as handler.
692       *
693       * @param h the new handler
694 <     * @return the old handler, or null if none
694 >     * @return the old handler, or {@code null} if none
695       * @throws SecurityException if a security manager exists and
696       *         the caller is not permitted to modify threads
697       *         because it does not hold {@link
# Line 780 | Line 765 | public class ForkJoinPool extends Abstra
765      /**
766       * Returns the number of worker threads that have started but not
767       * yet terminated.  This result returned by this method may differ
768 <     * from {@code getParallelism} when threads are created to
768 >     * from {@link #getParallelism} when threads are created to
769       * maintain parallelism when others are cooperatively blocked.
770       *
771       * @return the number of worker threads
# Line 805 | Line 790 | public class ForkJoinPool extends Abstra
790       * Setting this value has no effect on current pool size. It
791       * controls construction of new threads.
792       *
793 <     * @throws IllegalArgumentException if negative or greater then
793 >     * @throws IllegalArgumentException if negative or greater than
794       * internal implementation limit
795       */
796      public void setMaximumPoolSize(int newMax) {
# Line 816 | Line 801 | public class ForkJoinPool extends Abstra
801  
802  
803      /**
804 <     * Returns true if this pool dynamically maintains its target
805 <     * parallelism level. If false, new threads are added only to
806 <     * avoid possible starvation.
822 <     * This setting is by default true.
804 >     * Returns {@code true} if this pool dynamically maintains its
805 >     * target parallelism level. If false, new threads are added only
806 >     * to avoid possible starvation.  This setting is by default true.
807       *
808 <     * @return true if maintains parallelism
808 >     * @return {@code true} if maintains parallelism
809       */
810      public boolean getMaintainsParallelism() {
811          return maintainsParallelism;
# Line 832 | Line 816 | public class ForkJoinPool extends Abstra
816       * parallelism level. If false, new threads are added only to
817       * avoid possible starvation.
818       *
819 <     * @param enable true to maintains parallelism
819 >     * @param enable {@code true} to maintain parallelism
820       */
821      public void setMaintainsParallelism(boolean enable) {
822          maintainsParallelism = enable;
# Line 843 | Line 827 | public class ForkJoinPool extends Abstra
827       * tasks that are never joined. This mode may be more appropriate
828       * than default locally stack-based mode in applications in which
829       * worker threads only process asynchronous tasks.  This method is
830 <     * designed to be invoked only when pool is quiescent, and
830 >     * designed to be invoked only when the pool is quiescent, and
831       * typically only before any tasks are submitted. The effects of
832       * invocations at other times may be unpredictable.
833       *
834 <     * @param async if true, use locally FIFO scheduling
834 >     * @param async if {@code true}, use locally FIFO scheduling
835       * @return the previous mode
836 +     * @see #getAsyncMode
837       */
838      public boolean setAsyncMode(boolean async) {
839          boolean oldMode = locallyFifo;
# Line 865 | Line 850 | public class ForkJoinPool extends Abstra
850      }
851  
852      /**
853 <     * Returns true if this pool uses local first-in-first-out
853 >     * Returns {@code true} if this pool uses local first-in-first-out
854       * scheduling mode for forked tasks that are never joined.
855       *
856 <     * @return true if this pool uses async mode
856 >     * @return {@code true} if this pool uses async mode
857 >     * @see #setAsyncMode
858       */
859      public boolean getAsyncMode() {
860          return locallyFifo;
# Line 909 | Line 895 | public class ForkJoinPool extends Abstra
895      }
896  
897      /**
898 <     * Returns true if all worker threads are currently idle. An idle
899 <     * worker is one that cannot obtain a task to execute because none
900 <     * are available to steal from other threads, and there are no
901 <     * pending submissions to the pool. This method is conservative;
902 <     * it might not return true immediately upon idleness of all
903 <     * threads, but will eventually become true if threads remain
904 <     * inactive.
898 >     * Returns {@code true} if all worker threads are currently idle.
899 >     * An idle worker is one that cannot obtain a task to execute
900 >     * because none are available to steal from other threads, and
901 >     * there are no pending submissions to the pool. This method is
902 >     * conservative; it might not return {@code true} immediately upon
903 >     * idleness of all threads, but will eventually become true if
904 >     * threads remain inactive.
905       *
906 <     * @return true if all threads are currently idle
906 >     * @return {@code true} if all threads are currently idle
907       */
908      public boolean isQuiescent() {
909          return activeCountOf(runControl) == 0;
# Line 972 | Line 958 | public class ForkJoinPool extends Abstra
958      }
959  
960      /**
961 <     * Returns an estimate of the number tasks submitted to this pool
962 <     * that have not yet begun executing. This method takes time
961 >     * Returns an estimate of the number of tasks submitted to this
962 >     * pool that have not yet begun executing.  This method takes time
963       * proportional to the number of submissions.
964       *
965       * @return the number of queued submissions
# Line 983 | Line 969 | public class ForkJoinPool extends Abstra
969      }
970  
971      /**
972 <     * Returns true if there are any tasks submitted to this pool
973 <     * that have not yet begun executing.
972 >     * Returns {@code true} if there are any tasks submitted to this
973 >     * pool that have not yet begun executing.
974       *
975       * @return {@code true} if there are any queued submissions
976       */
# Line 997 | Line 983 | public class ForkJoinPool extends Abstra
983       * available.  This method may be useful in extensions to this
984       * class that re-assign work in systems with multiple pools.
985       *
986 <     * @return the next submission, or null if none
986 >     * @return the next submission, or {@code null} if none
987       */
988      protected ForkJoinTask<?> pollSubmission() {
989          return submissionQueue.poll();
# Line 1007 | Line 993 | public class ForkJoinPool extends Abstra
993       * Removes all available unexecuted submitted and forked tasks
994       * from scheduling queues and adds them to the given collection,
995       * without altering their execution status. These may include
996 <     * artificially generated or wrapped tasks. This method is designed
997 <     * to be invoked only when the pool is known to be
996 >     * artificially generated or wrapped tasks. This method is
997 >     * designed to be invoked only when the pool is known to be
998       * quiescent. Invocations at other times may not remove all
999       * tasks. A failure encountered while attempting to add elements
1000       * to collection {@code c} may result in elements being in
# Line 1020 | Line 1006 | public class ForkJoinPool extends Abstra
1006       * @param c the collection to transfer elements into
1007       * @return the number of elements transferred
1008       */
1009 <    protected int drainTasksTo(Collection<ForkJoinTask<?>> c) {
1009 >    protected int drainTasksTo(Collection<? super ForkJoinTask<?>> c) {
1010          int n = submissionQueue.drainTo(c);
1011          ForkJoinWorkerThread[] ws = workers;
1012          if (ws != null) {
# Line 1086 | Line 1072 | public class ForkJoinPool extends Abstra
1072      public void shutdown() {
1073          checkPermission();
1074          transitionRunStateTo(SHUTDOWN);
1075 <        if (canTerminateOnShutdown(runControl))
1075 >        if (canTerminateOnShutdown(runControl)) {
1076 >            if (workers == null) { // shutting down before workers created
1077 >                final ReentrantLock lock = this.workerLock;
1078 >                lock.lock();
1079 >                try {
1080 >                    if (workers == null) {
1081 >                        terminate();
1082 >                        transitionRunStateTo(TERMINATED);
1083 >                        termination.signalAll();
1084 >                    }
1085 >                } finally {
1086 >                    lock.unlock();
1087 >                }
1088 >            }
1089              terminateOnShutdown();
1090 +        }
1091      }
1092  
1093      /**
# Line 1097 | Line 1097 | public class ForkJoinPool extends Abstra
1097       * method may or may not be rejected. Unlike some other executors,
1098       * this method cancels rather than collects non-executed tasks
1099       * upon termination, so always returns an empty list. However, you
1100 <     * can use method {@code drainTasksTo} before invoking this
1100 >     * can use method {@link #drainTasksTo} before invoking this
1101       * method to transfer unexecuted tasks to another collection.
1102       *
1103       * @return an empty list
# Line 1457 | Line 1457 | public class ForkJoinPool extends Abstra
1457      }
1458  
1459      /**
1460 <     * Returns true if worker waiting on sync can proceed:
1460 >     * Returns {@code true} if worker waiting on sync can proceed:
1461       *  - on signal (thread == null)
1462       *  - on event count advance (winning race to notify vs signaller)
1463       *  - on interrupt
# Line 1465 | Line 1465 | public class ForkJoinPool extends Abstra
1465       * If node was not signalled and event count not advanced on exit,
1466       * then we also help advance event count.
1467       *
1468 <     * @return true if node can be released
1468 >     * @return {@code true} if node can be released
1469       */
1470      final boolean syncIsReleasable(WaitQueueNode node) {
1471          long prev = node.count;
# Line 1484 | Line 1484 | public class ForkJoinPool extends Abstra
1484      }
1485  
1486      /**
1487 <     * Returns true if a new sync event occurred since last call to
1488 <     * sync or this method, if so, updating caller's count.
1487 >     * Returns {@code true} if a new sync event occurred since last
1488 >     * call to sync or this method, if so, updating caller's count.
1489       */
1490      final boolean hasNewSyncEvent(ForkJoinWorkerThread w) {
1491          long lc = w.lastEventCount;
# Line 1569 | Line 1569 | public class ForkJoinPool extends Abstra
1569      }
1570  
1571      /**
1572 <     * Returns true if a spare thread appears to be needed.  If
1573 <     * maintaining parallelism, returns true when the deficit in
1572 >     * Returns {@code true} if a spare thread appears to be needed.
1573 >     * If maintaining parallelism, returns true when the deficit in
1574       * running threads is more than the surplus of total threads, and
1575       * there is apparently some work to do.  This self-limiting rule
1576       * means that the more threads that have already been added, the
# Line 1738 | Line 1738 | public class ForkJoinPool extends Abstra
1738  
1739      /**
1740       * Interface for extending managed parallelism for tasks running
1741 <     * in ForkJoinPools. A ManagedBlocker provides two methods.
1742 <     * Method {@code isReleasable} must return true if blocking is not
1743 <     * necessary. Method {@code block} blocks the current thread if
1744 <     * necessary (perhaps internally invoking {@code isReleasable}
1745 <     * before actually blocking.).
1741 >     * in {@link ForkJoinPool}s.
1742 >     *
1743 >     * <p>A {@code ManagedBlocker} provides two methods.
1744 >     * Method {@code isReleasable} must return {@code true} if
1745 >     * blocking is not necessary. Method {@code block} blocks the
1746 >     * current thread if necessary (perhaps internally invoking
1747 >     * {@code isReleasable} before actually blocking).
1748       *
1749       * <p>For example, here is a ManagedBlocker based on a
1750       * ReentrantLock:
# Line 1766 | Line 1768 | public class ForkJoinPool extends Abstra
1768           * Possibly blocks the current thread, for example waiting for
1769           * a lock or condition.
1770           *
1771 <         * @return true if no additional blocking is necessary (i.e.,
1772 <         * if isReleasable would return true)
1771 >         * @return {@code true} if no additional blocking is necessary
1772 >         * (i.e., if isReleasable would return true)
1773           * @throws InterruptedException if interrupted while waiting
1774           * (the method is not required to do so, but is allowed to)
1775           */
1776          boolean block() throws InterruptedException;
1777  
1778          /**
1779 <         * Returns true if blocking is unnecessary.
1779 >         * Returns {@code true} if blocking is unnecessary.
1780           */
1781          boolean isReleasable();
1782      }
1783  
1784      /**
1785       * Blocks in accord with the given blocker.  If the current thread
1786 <     * is a ForkJoinWorkerThread, this method possibly arranges for a
1787 <     * spare thread to be activated if necessary to ensure parallelism
1788 <     * while the current thread is blocked.  If
1789 <     * {@code maintainParallelism} is true and the pool supports
1790 <     * it ({@link #getMaintainsParallelism}), this method attempts to
1791 <     * maintain the pool's nominal parallelism. Otherwise it activates
1792 <     * a thread only if necessary to avoid complete starvation. This
1793 <     * option may be preferable when blockages use timeouts, or are
1794 <     * almost always brief.
1786 >     * is a {@link ForkJoinWorkerThread}, this method possibly
1787 >     * arranges for a spare thread to be activated if necessary to
1788 >     * ensure parallelism while the current thread is blocked.
1789 >     *
1790 >     * <p>If {@code maintainParallelism} is {@code true} and the pool
1791 >     * supports it ({@link #getMaintainsParallelism}), this method
1792 >     * attempts to maintain the pool's nominal parallelism. Otherwise
1793 >     * it activates a thread only if necessary to avoid complete
1794 >     * starvation. This option may be preferable when blockages use
1795 >     * timeouts, or are almost always brief.
1796       *
1797 <     * <p> If the caller is not a ForkJoinTask, this method is behaviorally
1798 <     * equivalent to
1797 >     * <p>If the caller is not a {@link ForkJoinTask}, this method is
1798 >     * behaviorally equivalent to
1799       *  <pre> {@code
1800       * while (!blocker.isReleasable())
1801       *   if (blocker.block())
1802       *     return;
1803       * }</pre>
1804 <     * If the caller is a ForkJoinTask, then the pool may first
1805 <     * be expanded to ensure parallelism, and later adjusted.
1804 >     *
1805 >     * If the caller is a {@code ForkJoinTask}, then the pool may
1806 >     * first be expanded to ensure parallelism, and later adjusted.
1807       *
1808       * @param blocker the blocker
1809 <     * @param maintainParallelism if true and supported by this pool,
1810 <     * attempt to maintain the pool's nominal parallelism; otherwise
1811 <     * activate a thread only if necessary to avoid complete
1812 <     * starvation.
1809 >     * @param maintainParallelism if {@code true} and supported by
1810 >     * this pool, attempt to maintain the pool's nominal parallelism;
1811 >     * otherwise activate a thread only if necessary to avoid
1812 >     * complete starvation.
1813       * @throws InterruptedException if blocker.block did so
1814       */
1815      public static void managedBlock(ManagedBlocker blocker,
# Line 1831 | Line 1835 | public class ForkJoinPool extends Abstra
1835          do {} while (!blocker.isReleasable() && !blocker.block());
1836      }
1837  
1838 <    // AbstractExecutorService overrides
1838 >    // AbstractExecutorService overrides.  These rely on undocumented
1839 >    // fact that ForkJoinTask.adapt returns ForkJoinTasks that also
1840 >    // implement RunnableFuture.
1841  
1842      protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
1843 <        return new AdaptedRunnable<T>(runnable, value);
1843 >        return (RunnableFuture<T>) ForkJoinTask.adapt(runnable, value);
1844      }
1845  
1846      protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
1847 <        return new AdaptedCallable<T>(callable);
1847 >        return (RunnableFuture<T>) ForkJoinTask.adapt(callable);
1848      }
1849  
1850 +    // Unsafe mechanics
1851  
1852 <    // Temporary Unsafe mechanics for preliminary release
1853 <    private static Unsafe getUnsafe() throws Throwable {
1854 <        try {
1855 <            return Unsafe.getUnsafe();
1856 <        } catch (SecurityException se) {
1857 <            try {
1858 <                return java.security.AccessController.doPrivileged
1859 <                    (new java.security.PrivilegedExceptionAction<Unsafe>() {
1860 <                        public Unsafe run() throws Exception {
1861 <                            return getUnsafePrivileged();
1862 <                        }});
1856 <            } catch (java.security.PrivilegedActionException e) {
1857 <                throw e.getCause();
1858 <            }
1859 <        }
1860 <    }
1861 <
1862 <    private static Unsafe getUnsafePrivileged()
1863 <            throws NoSuchFieldException, IllegalAccessException {
1864 <        Field f = Unsafe.class.getDeclaredField("theUnsafe");
1865 <        f.setAccessible(true);
1866 <        return (Unsafe) f.get(null);
1867 <    }
1868 <
1869 <    private static long fieldOffset(String fieldName)
1870 <            throws NoSuchFieldException {
1871 <        return UNSAFE.objectFieldOffset
1872 <            (ForkJoinPool.class.getDeclaredField(fieldName));
1873 <    }
1874 <
1875 <    static final Unsafe UNSAFE;
1876 <    static final long eventCountOffset;
1877 <    static final long workerCountsOffset;
1878 <    static final long runControlOffset;
1879 <    static final long syncStackOffset;
1880 <    static final long spareStackOffset;
1881 <
1882 <    static {
1883 <        try {
1884 <            UNSAFE = getUnsafe();
1885 <            eventCountOffset = fieldOffset("eventCount");
1886 <            workerCountsOffset = fieldOffset("workerCounts");
1887 <            runControlOffset = fieldOffset("runControl");
1888 <            syncStackOffset = fieldOffset("syncStack");
1889 <            spareStackOffset = fieldOffset("spareStack");
1890 <        } catch (Throwable e) {
1891 <            throw new RuntimeException("Could not initialize intrinsics", e);
1892 <        }
1893 <    }
1852 >    private static final sun.misc.Unsafe UNSAFE = getUnsafe();
1853 >    private static final long eventCountOffset =
1854 >        objectFieldOffset("eventCount", ForkJoinPool.class);
1855 >    private static final long workerCountsOffset =
1856 >        objectFieldOffset("workerCounts", ForkJoinPool.class);
1857 >    private static final long runControlOffset =
1858 >        objectFieldOffset("runControl", ForkJoinPool.class);
1859 >    private static final long syncStackOffset =
1860 >        objectFieldOffset("syncStack",ForkJoinPool.class);
1861 >    private static final long spareStackOffset =
1862 >        objectFieldOffset("spareStack", ForkJoinPool.class);
1863  
1864      private boolean casEventCount(long cmp, long val) {
1865          return UNSAFE.compareAndSwapLong(this, eventCountOffset, cmp, val);
# Line 1907 | Line 1876 | public class ForkJoinPool extends Abstra
1876      private boolean casBarrierStack(WaitQueueNode cmp, WaitQueueNode val) {
1877          return UNSAFE.compareAndSwapObject(this, syncStackOffset, cmp, val);
1878      }
1879 +
1880 +    private static long objectFieldOffset(String field, Class<?> klazz) {
1881 +        try {
1882 +            return UNSAFE.objectFieldOffset(klazz.getDeclaredField(field));
1883 +        } catch (NoSuchFieldException e) {
1884 +            // Convert Exception to corresponding Error
1885 +            NoSuchFieldError error = new NoSuchFieldError(field);
1886 +            error.initCause(e);
1887 +            throw error;
1888 +        }
1889 +    }
1890 +
1891 +    /**
1892 +     * Returns a sun.misc.Unsafe.  Suitable for use in a 3rd party package.
1893 +     * Replace with a simple call to Unsafe.getUnsafe when integrating
1894 +     * into a jdk.
1895 +     *
1896 +     * @return a sun.misc.Unsafe
1897 +     */
1898 +    private static sun.misc.Unsafe getUnsafe() {
1899 +        try {
1900 +            return sun.misc.Unsafe.getUnsafe();
1901 +        } catch (SecurityException se) {
1902 +            try {
1903 +                return java.security.AccessController.doPrivileged
1904 +                    (new java.security
1905 +                     .PrivilegedExceptionAction<sun.misc.Unsafe>() {
1906 +                        public sun.misc.Unsafe run() throws Exception {
1907 +                            java.lang.reflect.Field f = sun.misc
1908 +                                .Unsafe.class.getDeclaredField("theUnsafe");
1909 +                            f.setAccessible(true);
1910 +                            return (sun.misc.Unsafe) f.get(null);
1911 +                        }});
1912 +            } catch (java.security.PrivilegedActionException e) {
1913 +                throw new RuntimeException("Could not initialize intrinsics",
1914 +                                           e.getCause());
1915 +            }
1916 +        }
1917 +    }
1918   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines