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.3 by dl, Wed Jan 7 19:12:36 2009 UTC vs.
Revision 1.13 by jsr166, Wed Jul 22 01:36:51 2009 UTC

# Line 27 | Line 27 | import java.lang.reflect.*;
27   * (eventually blocking if none exist). This makes them efficient when
28   * most tasks spawn other subtasks (as do most ForkJoinTasks), as well
29   * as the mixed execution of some plain Runnable- or Callable- based
30 < * activities along with ForkJoinTasks. Otherwise, other
30 > * activities along with ForkJoinTasks. When setting
31 > * {@code setAsyncMode}, a ForkJoinPools may also be appropriate for
32 > * use with fine-grained tasks that are never joined. Otherwise, other
33   * ExecutorService implementations are typically more appropriate
34   * choices.
35   *
# Line 36 | Line 38 | import java.lang.reflect.*;
38   * adding, suspending, or resuming threads, even if some tasks are
39   * waiting to join others. However, no such adjustments are performed
40   * in the face of blocked IO or other unmanaged synchronization. The
41 < * nested <code>ManagedBlocker</code> interface enables extension of
41 > * nested {@code ManagedBlocker} interface enables extension of
42   * the kinds of synchronization accommodated.  The target parallelism
43 < * level may also be changed dynamically (<code>setParallelism</code>)
44 < * and dynamically thread construction can be limited using methods
45 < * <code>setMaximumPoolSize</code> and/or
46 < * <code>setMaintainsParallelism</code>.
43 > * level may also be changed dynamically ({@code setParallelism})
44 > * and thread construction can be limited using methods
45 > * {@code setMaximumPoolSize} and/or
46 > * {@code setMaintainsParallelism}.
47   *
48   * <p>In addition to execution and lifecycle control methods, this
49   * class provides status check methods (for example
50 < * <code>getStealCount</code>) that are intended to aid in developing,
50 > * {@code getStealCount}) that are intended to aid in developing,
51   * tuning, and monitoring fork/join applications. Also, method
52 < * <code>toString</code> returns indications of pool state in a
52 > * {@code toString} returns indications of pool state in a
53   * convenient form for informal monitoring.
54   *
55   * <p><b>Implementation notes</b>: This implementation restricts the
56   * maximum number of running threads to 32767. Attempts to create
57   * pools with greater than the maximum result in
58   * IllegalArgumentExceptions.
59 + *
60 + * @since 1.7
61 + * @author Doug Lea
62   */
63   public class ForkJoinPool extends AbstractExecutorService {
64  
# Line 79 | Line 84 | public class ForkJoinPool extends Abstra
84           * Returns a new worker thread operating in the given pool.
85           *
86           * @param pool the pool this thread works in
87 <         * @throws NullPointerException if pool is null;
87 >         * @throws NullPointerException if pool is null
88           */
89          public ForkJoinWorkerThread newThread(ForkJoinPool pool);
90      }
# Line 131 | Line 136 | public class ForkJoinPool extends Abstra
136          new AtomicInteger();
137  
138      /**
139 <     * Array holding all worker threads in the pool. Array size must
140 <     * be a power of two.  Updates and replacements are protected by
141 <     * workerLock, but it is always kept in a consistent enough state
142 <     * to be randomly accessed without locking by workers performing
143 <     * work-stealing.
139 >     * Array holding all worker threads in the pool. Initialized upon
140 >     * first use. Array size must be a power of two.  Updates and
141 >     * replacements are protected by workerLock, but it is always kept
142 >     * in a consistent enough state to be randomly accessed without
143 >     * locking by workers performing work-stealing.
144       */
145      volatile ForkJoinWorkerThread[] workers;
146  
# Line 151 | Line 156 | public class ForkJoinPool extends Abstra
156  
157      /**
158       * The uncaught exception handler used when any worker
159 <     * abrupty terminates
159 >     * abruptly terminates
160       */
161      private Thread.UncaughtExceptionHandler ueh;
162  
# Line 181 | Line 186 | public class ForkJoinPool extends Abstra
186      /**
187       * Head of Treiber stack for barrier sync. See below for explanation
188       */
189 <    private volatile WaitQueueNode barrierStack;
189 >    private volatile WaitQueueNode syncStack;
190  
191      /**
192       * The count for event barrier
# Line 204 | Line 209 | public class ForkJoinPool extends Abstra
209      private volatile int parallelism;
210  
211      /**
212 +     * True if use local fifo, not default lifo, for local polling
213 +     */
214 +    private volatile boolean locallyFifo;
215 +
216 +    /**
217       * Holds number of total (i.e., created and not yet terminated)
218       * and running (i.e., not blocked on joins or other managed sync)
219       * threads, packed into one int to ensure consistent snapshot when
# Line 219 | Line 229 | public class ForkJoinPool extends Abstra
229      private static int workerCountsFor(int t, int r) { return (t << 16) + r; }
230  
231      /**
232 <     * Add delta (which may be negative) to running count.  This must
232 >     * Adds delta (which may be negative) to running count.  This must
233       * be called before (with negative arg) and after (with positive)
234 <     * any managed synchronization (i.e., mainly, joins)
234 >     * any managed synchronization (i.e., mainly, joins).
235       * @param delta the number to add
236       */
237      final void updateRunningCount(int delta) {
# Line 230 | Line 240 | public class ForkJoinPool extends Abstra
240      }
241  
242      /**
243 <     * Add delta (which may be negative) to both total and running
243 >     * Adds delta (which may be negative) to both total and running
244       * count.  This must be called upon creation and termination of
245       * worker threads.
246       * @param delta the number to add
# Line 264 | Line 274 | public class ForkJoinPool extends Abstra
274      private static int runControlFor(int r, int a)   { return (r << 16) + a; }
275  
276      /**
277 <     * Increment active count. Called by workers before/during
278 <     * executing tasks.
277 >     * Try incrementing active count; fail on contention. Called by
278 >     * workers before/during executing tasks.
279 >     * @return true on success
280       */
281 <    final void incrementActiveCount() {
282 <        int c;
283 <        do;while (!casRunControl(c = runControl, c+1));
281 >    final boolean tryIncrementActiveCount() {
282 >        int c = runControl;
283 >        return casRunControl(c, c+1);
284      }
285  
286      /**
287 <     * Decrement active count; possibly trigger termination.
287 >     * Tries decrementing active count; fails on contention.
288 >     * Possibly triggers termination on success.
289       * Called by workers when they can't find tasks.
290 +     * @return true on success
291       */
292 <    final void decrementActiveCount() {
293 <        int c, nextc;
294 <        do;while (!casRunControl(c = runControl, nextc = c-1));
292 >    final boolean tryDecrementActiveCount() {
293 >        int c = runControl;
294 >        int nextc = c - 1;
295 >        if (!casRunControl(c, nextc))
296 >            return false;
297          if (canTerminateOnShutdown(nextc))
298              terminateOnShutdown();
299 +        return true;
300      }
301  
302      /**
303 <     * Return true if argument represents zero active count and
303 >     * Returns true if argument represents zero active count and
304       * nonzero runstate, which is the triggering condition for
305       * terminating on shutdown.
306       */
# Line 320 | Line 336 | public class ForkJoinPool extends Abstra
336       * @throws SecurityException if a security manager exists and
337       *         the caller is not permitted to modify threads
338       *         because it does not hold {@link
339 <     *         java.lang.RuntimePermission}<code>("modifyThread")</code>,
339 >     *         java.lang.RuntimePermission}{@code ("modifyThread")},
340       */
341      public ForkJoinPool() {
342          this(Runtime.getRuntime().availableProcessors(),
# Line 328 | Line 344 | public class ForkJoinPool extends Abstra
344      }
345  
346      /**
347 <     * Creates a ForkJoinPool with the indicated parellelism level
347 >     * Creates a ForkJoinPool with the indicated parallelism level
348       * threads, and using the default ForkJoinWorkerThreadFactory,
349       * @param parallelism the number of worker threads
350       * @throws IllegalArgumentException if parallelism less than or
# Line 336 | Line 352 | public class ForkJoinPool extends Abstra
352       * @throws SecurityException if a security manager exists and
353       *         the caller is not permitted to modify threads
354       *         because it does not hold {@link
355 <     *         java.lang.RuntimePermission}<code>("modifyThread")</code>,
355 >     *         java.lang.RuntimePermission}{@code ("modifyThread")},
356       */
357      public ForkJoinPool(int parallelism) {
358          this(parallelism, defaultForkJoinWorkerThreadFactory);
# Line 351 | Line 367 | public class ForkJoinPool extends Abstra
367       * @throws SecurityException if a security manager exists and
368       *         the caller is not permitted to modify threads
369       *         because it does not hold {@link
370 <     *         java.lang.RuntimePermission}<code>("modifyThread")</code>,
370 >     *         java.lang.RuntimePermission}{@code ("modifyThread")},
371       */
372      public ForkJoinPool(ForkJoinWorkerThreadFactory factory) {
373          this(Runtime.getRuntime().availableProcessors(), factory);
# Line 363 | Line 379 | public class ForkJoinPool extends Abstra
379       * @param parallelism the targeted number of worker threads
380       * @param factory the factory for creating new threads
381       * @throws IllegalArgumentException if parallelism less than or
382 <     * equal to zero, or greater than implementation limit.
382 >     * equal to zero, or greater than implementation limit
383       * @throws NullPointerException if factory is null
384       * @throws SecurityException if a security manager exists and
385       *         the caller is not permitted to modify threads
386       *         because it does not hold {@link
387 <     *         java.lang.RuntimePermission}<code>("modifyThread")</code>,
387 >     *         java.lang.RuntimePermission}{@code ("modifyThread")},
388       */
389      public ForkJoinPool(int parallelism, ForkJoinWorkerThreadFactory factory) {
390          if (parallelism <= 0 || parallelism > MAX_THREADS)
# Line 385 | Line 401 | public class ForkJoinPool extends Abstra
401          this.termination = workerLock.newCondition();
402          this.stealCount = new AtomicLong();
403          this.submissionQueue = new LinkedTransferQueue<ForkJoinTask<?>>();
404 <        createAndStartInitialWorkers(parallelism);
404 >        // worker array and workers are lazily constructed
405      }
406  
407      /**
# Line 399 | Line 415 | public class ForkJoinPool extends Abstra
415          if (w != null) {
416              w.poolIndex = index;
417              w.setDaemon(true);
418 +            w.setAsyncMode(locallyFifo);
419              w.setName("ForkJoinPool-" + poolNumber + "-worker-" + index);
420              if (h != null)
421                  w.setUncaughtExceptionHandler(h);
# Line 407 | Line 424 | public class ForkJoinPool extends Abstra
424      }
425  
426      /**
427 <     * Return a good size for worker array given pool size.
427 >     * Returns a good size for worker array given pool size.
428       * Currently requires size to be a power of two.
429       */
430      private static int arraySizeFor(int ps) {
# Line 415 | Line 432 | public class ForkJoinPool extends Abstra
432      }
433  
434      /**
435 <     * Create or resize array if necessary to hold newLength
435 >     * Creates or resizes array if necessary to hold newLength.
436 >     * Call only under exclusion or lock.
437       * @return the array
438       */
439      private ForkJoinWorkerThread[] ensureWorkerArrayCapacity(int newLength) {
# Line 433 | Line 451 | public class ForkJoinPool extends Abstra
451       */
452      private void tryShrinkWorkerArray() {
453          ForkJoinWorkerThread[] ws = workers;
454 <        int len = ws.length;
455 <        int last = len - 1;
456 <        while (last >= 0 && ws[last] == null)
457 <            --last;
458 <        int newLength = arraySizeFor(last+1);
459 <        if (newLength < len)
460 <            workers = Arrays.copyOf(ws, newLength);
454 >        if (ws != null) {
455 >            int len = ws.length;
456 >            int last = len - 1;
457 >            while (last >= 0 && ws[last] == null)
458 >                --last;
459 >            int newLength = arraySizeFor(last+1);
460 >            if (newLength < len)
461 >                workers = Arrays.copyOf(ws, newLength);
462 >        }
463      }
464  
465      /**
466 <     * Initial worker array and worker creation and startup. (This
447 <     * must be done under lock to avoid interference by some of the
448 <     * newly started threads while creating others.)
466 >     * Initialize workers if necessary
467       */
468 <    private void createAndStartInitialWorkers(int ps) {
469 <        final ReentrantLock lock = this.workerLock;
470 <        lock.lock();
471 <        try {
472 <            ForkJoinWorkerThread[] ws = ensureWorkerArrayCapacity(ps);
473 <            for (int i = 0; i < ps; ++i) {
474 <                ForkJoinWorkerThread w = createWorker(i);
475 <                if (w != null) {
476 <                    ws[i] = w;
477 <                    w.start();
478 <                    updateWorkerCount(1);
468 >    final void ensureWorkerInitialization() {
469 >        ForkJoinWorkerThread[] ws = workers;
470 >        if (ws == null) {
471 >            final ReentrantLock lock = this.workerLock;
472 >            lock.lock();
473 >            try {
474 >                ws = workers;
475 >                if (ws == null) {
476 >                    int ps = parallelism;
477 >                    ws = ensureWorkerArrayCapacity(ps);
478 >                    for (int i = 0; i < ps; ++i) {
479 >                        ForkJoinWorkerThread w = createWorker(i);
480 >                        if (w != null) {
481 >                            ws[i] = w;
482 >                            w.start();
483 >                            updateWorkerCount(1);
484 >                        }
485 >                    }
486                  }
487 +            } finally {
488 +                lock.unlock();
489              }
463        } finally {
464            lock.unlock();
490          }
491      }
492  
# Line 507 | Line 532 | public class ForkJoinPool extends Abstra
532      private <T> void doSubmit(ForkJoinTask<T> task) {
533          if (isShutdown())
534              throw new RejectedExecutionException();
535 +        if (workers == null)
536 +            ensureWorkerInitialization();
537          submissionQueue.offer(task);
538 <        signalIdleWorkers(true);
538 >        signalIdleWorkers();
539      }
540  
541      /**
# Line 665 | Line 692 | public class ForkJoinPool extends Abstra
692       * @throws SecurityException if a security manager exists and
693       *         the caller is not permitted to modify threads
694       *         because it does not hold {@link
695 <     *         java.lang.RuntimePermission}<code>("modifyThread")</code>,
695 >     *         java.lang.RuntimePermission}{@code ("modifyThread")},
696       */
697      public Thread.UncaughtExceptionHandler
698          setUncaughtExceptionHandler(Thread.UncaughtExceptionHandler h) {
# Line 677 | Line 704 | public class ForkJoinPool extends Abstra
704              old = ueh;
705              ueh = h;
706              ForkJoinWorkerThread[] ws = workers;
707 <            for (int i = 0; i < ws.length; ++i) {
708 <                ForkJoinWorkerThread w = ws[i];
709 <                if (w != null)
710 <                    w.setUncaughtExceptionHandler(h);
707 >            if (ws != null) {
708 >                for (int i = 0; i < ws.length; ++i) {
709 >                    ForkJoinWorkerThread w = ws[i];
710 >                    if (w != null)
711 >                        w.setUncaughtExceptionHandler(h);
712 >                }
713              }
714          } finally {
715              lock.unlock();
# Line 690 | Line 719 | public class ForkJoinPool extends Abstra
719  
720  
721      /**
722 <     * Sets the target paralleism level of this pool.
722 >     * Sets the target parallelism level of this pool.
723       * @param parallelism the target parallelism
724       * @throws IllegalArgumentException if parallelism less than or
725 <     * equal to zero or greater than maximum size bounds.
725 >     * equal to zero or greater than maximum size bounds
726       * @throws SecurityException if a security manager exists and
727       *         the caller is not permitted to modify threads
728       *         because it does not hold {@link
729 <     *         java.lang.RuntimePermission}<code>("modifyThread")</code>,
729 >     *         java.lang.RuntimePermission}{@code ("modifyThread")},
730       */
731      public void setParallelism(int parallelism) {
732          checkPermission();
# Line 717 | Line 746 | public class ForkJoinPool extends Abstra
746          } finally {
747              lock.unlock();
748          }
749 <        signalIdleWorkers(false);
749 >        signalIdleWorkers();
750      }
751  
752      /**
# Line 732 | Line 761 | public class ForkJoinPool extends Abstra
761      /**
762       * Returns the number of worker threads that have started but not
763       * yet terminated.  This result returned by this method may differ
764 <     * from <code>getParallelism</code> when threads are created to
764 >     * from {@code getParallelism} when threads are created to
765       * maintain parallelism when others are cooperatively blocked.
766       *
767       * @return the number of worker threads
# Line 756 | Line 785 | public class ForkJoinPool extends Abstra
785       * Setting this value has no effect on current pool size. It
786       * controls construction of new threads.
787       * @throws IllegalArgumentException if negative or greater then
788 <     * internal implementation limit.
788 >     * internal implementation limit
789       */
790      public void setMaximumPoolSize(int newMax) {
791          if (newMax < 0 || newMax > MAX_THREADS)
# Line 787 | Line 816 | public class ForkJoinPool extends Abstra
816      }
817  
818      /**
819 +     * Establishes local first-in-first-out scheduling mode for forked
820 +     * tasks that are never joined. This mode may be more appropriate
821 +     * than default locally stack-based mode in applications in which
822 +     * worker threads only process asynchronous tasks.  This method is
823 +     * designed to be invoked only when pool is quiescent, and
824 +     * typically only before any tasks are submitted. The effects of
825 +     * invocations at other times may be unpredictable.
826 +     *
827 +     * @param async if true, use locally FIFO scheduling
828 +     * @return the previous mode
829 +     */
830 +    public boolean setAsyncMode(boolean async) {
831 +        boolean oldMode = locallyFifo;
832 +        locallyFifo = async;
833 +        ForkJoinWorkerThread[] ws = workers;
834 +        if (ws != null) {
835 +            for (int i = 0; i < ws.length; ++i) {
836 +                ForkJoinWorkerThread t = ws[i];
837 +                if (t != null)
838 +                    t.setAsyncMode(async);
839 +            }
840 +        }
841 +        return oldMode;
842 +    }
843 +
844 +    /**
845 +     * Returns true if this pool uses local first-in-first-out
846 +     * scheduling mode for forked tasks that are never joined.
847 +     *
848 +     * @return true if this pool uses async mode
849 +     */
850 +    public boolean getAsyncMode() {
851 +        return locallyFifo;
852 +    }
853 +
854 +    /**
855       * Returns an estimate of the number of worker threads that are
856       * not blocked waiting to join tasks or for other managed
857       * synchronization.
# Line 801 | Line 866 | public class ForkJoinPool extends Abstra
866       * Returns an estimate of the number of threads that are currently
867       * stealing or executing tasks. This method may overestimate the
868       * number of active threads.
869 <     * @return the number of active threads.
869 >     * @return the number of active threads
870       */
871      public int getActiveThreadCount() {
872          return activeCountOf(runControl);
# Line 811 | Line 876 | public class ForkJoinPool extends Abstra
876       * Returns an estimate of the number of threads that are currently
877       * idle waiting for tasks. This method may underestimate the
878       * number of idle threads.
879 <     * @return the number of idle threads.
879 >     * @return the number of idle threads
880       */
881      final int getIdleThreadCount() {
882          int c = runningCountOf(workerCounts) - activeCountOf(runControl);
# Line 840 | Line 905 | public class ForkJoinPool extends Abstra
905       * tuning fork/join programs: In general, steal counts should be
906       * high enough to keep threads busy, but low enough to avoid
907       * overhead and contention across threads.
908 <     * @return the number of steals.
908 >     * @return the number of steals
909       */
910      public long getStealCount() {
911          return stealCount.get();
# Line 863 | Line 928 | public class ForkJoinPool extends Abstra
928       * an approximation, obtained by iterating across all threads in
929       * the pool. This method may be useful for tuning task
930       * granularities.
931 <     * @return the number of queued tasks.
931 >     * @return the number of queued tasks
932       */
933      public long getQueuedTaskCount() {
934          long count = 0;
935          ForkJoinWorkerThread[] ws = workers;
936 <        for (int i = 0; i < ws.length; ++i) {
937 <            ForkJoinWorkerThread t = ws[i];
938 <            if (t != null)
939 <                count += t.getQueueSize();
936 >        if (ws != null) {
937 >            for (int i = 0; i < ws.length; ++i) {
938 >                ForkJoinWorkerThread t = ws[i];
939 >                if (t != null)
940 >                    count += t.getQueueSize();
941 >            }
942          }
943          return count;
944      }
# Line 880 | Line 947 | public class ForkJoinPool extends Abstra
947       * Returns an estimate of the number tasks submitted to this pool
948       * that have not yet begun executing. This method takes time
949       * proportional to the number of submissions.
950 <     * @return the number of queued submissions.
950 >     * @return the number of queued submissions
951       */
952      public int getQueuedSubmissionCount() {
953          return submissionQueue.size();
# Line 889 | Line 956 | public class ForkJoinPool extends Abstra
956      /**
957       * Returns true if there are any tasks submitted to this pool
958       * that have not yet begun executing.
959 <     * @return <code>true</code> if there are any queued submissions.
959 >     * @return {@code true} if there are any queued submissions
960       */
961      public boolean hasQueuedSubmissions() {
962          return !submissionQueue.isEmpty();
# Line 906 | Line 973 | public class ForkJoinPool extends Abstra
973      }
974  
975      /**
976 +     * Removes all available unexecuted submitted and forked tasks
977 +     * from scheduling queues and adds them to the given collection,
978 +     * without altering their execution status. These may include
979 +     * artificially generated or wrapped tasks. This method is designed
980 +     * to be invoked only when the pool is known to be
981 +     * quiescent. Invocations at other times may not remove all
982 +     * tasks. A failure encountered while attempting to add elements
983 +     * to collection {@code c} may result in elements being in
984 +     * neither, either or both collections when the associated
985 +     * exception is thrown.  The behavior of this operation is
986 +     * undefined if the specified collection is modified while the
987 +     * operation is in progress.
988 +     * @param c the collection to transfer elements into
989 +     * @return the number of elements transferred
990 +     */
991 +    protected int drainTasksTo(Collection<ForkJoinTask<?>> c) {
992 +        int n = submissionQueue.drainTo(c);
993 +        ForkJoinWorkerThread[] ws = workers;
994 +        if (ws != null) {
995 +            for (int i = 0; i < ws.length; ++i) {
996 +                ForkJoinWorkerThread w = ws[i];
997 +                if (w != null)
998 +                    n += w.drainTasksTo(c);
999 +            }
1000 +        }
1001 +        return n;
1002 +    }
1003 +
1004 +    /**
1005       * Returns a string identifying this pool, as well as its state,
1006       * including indications of run state, parallelism level, and
1007       * worker and task counts.
# Line 952 | Line 1048 | public class ForkJoinPool extends Abstra
1048       * @throws SecurityException if a security manager exists and
1049       *         the caller is not permitted to modify threads
1050       *         because it does not hold {@link
1051 <     *         java.lang.RuntimePermission}<code>("modifyThread")</code>,
1051 >     *         java.lang.RuntimePermission}{@code ("modifyThread")},
1052       */
1053      public void shutdown() {
1054          checkPermission();
# Line 966 | Line 1062 | public class ForkJoinPool extends Abstra
1062       * waiting tasks.  Tasks that are in the process of being
1063       * submitted or executed concurrently during the course of this
1064       * method may or may not be rejected. Unlike some other executors,
1065 <     * this method cancels rather than collects non-executed tasks,
1066 <     * so always returns an empty list.
1065 >     * this method cancels rather than collects non-executed tasks
1066 >     * upon termination, so always returns an empty list. However, you
1067 >     * can use method {@code drainTasksTo} before invoking this
1068 >     * method to transfer unexecuted tasks to another collection.
1069       * @return an empty list
1070       * @throws SecurityException if a security manager exists and
1071       *         the caller is not permitted to modify threads
1072       *         because it does not hold {@link
1073 <     *         java.lang.RuntimePermission}<code>("modifyThread")</code>,
1073 >     *         java.lang.RuntimePermission}{@code ("modifyThread")},
1074       */
1075      public List<Runnable> shutdownNow() {
1076          checkPermission();
# Line 981 | Line 1079 | public class ForkJoinPool extends Abstra
1079      }
1080  
1081      /**
1082 <     * Returns <code>true</code> if all tasks have completed following shut down.
1082 >     * Returns {@code true} if all tasks have completed following shut down.
1083       *
1084 <     * @return <code>true</code> if all tasks have completed following shut down
1084 >     * @return {@code true} if all tasks have completed following shut down
1085       */
1086      public boolean isTerminated() {
1087          return runStateOf(runControl) == TERMINATED;
1088      }
1089  
1090      /**
1091 <     * Returns <code>true</code> if the process of termination has
1091 >     * Returns {@code true} if the process of termination has
1092       * commenced but possibly not yet completed.
1093       *
1094 <     * @return <code>true</code> if terminating
1094 >     * @return {@code true} if terminating
1095       */
1096      public boolean isTerminating() {
1097          return runStateOf(runControl) >= TERMINATING;
1098      }
1099  
1100      /**
1101 <     * Returns <code>true</code> if this pool has been shut down.
1101 >     * Returns {@code true} if this pool has been shut down.
1102       *
1103 <     * @return <code>true</code> if this pool has been shut down
1103 >     * @return {@code true} if this pool has been shut down
1104       */
1105      public boolean isShutdown() {
1106          return runStateOf(runControl) >= SHUTDOWN;
# Line 1015 | Line 1113 | public class ForkJoinPool extends Abstra
1113       *
1114       * @param timeout the maximum time to wait
1115       * @param unit the time unit of the timeout argument
1116 <     * @return <code>true</code> if this executor terminated and
1117 <     *         <code>false</code> if the timeout elapsed before termination
1116 >     * @return {@code true} if this executor terminated and
1117 >     *         {@code false} if the timeout elapsed before termination
1118       * @throws InterruptedException if interrupted while waiting
1119       */
1120      public boolean awaitTermination(long timeout, TimeUnit unit)
# Line 1052 | Line 1150 | public class ForkJoinPool extends Abstra
1150          lock.lock();
1151          try {
1152              ForkJoinWorkerThread[] ws = workers;
1153 <            int idx = w.poolIndex;
1154 <            if (idx >= 0 && idx < ws.length && ws[idx] == w)
1155 <                ws[idx] = null;
1156 <            if (totalCountOf(workerCounts) == 0) {
1157 <                terminate(); // no-op if already terminating
1158 <                transitionRunStateTo(TERMINATED);
1159 <                termination.signalAll();
1160 <            }
1161 <            else if (!isTerminating()) {
1162 <                tryShrinkWorkerArray();
1163 <                tryResumeSpare(true); // allow replacement
1153 >            if (ws != null) {
1154 >                int idx = w.poolIndex;
1155 >                if (idx >= 0 && idx < ws.length && ws[idx] == w)
1156 >                    ws[idx] = null;
1157 >                if (totalCountOf(workerCounts) == 0) {
1158 >                    terminate(); // no-op if already terminating
1159 >                    transitionRunStateTo(TERMINATED);
1160 >                    termination.signalAll();
1161 >                }
1162 >                else if (!isTerminating()) {
1163 >                    tryShrinkWorkerArray();
1164 >                    tryResumeSpare(true); // allow replacement
1165 >                }
1166              }
1167          } finally {
1168              lock.unlock();
1169          }
1170 <        signalIdleWorkers(false);
1170 >        signalIdleWorkers();
1171      }
1172  
1173      /**
# Line 1077 | Line 1177 | public class ForkJoinPool extends Abstra
1177          if (transitionRunStateTo(TERMINATING)) {
1178              stopAllWorkers();
1179              resumeAllSpares();
1180 <            signalIdleWorkers(true);
1180 >            signalIdleWorkers();
1181              cancelQueuedSubmissions();
1182              cancelQueuedWorkerTasks();
1183              interruptUnterminatedWorkers();
1184 <            signalIdleWorkers(true); // resignal after interrupt
1184 >            signalIdleWorkers(); // resignal after interrupt
1185          }
1186      }
1187  
1188      /**
1189 <     * Possibly terminate when on shutdown state
1189 >     * Possibly terminates when on shutdown state.
1190       */
1191      private void terminateOnShutdown() {
1192          if (!hasQueuedSubmissions() && canTerminateOnShutdown(runControl))
# Line 1094 | Line 1194 | public class ForkJoinPool extends Abstra
1194      }
1195  
1196      /**
1197 <     * Clear out and cancel submissions
1197 >     * Clears out and cancels submissions.
1198       */
1199      private void cancelQueuedSubmissions() {
1200          ForkJoinTask<?> task;
# Line 1103 | Line 1203 | public class ForkJoinPool extends Abstra
1203      }
1204  
1205      /**
1206 <     * Clean out worker queues.
1206 >     * Cleans out worker queues.
1207       */
1208      private void cancelQueuedWorkerTasks() {
1209          final ReentrantLock lock = this.workerLock;
1210          lock.lock();
1211          try {
1212              ForkJoinWorkerThread[] ws = workers;
1213 <            for (int i = 0; i < ws.length; ++i) {
1214 <                ForkJoinWorkerThread t = ws[i];
1215 <                if (t != null)
1216 <                    t.cancelTasks();
1213 >            if (ws != null) {
1214 >                for (int i = 0; i < ws.length; ++i) {
1215 >                    ForkJoinWorkerThread t = ws[i];
1216 >                    if (t != null)
1217 >                        t.cancelTasks();
1218 >                }
1219              }
1220          } finally {
1221              lock.unlock();
# Line 1121 | Line 1223 | public class ForkJoinPool extends Abstra
1223      }
1224  
1225      /**
1226 <     * Set each worker's status to terminating. Requires lock to avoid
1227 <     * conflicts with add/remove
1226 >     * Sets each worker's status to terminating. Requires lock to avoid
1227 >     * conflicts with add/remove.
1228       */
1229      private void stopAllWorkers() {
1230          final ReentrantLock lock = this.workerLock;
1231          lock.lock();
1232          try {
1233              ForkJoinWorkerThread[] ws = workers;
1234 <            for (int i = 0; i < ws.length; ++i) {
1235 <                ForkJoinWorkerThread t = ws[i];
1236 <                if (t != null)
1237 <                    t.shutdownNow();
1234 >            if (ws != null) {
1235 >                for (int i = 0; i < ws.length; ++i) {
1236 >                    ForkJoinWorkerThread t = ws[i];
1237 >                    if (t != null)
1238 >                        t.shutdownNow();
1239 >                }
1240              }
1241          } finally {
1242              lock.unlock();
# Line 1140 | Line 1244 | public class ForkJoinPool extends Abstra
1244      }
1245  
1246      /**
1247 <     * Interrupt all unterminated workers.  This is not required for
1247 >     * Interrupts all unterminated workers.  This is not required for
1248       * sake of internal control, but may help unstick user code during
1249       * shutdown.
1250       */
# Line 1149 | Line 1253 | public class ForkJoinPool extends Abstra
1253          lock.lock();
1254          try {
1255              ForkJoinWorkerThread[] ws = workers;
1256 <            for (int i = 0; i < ws.length; ++i) {
1257 <                ForkJoinWorkerThread t = ws[i];
1258 <                if (t != null && !t.isTerminated()) {
1259 <                    try {
1260 <                        t.interrupt();
1261 <                    } catch (SecurityException ignore) {
1256 >            if (ws != null) {
1257 >                for (int i = 0; i < ws.length; ++i) {
1258 >                    ForkJoinWorkerThread t = ws[i];
1259 >                    if (t != null && !t.isTerminated()) {
1260 >                        try {
1261 >                            t.interrupt();
1262 >                        } catch (SecurityException ignore) {
1263 >                        }
1264                      }
1265                  }
1266              }
# Line 1165 | Line 1271 | public class ForkJoinPool extends Abstra
1271  
1272  
1273      /*
1274 <     * Nodes for event barrier to manage idle threads.
1274 >     * Nodes for event barrier to manage idle threads.  Queue nodes
1275 >     * are basic Treiber stack nodes, also used for spare stack.
1276       *
1277       * The event barrier has an event count and a wait queue (actually
1278       * a Treiber stack).  Workers are enabled to look for work when
1279 <     * the eventCount is incremented. If they fail to find some,
1280 <     * they may wait for next count. Synchronization events occur only
1281 <     * in enough contexts to maintain overall liveness:
1279 >     * the eventCount is incremented. If they fail to find work, they
1280 >     * may wait for next count. Upon release, threads help others wake
1281 >     * up.
1282 >     *
1283 >     * Synchronization events occur only in enough contexts to
1284 >     * maintain overall liveness:
1285       *
1286       *   - Submission of a new task to the pool
1287 <     *   - Creation or termination of a worker
1287 >     *   - Resizes or other changes to the workers array
1288       *   - pool termination
1289       *   - A worker pushing a task on an empty queue
1290       *
1291 <     * The last case (pushing a task) occurs often enough, and is
1292 <     * heavy enough compared to simple stack pushes to require some
1293 <     * special handling: Method signalNonEmptyWorkerQueue returns
1294 <     * without advancing count if the queue appears to be empty.  This
1295 <     * would ordinarily result in races causing some queued waiters
1296 <     * not to be woken up. To avoid this, a worker in sync
1297 <     * rescans for tasks after being enqueued if it was the first to
1298 <     * enqueue, and aborts the wait if finding one, also helping to
1299 <     * signal others. This works well because the worker has nothing
1300 <     * better to do anyway, and so might as well help alleviate the
1301 <     * overhead and contention on the threads actually doing work.
1302 <     *
1303 <     * Queue nodes are basic Treiber stack nodes, also used for spare
1304 <     * stack.
1291 >     * The case of pushing a task occurs often enough, and is heavy
1292 >     * enough compared to simple stack pushes, to require special
1293 >     * handling: Method signalWork returns without advancing count if
1294 >     * the queue appears to be empty.  This would ordinarily result in
1295 >     * races causing some queued waiters not to be woken up. To avoid
1296 >     * this, the first worker enqueued in method sync (see
1297 >     * syncIsReleasable) rescans for tasks after being enqueued, and
1298 >     * helps signal if any are found. This works well because the
1299 >     * worker has nothing better to do, and so might as well help
1300 >     * alleviate the overhead and contention on the threads actually
1301 >     * doing work.  Also, since event counts increments on task
1302 >     * availability exist to maintain liveness (rather than to force
1303 >     * refreshes etc), it is OK for callers to exit early if
1304 >     * contending with another signaller.
1305       */
1306      static final class WaitQueueNode {
1307          WaitQueueNode next; // only written before enqueued
1308          volatile ForkJoinWorkerThread thread; // nulled to cancel wait
1309          final long count; // unused for spare stack
1310 <        WaitQueueNode(ForkJoinWorkerThread w, long c) {
1310 >
1311 >        WaitQueueNode(long c, ForkJoinWorkerThread w) {
1312              count = c;
1313              thread = w;
1314          }
1315 <        final boolean signal() {
1315 >
1316 >        /**
1317 >         * Wakes up waiter, returning false if known to already
1318 >         */
1319 >        boolean signal() {
1320              ForkJoinWorkerThread t = thread;
1321 +            if (t == null)
1322 +                return false;
1323              thread = null;
1324 <            if (t != null) {
1325 <                LockSupport.unpark(t);
1326 <                return true;
1324 >            LockSupport.unpark(t);
1325 >            return true;
1326 >        }
1327 >
1328 >        /**
1329 >         * Awaits release on sync.
1330 >         */
1331 >        void awaitSyncRelease(ForkJoinPool p) {
1332 >            while (thread != null && !p.syncIsReleasable(this))
1333 >                LockSupport.park(this);
1334 >        }
1335 >
1336 >        /**
1337 >         * Awaits resumption as spare.
1338 >         */
1339 >        void awaitSpareRelease() {
1340 >            while (thread != null) {
1341 >                if (!Thread.interrupted())
1342 >                    LockSupport.park(this);
1343              }
1211            return false;
1344          }
1345      }
1346  
1347      /**
1348 <     * Release at least one thread waiting for event count to advance,
1349 <     * if one exists. If initial attempt fails, release all threads.
1350 <     * @param all if false, at first try to only release one thread
1351 <     * @return current event
1348 >     * Ensures that no thread is waiting for count to advance from the
1349 >     * current value of eventCount read on entry to this method, by
1350 >     * releasing waiting threads if necessary.
1351 >     * @return the count
1352       */
1353 <    private long releaseIdleWorkers(boolean all) {
1354 <        long c;
1355 <        for (;;) {
1356 <            WaitQueueNode q = barrierStack;
1357 <            c = eventCount;
1226 <            long qc;
1227 <            if (q == null || (qc = q.count) >= c)
1228 <                break;
1229 <            if (!all) {
1230 <                if (casBarrierStack(q, q.next) && q.signal())
1231 <                    break;
1232 <                all = true;
1233 <            }
1234 <            else if (casBarrierStack(q, null)) {
1353 >    final long ensureSync() {
1354 >        long c = eventCount;
1355 >        WaitQueueNode q;
1356 >        while ((q = syncStack) != null && q.count < c) {
1357 >            if (casBarrierStack(q, null)) {
1358                  do {
1359 <                 q.signal();
1359 >                    q.signal();
1360                  } while ((q = q.next) != null);
1361                  break;
1362              }
# Line 1242 | Line 1365 | public class ForkJoinPool extends Abstra
1365      }
1366  
1367      /**
1368 <     * Returns current barrier event count
1246 <     * @return current barrier event count
1368 >     * Increments event count and releases waiting threads.
1369       */
1370 <    final long getEventCount() {
1249 <        long ec = eventCount;
1250 <        releaseIdleWorkers(true); // release to ensure accurate result
1251 <        return ec;
1252 <    }
1253 <
1254 <    /**
1255 <     * Increment event count and release at least one waiting thread,
1256 <     * if one exists (released threads will in turn wake up others).
1257 <     * @param all if true, try to wake up all
1258 <     */
1259 <    final void signalIdleWorkers(boolean all) {
1370 >    private void signalIdleWorkers() {
1371          long c;
1372          do;while (!casEventCount(c = eventCount, c+1));
1373 <        releaseIdleWorkers(all);
1373 >        ensureSync();
1374      }
1375  
1376      /**
1377 <     * Wake up threads waiting to steal a task. Because method
1378 <     * sync rechecks availability, it is OK to only proceed if
1379 <     * queue appears to be non-empty.
1377 >     * Signals threads waiting to poll a task. Because method sync
1378 >     * rechecks availability, it is OK to only proceed if queue
1379 >     * appears to be non-empty, and OK to skip under contention to
1380 >     * increment count (since some other thread succeeded).
1381       */
1382 <    final void signalNonEmptyWorkerQueue() {
1271 <        // If CAS fails another signaller must have succeeded
1382 >    final void signalWork() {
1383          long c;
1384 <        if (barrierStack != null && casEventCount(c = eventCount, c+1))
1385 <            releaseIdleWorkers(false);
1384 >        WaitQueueNode q;
1385 >        if (syncStack != null &&
1386 >            casEventCount(c = eventCount, c+1) &&
1387 >            (((q = syncStack) != null && q.count <= c) &&
1388 >             (!casBarrierStack(q, q.next) || !q.signal())))
1389 >            ensureSync();
1390      }
1391  
1392      /**
1393 <     * Waits until event count advances from count, or some thread is
1394 <     * waiting on a previous count, or there is stealable work
1395 <     * available. Help wake up others on release.
1393 >     * Waits until event count advances from last value held by
1394 >     * caller, or if excess threads, caller is resumed as spare, or
1395 >     * caller or pool is terminating. Updates caller's event on exit.
1396       * @param w the calling worker thread
1282     * @param prev previous value returned by sync (or 0)
1283     * @return current event count
1397       */
1398 <    final long sync(ForkJoinWorkerThread w, long prev) {
1399 <        updateStealCount(w);
1398 >    final void sync(ForkJoinWorkerThread w) {
1399 >        updateStealCount(w); // Transfer w's count while it is idle
1400  
1401 <        while (!w.isShutdown() && !isTerminating() &&
1402 <               (parallelism >= runningCountOf(workerCounts) ||
1290 <                !suspendIfSpare(w))) { // prefer suspend to waiting here
1401 >        while (!w.isShutdown() && !isTerminating() && !suspendIfSpare(w)) {
1402 >            long prev = w.lastEventCount;
1403              WaitQueueNode node = null;
1404 <            boolean queued = false;
1405 <            for (;;) {
1406 <                if (!queued) {
1407 <                    if (eventCount != prev)
1408 <                        break;
1409 <                    WaitQueueNode h = barrierStack;
1410 <                    if (h != null && h.count != prev)
1299 <                        break; // release below and maybe retry
1300 <                    if (node == null)
1301 <                        node = new WaitQueueNode(w, prev);
1302 <                    queued = casBarrierStack(node.next = h, node);
1303 <                }
1304 <                else if (Thread.interrupted() ||
1305 <                         node.thread == null ||
1306 <                         (node.next == null && w.prescan()) ||
1307 <                         eventCount != prev) {
1308 <                    node.thread = null;
1309 <                    if (eventCount == prev) // help trigger
1310 <                        casEventCount(prev, prev+1);
1404 >            WaitQueueNode h;
1405 >            while (eventCount == prev &&
1406 >                   ((h = syncStack) == null || h.count == prev)) {
1407 >                if (node == null)
1408 >                    node = new WaitQueueNode(prev, w);
1409 >                if (casBarrierStack(node.next = h, node)) {
1410 >                    node.awaitSyncRelease(this);
1411                      break;
1412                  }
1313                else
1314                    LockSupport.park(this);
1413              }
1414 +            long ec = ensureSync();
1415 +            if (ec != prev) {
1416 +                w.lastEventCount = ec;
1417 +                break;
1418 +            }
1419 +        }
1420 +    }
1421 +
1422 +    /**
1423 +     * Returns true if worker waiting on sync can proceed:
1424 +     *  - on signal (thread == null)
1425 +     *  - on event count advance (winning race to notify vs signaller)
1426 +     *  - on Interrupt
1427 +     *  - if the first queued node, we find work available
1428 +     * If node was not signalled and event count not advanced on exit,
1429 +     * then we also help advance event count.
1430 +     * @return true if node can be released
1431 +     */
1432 +    final boolean syncIsReleasable(WaitQueueNode node) {
1433 +        long prev = node.count;
1434 +        if (!Thread.interrupted() && node.thread != null &&
1435 +            (node.next != null ||
1436 +             !ForkJoinWorkerThread.hasQueuedTasks(workers)) &&
1437 +            eventCount == prev)
1438 +            return false;
1439 +        if (node.thread != null) {
1440 +            node.thread = null;
1441              long ec = eventCount;
1442 <            if (releaseIdleWorkers(false) != prev)
1443 <                return ec;
1442 >            if (prev <= ec) // help signal
1443 >                casEventCount(ec, ec+1);
1444          }
1445 <        return prev; // return old count if aborted
1445 >        return true;
1446 >    }
1447 >
1448 >    /**
1449 >     * Returns true if a new sync event occurred since last call to
1450 >     * sync or this method, if so, updating caller's count.
1451 >     */
1452 >    final boolean hasNewSyncEvent(ForkJoinWorkerThread w) {
1453 >        long lc = w.lastEventCount;
1454 >        long ec = ensureSync();
1455 >        if (ec == lc)
1456 >            return false;
1457 >        w.lastEventCount = ec;
1458 >        return true;
1459      }
1460  
1461      //  Parallelism maintenance
1462  
1463      /**
1464 <     * Decrement running count; if too low, add spare.
1464 >     * Decrements running count; if too low, adds spare.
1465       *
1466       * Conceptually, all we need to do here is add or resume a
1467       * spare thread when one is about to block (and remove or
# Line 1343 | Line 1481 | public class ForkJoinPool extends Abstra
1481       * only be suspended or removed when they are idle, not
1482       * immediately when they aren't needed. So adding threads will
1483       * raise parallelism level for longer than necessary.  Also,
1484 <     * FJ applications often enounter highly transient peaks when
1484 >     * FJ applications often encounter highly transient peaks when
1485       * many threads are blocked joining, but for less time than it
1486       * takes to create or resume spares.
1487       *
# Line 1408 | Line 1546 | public class ForkJoinPool extends Abstra
1546          return (tc < maxPoolSize &&
1547                  (rc == 0 || totalSurplus < 0 ||
1548                   (maintainParallelism &&
1549 <                  runningDeficit > totalSurplus && mayHaveQueuedWork())));
1550 <    }
1413 <
1414 <    /**
1415 <     * Returns true if at least one worker queue appears to be
1416 <     * nonempty. This is expensive but not often called. It is not
1417 <     * critical that this be accurate, but if not, more or fewer
1418 <     * running threads than desired might be maintained.
1419 <     */
1420 <    private boolean mayHaveQueuedWork() {
1421 <        ForkJoinWorkerThread[] ws = workers;
1422 <        int len = ws.length;
1423 <        ForkJoinWorkerThread v;
1424 <        for (int i = 0; i < len; ++i) {
1425 <            if ((v = ws[i]) != null && v.getRawQueueSize() > 0) {
1426 <                releaseIdleWorkers(false); // help wake up stragglers
1427 <                return true;
1428 <            }
1429 <        }
1430 <        return false;
1549 >                  runningDeficit > totalSurplus &&
1550 >                  ForkJoinWorkerThread.hasQueuedTasks(workers))));
1551      }
1552  
1553      /**
1554 <     * Add a spare worker if lock available and no more than the
1555 <     * expected numbers of threads exist
1554 >     * Adds a spare worker if lock available and no more than the
1555 >     * expected numbers of threads exist.
1556       * @return true if successful
1557       */
1558      private boolean tryAddSpare(int expectedCounts) {
# Line 1465 | Line 1585 | public class ForkJoinPool extends Abstra
1585      }
1586  
1587      /**
1588 <     * Add the kth spare worker. On entry, pool coounts are already
1588 >     * Adds the kth spare worker. On entry, pool counts are already
1589       * adjusted to reflect addition.
1590       */
1591      private void createAndStartSpare(int k) {
# Line 1483 | Line 1603 | public class ForkJoinPool extends Abstra
1603          }
1604          else
1605              updateWorkerCount(-1); // adjust on failure
1606 <        signalIdleWorkers(false);
1606 >        signalIdleWorkers();
1607      }
1608  
1609      /**
1610 <     * Suspend calling thread w if there are excess threads.  Called
1611 <     * only from sync.  Spares are enqueued in a Treiber stack
1612 <     * using the same WaitQueueNodes as barriers.  They are resumed
1613 <     * mainly in preJoin, but are also woken on pool events that
1614 <     * require all threads to check run state.
1610 >     * Suspends calling thread w if there are excess threads.  Called
1611 >     * only from sync.  Spares are enqueued in a Treiber stack using
1612 >     * the same WaitQueueNodes as barriers.  They are resumed mainly
1613 >     * in preJoin, but are also woken on pool events that require all
1614 >     * threads to check run state.
1615       * @param w the caller
1616       */
1617      private boolean suspendIfSpare(ForkJoinWorkerThread w) {
# Line 1499 | Line 1619 | public class ForkJoinPool extends Abstra
1619          int s;
1620          while (parallelism < runningCountOf(s = workerCounts)) {
1621              if (node == null)
1622 <                node = new WaitQueueNode(w, 0);
1622 >                node = new WaitQueueNode(0, w);
1623              if (casWorkerCounts(s, s-1)) { // representation-dependent
1624                  // push onto stack
1625                  do;while (!casSpareStack(node.next = spareStack, node));
1506
1626                  // block until released by resumeSpare
1627 <                while (node.thread != null) {
1509 <                    if (!Thread.interrupted())
1510 <                        LockSupport.park(this);
1511 <                }
1512 <                w.activate(); // help warm up
1627 >                node.awaitSpareRelease();
1628                  return true;
1629              }
1630          }
# Line 1517 | Line 1632 | public class ForkJoinPool extends Abstra
1632      }
1633  
1634      /**
1635 <     * Try to pop and resume a spare thread.
1635 >     * Tries to pop and resume a spare thread.
1636       * @param updateCount if true, increment running count on success
1637       * @return true if successful
1638       */
# Line 1535 | Line 1650 | public class ForkJoinPool extends Abstra
1650      }
1651  
1652      /**
1653 <     * Pop and resume all spare threads. Same idea as
1539 <     * releaseIdleWorkers.
1653 >     * Pops and resumes all spare threads. Same idea as ensureSync.
1654       * @return true if any spares released
1655       */
1656      private boolean resumeAllSpares() {
# Line 1554 | Line 1668 | public class ForkJoinPool extends Abstra
1668      }
1669  
1670      /**
1671 <     * Pop and shutdown excessive spare threads. Call only while
1671 >     * Pops and shuts down excessive spare threads. Call only while
1672       * holding lock. This is not guaranteed to eliminate all excess
1673       * threads, only those suspended as spares, which are the ones
1674       * unlikely to be needed in the future.
# Line 1577 | Line 1691 | public class ForkJoinPool extends Abstra
1691      }
1692  
1693      /**
1580     * Returns approximate number of spares, just for diagnostics.
1581     */
1582    private int countSpares() {
1583        int sum = 0;
1584        for (WaitQueueNode q = spareStack; q != null; q = q.next)
1585            ++sum;
1586        return sum;
1587    }
1588
1589    /**
1694       * Interface for extending managed parallelism for tasks running
1695       * in ForkJoinPools. A ManagedBlocker provides two methods.
1696 <     * Method <code>isReleasable</code> must return true if blocking is not
1697 <     * necessary. Method <code>block</code> blocks the current thread
1696 >     * Method {@code isReleasable} must return true if blocking is not
1697 >     * necessary. Method {@code block} blocks the current thread
1698       * if necessary (perhaps internally invoking isReleasable before
1699       * actually blocking.).
1700       * <p>For example, here is a ManagedBlocker based on a
# Line 1616 | Line 1720 | public class ForkJoinPool extends Abstra
1720           * Possibly blocks the current thread, for example waiting for
1721           * a lock or condition.
1722           * @return true if no additional blocking is necessary (i.e.,
1723 <         * if isReleasable would return true).
1723 >         * if isReleasable would return true)
1724           * @throws InterruptedException if interrupted while waiting
1725 <         * (the method is not required to do so, but is allowe to).
1725 >         * (the method is not required to do so, but is allowed to).
1726           */
1727          boolean block() throws InterruptedException;
1728  
# Line 1633 | Line 1737 | public class ForkJoinPool extends Abstra
1737       * is a ForkJoinWorkerThread, this method possibly arranges for a
1738       * spare thread to be activated if necessary to ensure parallelism
1739       * while the current thread is blocked.  If
1740 <     * <code>maintainParallelism</code> is true and the pool supports
1740 >     * {@code maintainParallelism} is true and the pool supports
1741       * it ({@link #getMaintainsParallelism}), this method attempts to
1742       * maintain the pool's nominal parallelism. Otherwise if activates
1743       * a thread only if necessary to avoid complete starvation. This
# Line 1655 | Line 1759 | public class ForkJoinPool extends Abstra
1759       * attempt to maintain the pool's nominal parallelism; otherwise
1760       * activate a thread only if necessary to avoid complete
1761       * starvation.
1762 <     * @throws InterruptedException if blocker.block did so.
1762 >     * @throws InterruptedException if blocker.block did so
1763       */
1764      public static void managedBlock(ManagedBlocker blocker,
1765                                      boolean maintainParallelism)
# Line 1692 | Line 1796 | public class ForkJoinPool extends Abstra
1796  
1797  
1798      // Temporary Unsafe mechanics for preliminary release
1799 +    private static Unsafe getUnsafe() throws Throwable {
1800 +        try {
1801 +            return Unsafe.getUnsafe();
1802 +        } catch (SecurityException se) {
1803 +            try {
1804 +                return java.security.AccessController.doPrivileged
1805 +                    (new java.security.PrivilegedExceptionAction<Unsafe>() {
1806 +                        public Unsafe run() throws Exception {
1807 +                            return getUnsafePrivileged();
1808 +                        }});
1809 +            } catch (java.security.PrivilegedActionException e) {
1810 +                throw e.getCause();
1811 +            }
1812 +        }
1813 +    }
1814 +
1815 +    private static Unsafe getUnsafePrivileged()
1816 +            throws NoSuchFieldException, IllegalAccessException {
1817 +        Field f = Unsafe.class.getDeclaredField("theUnsafe");
1818 +        f.setAccessible(true);
1819 +        return (Unsafe) f.get(null);
1820 +    }
1821 +
1822 +    private static long fieldOffset(String fieldName)
1823 +            throws NoSuchFieldException {
1824 +        return UNSAFE.objectFieldOffset
1825 +            (ForkJoinPool.class.getDeclaredField(fieldName));
1826 +    }
1827  
1828 <    static final Unsafe _unsafe;
1828 >    static final Unsafe UNSAFE;
1829      static final long eventCountOffset;
1830      static final long workerCountsOffset;
1831      static final long runControlOffset;
1832 <    static final long barrierStackOffset;
1832 >    static final long syncStackOffset;
1833      static final long spareStackOffset;
1834  
1835      static {
1836          try {
1837 <            if (ForkJoinPool.class.getClassLoader() != null) {
1838 <                Field f = Unsafe.class.getDeclaredField("theUnsafe");
1839 <                f.setAccessible(true);
1840 <                _unsafe = (Unsafe)f.get(null);
1841 <            }
1842 <            else
1843 <                _unsafe = Unsafe.getUnsafe();
1712 <            eventCountOffset = _unsafe.objectFieldOffset
1713 <                (ForkJoinPool.class.getDeclaredField("eventCount"));
1714 <            workerCountsOffset = _unsafe.objectFieldOffset
1715 <                (ForkJoinPool.class.getDeclaredField("workerCounts"));
1716 <            runControlOffset = _unsafe.objectFieldOffset
1717 <                (ForkJoinPool.class.getDeclaredField("runControl"));
1718 <            barrierStackOffset = _unsafe.objectFieldOffset
1719 <                (ForkJoinPool.class.getDeclaredField("barrierStack"));
1720 <            spareStackOffset = _unsafe.objectFieldOffset
1721 <                (ForkJoinPool.class.getDeclaredField("spareStack"));
1722 <        } catch (Exception e) {
1837 >            UNSAFE = getUnsafe();
1838 >            eventCountOffset = fieldOffset("eventCount");
1839 >            workerCountsOffset = fieldOffset("workerCounts");
1840 >            runControlOffset = fieldOffset("runControl");
1841 >            syncStackOffset = fieldOffset("syncStack");
1842 >            spareStackOffset = fieldOffset("spareStack");
1843 >        } catch (Throwable e) {
1844              throw new RuntimeException("Could not initialize intrinsics", e);
1845          }
1846      }
1847  
1848      private boolean casEventCount(long cmp, long val) {
1849 <        return _unsafe.compareAndSwapLong(this, eventCountOffset, cmp, val);
1849 >        return UNSAFE.compareAndSwapLong(this, eventCountOffset, cmp, val);
1850      }
1851      private boolean casWorkerCounts(int cmp, int val) {
1852 <        return _unsafe.compareAndSwapInt(this, workerCountsOffset, cmp, val);
1852 >        return UNSAFE.compareAndSwapInt(this, workerCountsOffset, cmp, val);
1853      }
1854      private boolean casRunControl(int cmp, int val) {
1855 <        return _unsafe.compareAndSwapInt(this, runControlOffset, cmp, val);
1855 >        return UNSAFE.compareAndSwapInt(this, runControlOffset, cmp, val);
1856      }
1857      private boolean casSpareStack(WaitQueueNode cmp, WaitQueueNode val) {
1858 <        return _unsafe.compareAndSwapObject(this, spareStackOffset, cmp, val);
1858 >        return UNSAFE.compareAndSwapObject(this, spareStackOffset, cmp, val);
1859      }
1860      private boolean casBarrierStack(WaitQueueNode cmp, WaitQueueNode val) {
1861 <        return _unsafe.compareAndSwapObject(this, barrierStackOffset, cmp, val);
1861 >        return UNSAFE.compareAndSwapObject(this, syncStackOffset, cmp, val);
1862      }
1863   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines