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.2 by dl, Wed Jan 7 16:07:37 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. Otherwise, other
38 < * ExecutorService implementations are typically more appropriate
39 < * 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</code> interface enables extension of
50 < * the kinds of synchronization accommodated.  The target parallelism
51 < * level may also be changed dynamically (<code>setParallelism</code>)
52 < * and dynamically thread construction can be limited using methods
53 < * <code>setMaximumPoolSize</code> and/or
54 < * <code>setMaintainsParallelism</code>.
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</code>) 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</code> 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
70   */
71   public class ForkJoinPool extends AbstractExecutorService {
72  
# Line 69 | 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          /**
92           * Returns a new worker thread operating in the given pool.
93           *
94           * @param pool the pool this thread works in
95 <         * @throws NullPointerException if pool is null;
95 >         * @throws NullPointerException if pool is null
96           */
97          public ForkJoinWorkerThread newThread(ForkJoinPool pool);
98      }
99  
100      /**
101 <     * Default ForkJoinWorkerThreadFactory implementation, creates a
101 >     * Default ForkJoinWorkerThreadFactory implementation; creates a
102       * new ForkJoinWorkerThread.
103       */
104      static class  DefaultForkJoinWorkerThreadFactory
# Line 131 | Line 144 | public class ForkJoinPool extends Abstra
144          new AtomicInteger();
145  
146      /**
147 <     * Array holding all worker threads in the pool. Array size must
148 <     * be a power of two.  Updates and replacements are protected by
149 <     * workerLock, but it is always kept in a consistent enough state
150 <     * to be randomly accessed without locking by workers performing
151 <     * work-stealing.
147 >     * Array holding all worker threads in the pool. Initialized upon
148 >     * first use. Array size must be a power of two.  Updates and
149 >     * replacements are protected by workerLock, but it is always kept
150 >     * in a consistent enough state to be randomly accessed without
151 >     * locking by workers performing work-stealing.
152       */
153      volatile ForkJoinWorkerThread[] workers;
154  
# Line 151 | Line 164 | public class ForkJoinPool extends Abstra
164  
165      /**
166       * The uncaught exception handler used when any worker
167 <     * abrupty terminates
167 >     * abruptly terminates
168       */
169      private Thread.UncaughtExceptionHandler ueh;
170  
# Line 179 | Line 192 | public class ForkJoinPool extends Abstra
192      private final LinkedTransferQueue<ForkJoinTask<?>> submissionQueue;
193  
194      /**
195 <     * Head of Treiber stack for barrier sync. See below for explanation
195 >     * Head of Treiber stack for barrier sync. See below for explanation.
196       */
197 <    private volatile WaitQueueNode barrierStack;
197 >    private volatile WaitQueueNode syncStack;
198  
199      /**
200       * The count for event barrier
# Line 204 | Line 217 | public class ForkJoinPool extends Abstra
217      private volatile int parallelism;
218  
219      /**
220 +     * True if use local fifo, not default lifo, for local polling
221 +     */
222 +    private volatile boolean locallyFifo;
223 +
224 +    /**
225       * Holds number of total (i.e., created and not yet terminated)
226       * and running (i.e., not blocked on joins or other managed sync)
227       * threads, packed into one int to ensure consistent snapshot when
228       * making decisions about creating and suspending spare
229       * threads. Updated only by CAS.  Note: CASes in
230 <     * updateRunningCount and preJoin running active count is in low
231 <     * word, so need to be modified if this changes
230 >     * updateRunningCount and preJoin assume that running active count
231 >     * is in low word, so need to be modified if this changes.
232       */
233      private volatile int workerCounts;
234  
# Line 219 | Line 237 | public class ForkJoinPool extends Abstra
237      private static int workerCountsFor(int t, int r) { return (t << 16) + r; }
238  
239      /**
240 <     * Add delta (which may be negative) to running count.  This must
240 >     * Adds delta (which may be negative) to running count.  This must
241       * be called before (with negative arg) and after (with positive)
242 <     * any managed synchronization (i.e., mainly, joins)
242 >     * any managed synchronization (i.e., mainly, joins).
243 >     *
244       * @param delta the number to add
245       */
246      final void updateRunningCount(int delta) {
247          int s;
248 <        do;while (!casWorkerCounts(s = workerCounts, s + delta));
248 >        do {} while (!casWorkerCounts(s = workerCounts, s + delta));
249      }
250  
251      /**
252 <     * Add delta (which may be negative) to both total and running
252 >     * Adds delta (which may be negative) to both total and running
253       * count.  This must be called upon creation and termination of
254       * worker threads.
255 +     *
256       * @param delta the number to add
257       */
258      private void updateWorkerCount(int delta) {
259          int d = delta + (delta << 16); // add to both lo and hi parts
260          int s;
261 <        do;while (!casWorkerCounts(s = workerCounts, s + d));
261 >        do {} while (!casWorkerCounts(s = workerCounts, s + d));
262      }
263  
264      /**
# Line 264 | Line 284 | public class ForkJoinPool extends Abstra
284      private static int runControlFor(int r, int a)   { return (r << 16) + a; }
285  
286      /**
287 <     * Increment active count. Called by workers before/during
288 <     * executing tasks.
287 >     * Tries incrementing active count; fails on contention.
288 >     * Called by workers before/during executing tasks.
289 >     *
290 >     * @return true on success
291       */
292 <    final void incrementActiveCount() {
293 <        int c;
294 <        do;while (!casRunControl(c = runControl, c+1));
292 >    final boolean tryIncrementActiveCount() {
293 >        int c = runControl;
294 >        return casRunControl(c, c+1);
295      }
296  
297      /**
298 <     * Decrement active count; possibly trigger termination.
298 >     * Tries decrementing active count; fails on contention.
299 >     * Possibly triggers termination on success.
300       * Called by workers when they can't find tasks.
301 +     *
302 +     * @return true on success
303       */
304 <    final void decrementActiveCount() {
305 <        int c, nextc;
306 <        do;while (!casRunControl(c = runControl, nextc = c-1));
304 >    final boolean tryDecrementActiveCount() {
305 >        int c = runControl;
306 >        int nextc = c - 1;
307 >        if (!casRunControl(c, nextc))
308 >            return false;
309          if (canTerminateOnShutdown(nextc))
310              terminateOnShutdown();
311 +        return true;
312      }
313  
314      /**
315 <     * Return 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) {
320 <        return ((c & -c) >>> 16) != 0; // i.e. least bit is nonzero runState bit
320 >        // i.e. least bit is nonzero runState bit
321 >        return ((c & -c) >>> 16) != 0;
322      }
323  
324      /**
# Line 314 | 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 and 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
352       *         because it does not hold {@link
353 <     *         java.lang.RuntimePermission}<code>("modifyThread")</code>,
353 >     *         java.lang.RuntimePermission}{@code ("modifyThread")}
354       */
355      public ForkJoinPool() {
356          this(Runtime.getRuntime().availableProcessors(),
# Line 328 | Line 358 | public class ForkJoinPool extends Abstra
358      }
359  
360      /**
361 <     * Creates a ForkJoinPool with the indicated parellelism 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
367       * equal to zero
368       * @throws SecurityException if a security manager exists and
369       *         the caller is not permitted to modify threads
370       *         because it does not hold {@link
371 <     *         java.lang.RuntimePermission}<code>("modifyThread")</code>,
371 >     *         java.lang.RuntimePermission}{@code ("modifyThread")}
372       */
373      public ForkJoinPool(int parallelism) {
374          this(parallelism, defaultForkJoinWorkerThreadFactory);
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
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(ForkJoinWorkerThreadFactory factory) {
390          this(Runtime.getRuntime().availableProcessors(), factory);
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
399       * @throws IllegalArgumentException if parallelism less than or
400 <     * equal to zero, or greater than implementation limit.
400 >     * equal to zero, or greater than implementation limit
401       * @throws NullPointerException if factory is null
402       * @throws SecurityException if a security manager exists and
403       *         the caller is not permitted to modify threads
404       *         because it does not hold {@link
405 <     *         java.lang.RuntimePermission}<code>("modifyThread")</code>,
405 >     *         java.lang.RuntimePermission}{@code ("modifyThread")}
406       */
407      public ForkJoinPool(int parallelism, ForkJoinWorkerThreadFactory factory) {
408          if (parallelism <= 0 || parallelism > MAX_THREADS)
# Line 385 | Line 419 | public class ForkJoinPool extends Abstra
419          this.termination = workerLock.newCondition();
420          this.stealCount = new AtomicLong();
421          this.submissionQueue = new LinkedTransferQueue<ForkJoinTask<?>>();
422 <        createAndStartInitialWorkers(parallelism);
422 >        // worker array and workers are lazily constructed
423      }
424  
425      /**
426 <     * Create new worker using factory.
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 399 | Line 434 | public class ForkJoinPool extends Abstra
434          if (w != null) {
435              w.poolIndex = index;
436              w.setDaemon(true);
437 +            w.setAsyncMode(locallyFifo);
438              w.setName("ForkJoinPool-" + poolNumber + "-worker-" + index);
439              if (h != null)
440                  w.setUncaughtExceptionHandler(h);
# Line 407 | Line 443 | public class ForkJoinPool extends Abstra
443      }
444  
445      /**
446 <     * Return a good size for worker array given pool size.
446 >     * Returns a good size for worker array given pool size.
447       * Currently requires size to be a power of two.
448       */
449 <    private static int arraySizeFor(int ps) {
450 <        return ps <= 1? 1 : (1 << (32 - Integer.numberOfLeadingZeros(ps-1)));
449 >    private static int arraySizeFor(int poolSize) {
450 >        return (poolSize <= 1) ? 1 :
451 >            (1 << (32 - Integer.numberOfLeadingZeros(poolSize-1)));
452      }
453  
454      /**
455 <     * Create or resize array if necessary to hold newLength
455 >     * Creates or resizes array if necessary to hold newLength.
456 >     * Call only under exclusion.
457 >     *
458       * @return the array
459       */
460      private ForkJoinWorkerThread[] ensureWorkerArrayCapacity(int newLength) {
# Line 429 | Line 468 | public class ForkJoinPool extends Abstra
468      }
469  
470      /**
471 <     * Try to shrink workers into smaller array after one or more terminate
471 >     * Tries to shrink workers into smaller array after one or more terminate.
472       */
473      private void tryShrinkWorkerArray() {
474          ForkJoinWorkerThread[] ws = workers;
475 <        int len = ws.length;
476 <        int last = len - 1;
477 <        while (last >= 0 && ws[last] == null)
478 <            --last;
479 <        int newLength = arraySizeFor(last+1);
480 <        if (newLength < len)
481 <            workers = Arrays.copyOf(ws, newLength);
475 >        if (ws != null) {
476 >            int len = ws.length;
477 >            int last = len - 1;
478 >            while (last >= 0 && ws[last] == null)
479 >                --last;
480 >            int newLength = arraySizeFor(last+1);
481 >            if (newLength < len)
482 >                workers = Arrays.copyOf(ws, newLength);
483 >        }
484      }
485  
486      /**
487 <     * 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.)
487 >     * Initializes workers if necessary.
488       */
489 <    private void createAndStartInitialWorkers(int ps) {
490 <        final ReentrantLock lock = this.workerLock;
491 <        lock.lock();
492 <        try {
493 <            ForkJoinWorkerThread[] ws = ensureWorkerArrayCapacity(ps);
494 <            for (int i = 0; i < ps; ++i) {
495 <                ForkJoinWorkerThread w = createWorker(i);
496 <                if (w != null) {
497 <                    ws[i] = w;
498 <                    w.start();
499 <                    updateWorkerCount(1);
489 >    final void ensureWorkerInitialization() {
490 >        ForkJoinWorkerThread[] ws = workers;
491 >        if (ws == null) {
492 >            final ReentrantLock lock = this.workerLock;
493 >            lock.lock();
494 >            try {
495 >                ws = workers;
496 >                if (ws == null) {
497 >                    int ps = parallelism;
498 >                    ws = ensureWorkerArrayCapacity(ps);
499 >                    for (int i = 0; i < ps; ++i) {
500 >                        ForkJoinWorkerThread w = createWorker(i);
501 >                        if (w != null) {
502 >                            ws[i] = w;
503 >                            w.start();
504 >                            updateWorkerCount(1);
505 >                        }
506 >                    }
507                  }
508 +            } finally {
509 +                lock.unlock();
510              }
463        } finally {
464            lock.unlock();
511          }
512      }
513  
# Line 505 | 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)
559 +            ensureWorkerInitialization();
560          submissionQueue.offer(task);
561 <        signalIdleWorkers(true);
561 >        signalIdleWorkers();
562      }
563  
564      /**
565 <     * Performs the given task; returning its result upon completion
565 >     * Performs the given task, returning its result upon completion.
566 >     *
567       * @param task the task
568       * @return the task's result
569       * @throws NullPointerException if task is null
# Line 525 | Line 576 | public class ForkJoinPool extends Abstra
576  
577      /**
578       * Arranges for (asynchronous) execution of the given task.
579 +     *
580       * @param task the task
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;
567 <        final T resultOnCompletion;
568 <        T result;
569 <        AdaptedRunnable(Runnable runnable, T result) {
570 <            if (runnable == null) throw new NullPointerException();
571 <            this.runnable = runnable;
572 <            this.resultOnCompletion = result;
573 <        }
574 <        public T getRawResult() { return result; }
575 <        public void setRawResult(T v) { result = v; }
576 <        public boolean exec() {
577 <            runnable.run();
578 <            result = resultOnCompletion;
579 <            return true;
580 <        }
581 <        public void run() { invoke(); }
630 >    public <T> ForkJoinTask<T> submit(ForkJoinTask<T> task) {
631 >        doSubmit(task);
632 >        return task;
633      }
634  
584    /**
585     * Adaptor for Callables
586     */
587    static final class AdaptedCallable<T> extends ForkJoinTask<T>
588        implements RunnableFuture<T> {
589        final Callable<T> callable;
590        T result;
591        AdaptedCallable(Callable<T> callable) {
592            if (callable == null) throw new NullPointerException();
593            this.callable = callable;
594        }
595        public T getRawResult() { return result; }
596        public void setRawResult(T v) { result = v; }
597        public boolean exec() {
598            try {
599                result = callable.call();
600                return true;
601            } catch (Error err) {
602                throw err;
603            } catch (RuntimeException rex) {
604                throw rex;
605            } catch (Exception ex) {
606                throw new RuntimeException(ex);
607            }
608        }
609        public void run() { invoke(); }
610    }
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 {
649          final ArrayList<ForkJoinTask<T>> tasks;
650          InvokeAll(ArrayList<ForkJoinTask<T>> tasks) { this.tasks = tasks; }
651          public void compute() {
652 <            try { invokeAll(tasks); } catch(Exception ignore) {}
652 >            try { invokeAll(tasks); }
653 >            catch (Exception ignore) {}
654          }
655 +        private static final long serialVersionUID = -7914297376763021607L;
656      }
657  
658      // Configuration and status settings and queries
659  
660      /**
661 <     * Returns the factory used for constructing new workers
661 >     * Returns the factory used for constructing new workers.
662       *
663       * @return the factory used for constructing new workers
664       */
# Line 640 | Line 669 | public class ForkJoinPool extends Abstra
669      /**
670       * Returns the handler for internal worker threads that terminate
671       * due to unrecoverable errors encountered while executing tasks.
672 <     * @return the handler, or null if none
672 >     *
673 >     * @return the handler, or {@code null} if none
674       */
675      public Thread.UncaughtExceptionHandler getUncaughtExceptionHandler() {
676          Thread.UncaughtExceptionHandler h;
# Line 661 | 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
698 <     *         java.lang.RuntimePermission}<code>("modifyThread")</code>,
698 >     *         java.lang.RuntimePermission}{@code ("modifyThread")}
699       */
700      public Thread.UncaughtExceptionHandler
701          setUncaughtExceptionHandler(Thread.UncaughtExceptionHandler h) {
# Line 677 | Line 707 | public class ForkJoinPool extends Abstra
707              old = ueh;
708              ueh = h;
709              ForkJoinWorkerThread[] ws = workers;
710 <            for (int i = 0; i < ws.length; ++i) {
711 <                ForkJoinWorkerThread w = ws[i];
712 <                if (w != null)
713 <                    w.setUncaughtExceptionHandler(h);
710 >            if (ws != null) {
711 >                for (int i = 0; i < ws.length; ++i) {
712 >                    ForkJoinWorkerThread w = ws[i];
713 >                    if (w != null)
714 >                        w.setUncaughtExceptionHandler(h);
715 >                }
716              }
717          } finally {
718              lock.unlock();
# Line 690 | Line 722 | public class ForkJoinPool extends Abstra
722  
723  
724      /**
725 <     * Sets the target paralleism level of this pool.
725 >     * Sets the target parallelism level of this pool.
726 >     *
727       * @param parallelism the target parallelism
728       * @throws IllegalArgumentException if parallelism less than or
729 <     * equal to zero or greater than maximum size bounds.
729 >     * equal to zero or greater than maximum size bounds
730       * @throws SecurityException if a security manager exists and
731       *         the caller is not permitted to modify threads
732       *         because it does not hold {@link
733 <     *         java.lang.RuntimePermission}<code>("modifyThread")</code>,
733 >     *         java.lang.RuntimePermission}{@code ("modifyThread")}
734       */
735      public void setParallelism(int parallelism) {
736          checkPermission();
# Line 717 | Line 750 | public class ForkJoinPool extends Abstra
750          } finally {
751              lock.unlock();
752          }
753 <        signalIdleWorkers(false);
753 >        signalIdleWorkers();
754      }
755  
756      /**
# Line 732 | 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</code> 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 744 | Line 777 | public class ForkJoinPool extends Abstra
777      /**
778       * Returns the maximum number of threads allowed to exist in the
779       * pool, even if there are insufficient unblocked running threads.
780 +     *
781       * @return the maximum
782       */
783      public int getMaximumPoolSize() {
# Line 755 | Line 789 | public class ForkJoinPool extends Abstra
789       * pool, even if there are insufficient unblocked running threads.
790       * Setting this value has no effect on current pool size. It
791       * controls construction of new threads.
792 <     * @throws IllegalArgumentException if negative or greater then
793 <     * internal implementation limit.
792 >     *
793 >     * @throws IllegalArgumentException if negative or greater than
794 >     * internal implementation limit
795       */
796      public void setMaximumPoolSize(int newMax) {
797          if (newMax < 0 || newMax > MAX_THREADS)
# Line 766 | 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.
807 <     * This setting is by default true;
808 <     * @return true if maintains parallelism
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 {@code true} if maintains parallelism
809       */
810      public boolean getMaintainsParallelism() {
811          return maintainsParallelism;
# Line 780 | Line 815 | public class ForkJoinPool extends Abstra
815       * Sets whether this pool dynamically maintains its target
816       * parallelism level. If false, new threads are added only to
817       * avoid possible starvation.
818 <     * @param enable true to maintains parallelism
818 >     *
819 >     * @param enable {@code true} to maintain parallelism
820       */
821      public void setMaintainsParallelism(boolean enable) {
822          maintainsParallelism = enable;
823      }
824  
825      /**
826 +     * Establishes local first-in-first-out scheduling mode for forked
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 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 {@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;
840 +        locallyFifo = async;
841 +        ForkJoinWorkerThread[] ws = workers;
842 +        if (ws != null) {
843 +            for (int i = 0; i < ws.length; ++i) {
844 +                ForkJoinWorkerThread t = ws[i];
845 +                if (t != null)
846 +                    t.setAsyncMode(async);
847 +            }
848 +        }
849 +        return oldMode;
850 +    }
851 +
852 +    /**
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 {@code true} if this pool uses async mode
857 +     * @see #setAsyncMode
858 +     */
859 +    public boolean getAsyncMode() {
860 +        return locallyFifo;
861 +    }
862 +
863 +    /**
864       * Returns an estimate of the number of worker threads that are
865       * not blocked waiting to join tasks or for other managed
866       * synchronization.
# Line 801 | Line 875 | public class ForkJoinPool extends Abstra
875       * Returns an estimate of the number of threads that are currently
876       * stealing or executing tasks. This method may overestimate the
877       * number of active threads.
878 <     * @return the number of active threads.
878 >     *
879 >     * @return the number of active threads
880       */
881      public int getActiveThreadCount() {
882          return activeCountOf(runControl);
# Line 811 | Line 886 | public class ForkJoinPool extends Abstra
886       * Returns an estimate of the number of threads that are currently
887       * idle waiting for tasks. This method may underestimate the
888       * number of idle threads.
889 <     * @return the number of idle threads.
889 >     *
890 >     * @return the number of idle threads
891       */
892      final int getIdleThreadCount() {
893          int c = runningCountOf(workerCounts) - activeCountOf(runControl);
894 <        return (c <= 0)? 0 : c;
894 >        return (c <= 0) ? 0 : c;
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.
905 <     * @return true if all threads are currently idle
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 {@code true} if all threads are currently idle
907       */
908      public boolean isQuiescent() {
909          return activeCountOf(runControl) == 0;
# Line 837 | Line 914 | public class ForkJoinPool extends Abstra
914       * one thread's work queue by another. The reported value
915       * underestimates the actual total number of steals when the pool
916       * is not quiescent. This value may be useful for monitoring and
917 <     * tuning fork/join programs: In general, steal counts should be
917 >     * tuning fork/join programs: in general, steal counts should be
918       * high enough to keep threads busy, but low enough to avoid
919       * overhead and contention across threads.
920 <     * @return the number of steals.
920 >     *
921 >     * @return the number of steals
922       */
923      public long getStealCount() {
924          return stealCount.get();
925      }
926  
927      /**
928 <     * Accumulate steal count from a worker. Call only
929 <     * when worker known to be idle.
928 >     * Accumulates steal count from a worker.
929 >     * Call only when worker known to be idle.
930       */
931      private void updateStealCount(ForkJoinWorkerThread w) {
932          int sc = w.getAndClearStealCount();
# Line 863 | Line 941 | public class ForkJoinPool extends Abstra
941       * an approximation, obtained by iterating across all threads in
942       * the pool. This method may be useful for tuning task
943       * granularities.
944 <     * @return the number of queued tasks.
944 >     *
945 >     * @return the number of queued tasks
946       */
947      public long getQueuedTaskCount() {
948          long count = 0;
949          ForkJoinWorkerThread[] ws = workers;
950 <        for (int i = 0; i < ws.length; ++i) {
951 <            ForkJoinWorkerThread t = ws[i];
952 <            if (t != null)
953 <                count += t.getQueueSize();
950 >        if (ws != null) {
951 >            for (int i = 0; i < ws.length; ++i) {
952 >                ForkJoinWorkerThread t = ws[i];
953 >                if (t != null)
954 >                    count += t.getQueueSize();
955 >            }
956          }
957          return count;
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 <     * @return the number of queued submissions.
964 >     *
965 >     * @return the number of queued submissions
966       */
967      public int getQueuedSubmissionCount() {
968          return submissionQueue.size();
969      }
970  
971      /**
972 <     * Returns true if there are any tasks submitted to this pool
973 <     * that have not yet begun executing.
974 <     * @return <code>true</code> if there are any queued submissions.
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       */
977      public boolean hasQueuedSubmissions() {
978          return !submissionQueue.isEmpty();
# Line 899 | Line 982 | public class ForkJoinPool extends Abstra
982       * Removes and returns the next unexecuted submission if one is
983       * available.  This method may be useful in extensions to this
984       * class that re-assign work in systems with multiple pools.
985 <     * @return the next submission, or null if none
985 >     *
986 >     * @return the next submission, or {@code null} if none
987       */
988      protected ForkJoinTask<?> pollSubmission() {
989          return submissionQueue.poll();
990      }
991  
992      /**
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
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
1001 +     * neither, either or both collections when the associated
1002 +     * exception is thrown.  The behavior of this operation is
1003 +     * undefined if the specified collection is modified while the
1004 +     * operation is in progress.
1005 +     *
1006 +     * @param c the collection to transfer elements into
1007 +     * @return the number of elements transferred
1008 +     */
1009 +    protected int drainTasksTo(Collection<? super ForkJoinTask<?>> c) {
1010 +        int n = submissionQueue.drainTo(c);
1011 +        ForkJoinWorkerThread[] ws = workers;
1012 +        if (ws != null) {
1013 +            for (int i = 0; i < ws.length; ++i) {
1014 +                ForkJoinWorkerThread w = ws[i];
1015 +                if (w != null)
1016 +                    n += w.drainTasksTo(c);
1017 +            }
1018 +        }
1019 +        return n;
1020 +    }
1021 +
1022 +    /**
1023       * Returns a string identifying this pool, as well as its state,
1024       * including indications of run state, parallelism level, and
1025       * worker and task counts.
# Line 949 | Line 1063 | public class ForkJoinPool extends Abstra
1063       * Invocation has no additional effect if already shut down.
1064       * Tasks that are in the process of being submitted concurrently
1065       * during the course of this method may or may not be rejected.
1066 +     *
1067       * @throws SecurityException if a security manager exists and
1068       *         the caller is not permitted to modify threads
1069       *         because it does not hold {@link
1070 <     *         java.lang.RuntimePermission}<code>("modifyThread")</code>,
1070 >     *         java.lang.RuntimePermission}{@code ("modifyThread")}
1071       */
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 966 | Line 1095 | public class ForkJoinPool extends Abstra
1095       * waiting tasks.  Tasks that are in the process of being
1096       * submitted or executed concurrently during the course of this
1097       * method may or may not be rejected. Unlike some other executors,
1098 <     * this method cancels rather than collects non-executed tasks,
1099 <     * so always returns an empty list.
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 {@link #drainTasksTo} before invoking this
1101 >     * method to transfer unexecuted tasks to another collection.
1102 >     *
1103       * @return an empty list
1104       * @throws SecurityException if a security manager exists and
1105       *         the caller is not permitted to modify threads
1106       *         because it does not hold {@link
1107 <     *         java.lang.RuntimePermission}<code>("modifyThread")</code>,
1107 >     *         java.lang.RuntimePermission}{@code ("modifyThread")}
1108       */
1109      public List<Runnable> shutdownNow() {
1110          checkPermission();
# Line 981 | Line 1113 | public class ForkJoinPool extends Abstra
1113      }
1114  
1115      /**
1116 <     * Returns <code>true</code> if all tasks have completed following shut down.
1116 >     * Returns {@code true} if all tasks have completed following shut down.
1117       *
1118 <     * @return <code>true</code> if all tasks have completed following shut down
1118 >     * @return {@code true} if all tasks have completed following shut down
1119       */
1120      public boolean isTerminated() {
1121          return runStateOf(runControl) == TERMINATED;
1122      }
1123  
1124      /**
1125 <     * Returns <code>true</code> if the process of termination has
1125 >     * Returns {@code true} if the process of termination has
1126       * commenced but possibly not yet completed.
1127       *
1128 <     * @return <code>true</code> if terminating
1128 >     * @return {@code true} if terminating
1129       */
1130      public boolean isTerminating() {
1131          return runStateOf(runControl) >= TERMINATING;
1132      }
1133  
1134      /**
1135 <     * Returns <code>true</code> if this pool has been shut down.
1135 >     * Returns {@code true} if this pool has been shut down.
1136       *
1137 <     * @return <code>true</code> if this pool has been shut down
1137 >     * @return {@code true} if this pool has been shut down
1138       */
1139      public boolean isShutdown() {
1140          return runStateOf(runControl) >= SHUTDOWN;
# Line 1015 | Line 1147 | public class ForkJoinPool extends Abstra
1147       *
1148       * @param timeout the maximum time to wait
1149       * @param unit the time unit of the timeout argument
1150 <     * @return <code>true</code> if this executor terminated and
1151 <     *         <code>false</code> if the timeout elapsed before termination
1150 >     * @return {@code true} if this executor terminated and
1151 >     *         {@code false} if the timeout elapsed before termination
1152       * @throws InterruptedException if interrupted while waiting
1153       */
1154      public boolean awaitTermination(long timeout, TimeUnit unit)
# Line 1040 | Line 1172 | public class ForkJoinPool extends Abstra
1172      // Shutdown and termination support
1173  
1174      /**
1175 <     * Callback from terminating worker. Null out the corresponding
1176 <     * workers slot, and if terminating, try to terminate, else try to
1177 <     * shrink workers array.
1175 >     * Callback from terminating worker. Nulls out the corresponding
1176 >     * workers slot, and if terminating, tries to terminate; else
1177 >     * tries to shrink workers array.
1178 >     *
1179       * @param w the worker
1180       */
1181      final void workerTerminated(ForkJoinWorkerThread w) {
# Line 1052 | Line 1185 | public class ForkJoinPool extends Abstra
1185          lock.lock();
1186          try {
1187              ForkJoinWorkerThread[] ws = workers;
1188 <            int idx = w.poolIndex;
1189 <            if (idx >= 0 && idx < ws.length && ws[idx] == w)
1190 <                ws[idx] = null;
1191 <            if (totalCountOf(workerCounts) == 0) {
1192 <                terminate(); // no-op if already terminating
1193 <                transitionRunStateTo(TERMINATED);
1194 <                termination.signalAll();
1195 <            }
1196 <            else if (!isTerminating()) {
1197 <                tryShrinkWorkerArray();
1198 <                tryResumeSpare(true); // allow replacement
1188 >            if (ws != null) {
1189 >                int idx = w.poolIndex;
1190 >                if (idx >= 0 && idx < ws.length && ws[idx] == w)
1191 >                    ws[idx] = null;
1192 >                if (totalCountOf(workerCounts) == 0) {
1193 >                    terminate(); // no-op if already terminating
1194 >                    transitionRunStateTo(TERMINATED);
1195 >                    termination.signalAll();
1196 >                }
1197 >                else if (!isTerminating()) {
1198 >                    tryShrinkWorkerArray();
1199 >                    tryResumeSpare(true); // allow replacement
1200 >                }
1201              }
1202          } finally {
1203              lock.unlock();
1204          }
1205 <        signalIdleWorkers(false);
1205 >        signalIdleWorkers();
1206      }
1207  
1208      /**
1209 <     * Initiate termination.
1209 >     * Initiates termination.
1210       */
1211      private void terminate() {
1212          if (transitionRunStateTo(TERMINATING)) {
1213              stopAllWorkers();
1214              resumeAllSpares();
1215 <            signalIdleWorkers(true);
1215 >            signalIdleWorkers();
1216              cancelQueuedSubmissions();
1217              cancelQueuedWorkerTasks();
1218              interruptUnterminatedWorkers();
1219 <            signalIdleWorkers(true); // resignal after interrupt
1219 >            signalIdleWorkers(); // resignal after interrupt
1220          }
1221      }
1222  
1223      /**
1224 <     * Possibly terminate when on shutdown state
1224 >     * Possibly terminates when on shutdown state.
1225       */
1226      private void terminateOnShutdown() {
1227          if (!hasQueuedSubmissions() && canTerminateOnShutdown(runControl))
# Line 1094 | Line 1229 | public class ForkJoinPool extends Abstra
1229      }
1230  
1231      /**
1232 <     * Clear out and cancel submissions
1232 >     * Clears out and cancels submissions.
1233       */
1234      private void cancelQueuedSubmissions() {
1235          ForkJoinTask<?> task;
# Line 1103 | Line 1238 | public class ForkJoinPool extends Abstra
1238      }
1239  
1240      /**
1241 <     * Clean out worker queues.
1241 >     * Cleans out worker queues.
1242       */
1243      private void cancelQueuedWorkerTasks() {
1244          final ReentrantLock lock = this.workerLock;
1245          lock.lock();
1246          try {
1247              ForkJoinWorkerThread[] ws = workers;
1248 <            for (int i = 0; i < ws.length; ++i) {
1249 <                ForkJoinWorkerThread t = ws[i];
1250 <                if (t != null)
1251 <                    t.cancelTasks();
1248 >            if (ws != null) {
1249 >                for (int i = 0; i < ws.length; ++i) {
1250 >                    ForkJoinWorkerThread t = ws[i];
1251 >                    if (t != null)
1252 >                        t.cancelTasks();
1253 >                }
1254              }
1255          } finally {
1256              lock.unlock();
# Line 1121 | Line 1258 | public class ForkJoinPool extends Abstra
1258      }
1259  
1260      /**
1261 <     * Set each worker's status to terminating. Requires lock to avoid
1262 <     * conflicts with add/remove
1261 >     * Sets each worker's status to terminating. Requires lock to avoid
1262 >     * conflicts with add/remove.
1263       */
1264      private void stopAllWorkers() {
1265          final ReentrantLock lock = this.workerLock;
1266          lock.lock();
1267          try {
1268              ForkJoinWorkerThread[] ws = workers;
1269 <            for (int i = 0; i < ws.length; ++i) {
1270 <                ForkJoinWorkerThread t = ws[i];
1271 <                if (t != null)
1272 <                    t.shutdownNow();
1269 >            if (ws != null) {
1270 >                for (int i = 0; i < ws.length; ++i) {
1271 >                    ForkJoinWorkerThread t = ws[i];
1272 >                    if (t != null)
1273 >                        t.shutdownNow();
1274 >                }
1275              }
1276          } finally {
1277              lock.unlock();
# Line 1140 | Line 1279 | public class ForkJoinPool extends Abstra
1279      }
1280  
1281      /**
1282 <     * Interrupt all unterminated workers.  This is not required for
1282 >     * Interrupts all unterminated workers.  This is not required for
1283       * sake of internal control, but may help unstick user code during
1284       * shutdown.
1285       */
# Line 1149 | Line 1288 | public class ForkJoinPool extends Abstra
1288          lock.lock();
1289          try {
1290              ForkJoinWorkerThread[] ws = workers;
1291 <            for (int i = 0; i < ws.length; ++i) {
1292 <                ForkJoinWorkerThread t = ws[i];
1293 <                if (t != null && !t.isTerminated()) {
1294 <                    try {
1295 <                        t.interrupt();
1296 <                    } catch (SecurityException ignore) {
1291 >            if (ws != null) {
1292 >                for (int i = 0; i < ws.length; ++i) {
1293 >                    ForkJoinWorkerThread t = ws[i];
1294 >                    if (t != null && !t.isTerminated()) {
1295 >                        try {
1296 >                            t.interrupt();
1297 >                        } catch (SecurityException ignore) {
1298 >                        }
1299                      }
1300                  }
1301              }
# Line 1165 | Line 1306 | public class ForkJoinPool extends Abstra
1306  
1307  
1308      /*
1309 <     * Nodes for event barrier to manage idle threads.
1309 >     * Nodes for event barrier to manage idle threads.  Queue nodes
1310 >     * are basic Treiber stack nodes, also used for spare stack.
1311       *
1312       * The event barrier has an event count and a wait queue (actually
1313       * a Treiber stack).  Workers are enabled to look for work when
1314 <     * the eventCount is incremented. If they fail to find some,
1315 <     * they may wait for next count. Synchronization events occur only
1316 <     * in enough contexts to maintain overall liveness:
1314 >     * the eventCount is incremented. If they fail to find work, they
1315 >     * may wait for next count. Upon release, threads help others wake
1316 >     * up.
1317 >     *
1318 >     * Synchronization events occur only in enough contexts to
1319 >     * maintain overall liveness:
1320       *
1321       *   - Submission of a new task to the pool
1322 <     *   - Creation or termination of a worker
1322 >     *   - Resizes or other changes to the workers array
1323       *   - pool termination
1324       *   - A worker pushing a task on an empty queue
1325       *
1326 <     * The last case (pushing a task) occurs often enough, and is
1327 <     * heavy enough compared to simple stack pushes to require some
1328 <     * special handling: Method signalNonEmptyWorkerQueue returns
1329 <     * without advancing count if the queue appears to be empty.  This
1330 <     * would ordinarily result in races causing some queued waiters
1331 <     * not to be woken up. To avoid this, a worker in sync
1332 <     * rescans for tasks after being enqueued if it was the first to
1333 <     * enqueue, and aborts the wait if finding one, also helping to
1334 <     * signal others. This works well because the worker has nothing
1335 <     * better to do anyway, and so might as well help alleviate the
1336 <     * overhead and contention on the threads actually doing work.
1337 <     *
1338 <     * Queue nodes are basic Treiber stack nodes, also used for spare
1339 <     * stack.
1326 >     * The case of pushing a task occurs often enough, and is heavy
1327 >     * enough compared to simple stack pushes, to require special
1328 >     * handling: Method signalWork returns without advancing count if
1329 >     * the queue appears to be empty.  This would ordinarily result in
1330 >     * races causing some queued waiters not to be woken up. To avoid
1331 >     * this, the first worker enqueued in method sync (see
1332 >     * syncIsReleasable) rescans for tasks after being enqueued, and
1333 >     * helps signal if any are found. This works well because the
1334 >     * worker has nothing better to do, and so might as well help
1335 >     * alleviate the overhead and contention on the threads actually
1336 >     * doing work.  Also, since event counts increments on task
1337 >     * availability exist to maintain liveness (rather than to force
1338 >     * refreshes etc), it is OK for callers to exit early if
1339 >     * contending with another signaller.
1340       */
1341      static final class WaitQueueNode {
1342          WaitQueueNode next; // only written before enqueued
1343          volatile ForkJoinWorkerThread thread; // nulled to cancel wait
1344          final long count; // unused for spare stack
1345 <        WaitQueueNode(ForkJoinWorkerThread w, long c) {
1345 >
1346 >        WaitQueueNode(long c, ForkJoinWorkerThread w) {
1347              count = c;
1348              thread = w;
1349          }
1350 <        final boolean signal() {
1350 >
1351 >        /**
1352 >         * Wakes up waiter, returning false if known to already
1353 >         */
1354 >        boolean signal() {
1355              ForkJoinWorkerThread t = thread;
1356 +            if (t == null)
1357 +                return false;
1358              thread = null;
1359 <            if (t != null) {
1360 <                LockSupport.unpark(t);
1361 <                return true;
1359 >            LockSupport.unpark(t);
1360 >            return true;
1361 >        }
1362 >
1363 >        /**
1364 >         * Awaits release on sync.
1365 >         */
1366 >        void awaitSyncRelease(ForkJoinPool p) {
1367 >            while (thread != null && !p.syncIsReleasable(this))
1368 >                LockSupport.park(this);
1369 >        }
1370 >
1371 >        /**
1372 >         * Awaits resumption as spare.
1373 >         */
1374 >        void awaitSpareRelease() {
1375 >            while (thread != null) {
1376 >                if (!Thread.interrupted())
1377 >                    LockSupport.park(this);
1378              }
1211            return false;
1379          }
1380      }
1381  
1382      /**
1383 <     * Release at least one thread waiting for event count to advance,
1384 <     * if one exists. If initial attempt fails, release all threads.
1385 <     * @param all if false, at first try to only release one thread
1386 <     * @return current event
1383 >     * Ensures that no thread is waiting for count to advance from the
1384 >     * current value of eventCount read on entry to this method, by
1385 >     * releasing waiting threads if necessary.
1386 >     *
1387 >     * @return the count
1388       */
1389 <    private long releaseIdleWorkers(boolean all) {
1390 <        long c;
1391 <        for (;;) {
1392 <            WaitQueueNode q = barrierStack;
1393 <            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)) {
1389 >    final long ensureSync() {
1390 >        long c = eventCount;
1391 >        WaitQueueNode q;
1392 >        while ((q = syncStack) != null && q.count < c) {
1393 >            if (casBarrierStack(q, null)) {
1394                  do {
1395 <                 q.signal();
1395 >                    q.signal();
1396                  } while ((q = q.next) != null);
1397                  break;
1398              }
# Line 1242 | Line 1401 | public class ForkJoinPool extends Abstra
1401      }
1402  
1403      /**
1404 <     * Returns current barrier event count
1246 <     * @return current barrier event count
1404 >     * Increments event count and releases waiting threads.
1405       */
1406 <    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) {
1406 >    private void signalIdleWorkers() {
1407          long c;
1408 <        do;while (!casEventCount(c = eventCount, c+1));
1409 <        releaseIdleWorkers(all);
1408 >        do {} while (!casEventCount(c = eventCount, c+1));
1409 >        ensureSync();
1410      }
1411  
1412      /**
1413 <     * Wake up threads waiting to steal a task. Because method
1414 <     * sync rechecks availability, it is OK to only proceed if
1415 <     * queue appears to be non-empty.
1413 >     * Signals threads waiting to poll a task. Because method sync
1414 >     * rechecks availability, it is OK to only proceed if queue
1415 >     * appears to be non-empty, and OK to skip under contention to
1416 >     * increment count (since some other thread succeeded).
1417       */
1418 <    final void signalNonEmptyWorkerQueue() {
1271 <        // If CAS fails another signaller must have succeeded
1418 >    final void signalWork() {
1419          long c;
1420 <        if (barrierStack != null && casEventCount(c = eventCount, c+1))
1421 <            releaseIdleWorkers(false);
1420 >        WaitQueueNode q;
1421 >        if (syncStack != null &&
1422 >            casEventCount(c = eventCount, c+1) &&
1423 >            (((q = syncStack) != null && q.count <= c) &&
1424 >             (!casBarrierStack(q, q.next) || !q.signal())))
1425 >            ensureSync();
1426      }
1427  
1428      /**
1429 <     * Waits until event count advances from count, or some thread is
1430 <     * waiting on a previous count, or there is stealable work
1431 <     * available. Help wake up others on release.
1429 >     * Waits until event count advances from last value held by
1430 >     * caller, or if excess threads, caller is resumed as spare, or
1431 >     * caller or pool is terminating. Updates caller's event on exit.
1432 >     *
1433       * @param w the calling worker thread
1282     * @param prev previous value returned by sync (or 0)
1283     * @return current event count
1434       */
1435 <    final long sync(ForkJoinWorkerThread w, long prev) {
1436 <        updateStealCount(w);
1435 >    final void sync(ForkJoinWorkerThread w) {
1436 >        updateStealCount(w); // Transfer w's count while it is idle
1437  
1438 <        while (!w.isShutdown() && !isTerminating() &&
1439 <               (parallelism >= runningCountOf(workerCounts) ||
1290 <                !suspendIfSpare(w))) { // prefer suspend to waiting here
1438 >        while (!w.isShutdown() && !isTerminating() && !suspendIfSpare(w)) {
1439 >            long prev = w.lastEventCount;
1440              WaitQueueNode node = null;
1441 <            boolean queued = false;
1442 <            for (;;) {
1443 <                if (!queued) {
1444 <                    if (eventCount != prev)
1445 <                        break;
1446 <                    WaitQueueNode h = barrierStack;
1447 <                    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);
1441 >            WaitQueueNode h;
1442 >            while (eventCount == prev &&
1443 >                   ((h = syncStack) == null || h.count == prev)) {
1444 >                if (node == null)
1445 >                    node = new WaitQueueNode(prev, w);
1446 >                if (casBarrierStack(node.next = h, node)) {
1447 >                    node.awaitSyncRelease(this);
1448                      break;
1449                  }
1313                else
1314                    LockSupport.park(this);
1450              }
1451 +            long ec = ensureSync();
1452 +            if (ec != prev) {
1453 +                w.lastEventCount = ec;
1454 +                break;
1455 +            }
1456 +        }
1457 +    }
1458 +
1459 +    /**
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
1464 +     *  - if the first queued node, we find work available
1465 +     * If node was not signalled and event count not advanced on exit,
1466 +     * then we also help advance event count.
1467 +     *
1468 +     * @return {@code true} if node can be released
1469 +     */
1470 +    final boolean syncIsReleasable(WaitQueueNode node) {
1471 +        long prev = node.count;
1472 +        if (!Thread.interrupted() && node.thread != null &&
1473 +            (node.next != null ||
1474 +             !ForkJoinWorkerThread.hasQueuedTasks(workers)) &&
1475 +            eventCount == prev)
1476 +            return false;
1477 +        if (node.thread != null) {
1478 +            node.thread = null;
1479              long ec = eventCount;
1480 <            if (releaseIdleWorkers(false) != prev)
1481 <                return ec;
1480 >            if (prev <= ec) // help signal
1481 >                casEventCount(ec, ec+1);
1482          }
1483 <        return prev; // return old count if aborted
1483 >        return true;
1484 >    }
1485 >
1486 >    /**
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;
1492 >        long ec = ensureSync();
1493 >        if (ec == lc)
1494 >            return false;
1495 >        w.lastEventCount = ec;
1496 >        return true;
1497      }
1498  
1499      //  Parallelism maintenance
1500  
1501      /**
1502 <     * Decrement running count; if too low, add spare.
1502 >     * Decrements running count; if too low, adds spare.
1503       *
1504       * Conceptually, all we need to do here is add or resume a
1505       * spare thread when one is about to block (and remove or
1506       * suspend it later when unblocked -- see suspendIfSpare).
1507       * However, implementing this idea requires coping with
1508 <     * several problems: We have imperfect information about the
1508 >     * several problems: we have imperfect information about the
1509       * states of threads. Some count updates can and usually do
1510       * lag run state changes, despite arrangements to keep them
1511       * accurate (for example, when possible, updating counts
# Line 1343 | Line 1519 | public class ForkJoinPool extends Abstra
1519       * only be suspended or removed when they are idle, not
1520       * immediately when they aren't needed. So adding threads will
1521       * raise parallelism level for longer than necessary.  Also,
1522 <     * FJ applications often enounter highly transient peaks when
1522 >     * FJ applications often encounter highly transient peaks when
1523       * many threads are blocked joining, but for less time than it
1524       * takes to create or resume spares.
1525       *
# Line 1352 | Line 1528 | public class ForkJoinPool extends Abstra
1528       * target counts, else create only to avoid starvation
1529       * @return true if joinMe known to be done
1530       */
1531 <    final boolean preJoin(ForkJoinTask<?> joinMe, boolean maintainParallelism) {
1531 >    final boolean preJoin(ForkJoinTask<?> joinMe,
1532 >                          boolean maintainParallelism) {
1533          maintainParallelism &= maintainsParallelism; // overrride
1534          boolean dec = false;  // true when running count decremented
1535          while (spareStack == null || !tryResumeSpare(dec)) {
1536              int counts = workerCounts;
1537 <            if (dec || (dec = casWorkerCounts(counts, --counts))) { // CAS cheat
1537 >            if (dec || (dec = casWorkerCounts(counts, --counts))) {
1538 >                // CAS cheat
1539                  if (!needSpare(counts, maintainParallelism))
1540                      break;
1541                  if (joinMe.status < 0)
# Line 1372 | Line 1550 | public class ForkJoinPool extends Abstra
1550      /**
1551       * Same idea as preJoin
1552       */
1553 <    final boolean preBlock(ManagedBlocker blocker, boolean maintainParallelism){
1553 >    final boolean preBlock(ManagedBlocker blocker,
1554 >                           boolean maintainParallelism) {
1555          maintainParallelism &= maintainsParallelism;
1556          boolean dec = false;
1557          while (spareStack == null || !tryResumeSpare(dec)) {
# Line 1390 | 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
1577       * less parallelism we will tolerate before adding another.
1578 +     *
1579       * @param counts current worker counts
1580       * @param maintainParallelism try to maintain parallelism
1581       */
# Line 1408 | Line 1588 | public class ForkJoinPool extends Abstra
1588          return (tc < maxPoolSize &&
1589                  (rc == 0 || totalSurplus < 0 ||
1590                   (maintainParallelism &&
1591 <                  runningDeficit > totalSurplus && mayHaveQueuedWork())));
1591 >                  runningDeficit > totalSurplus &&
1592 >                  ForkJoinWorkerThread.hasQueuedTasks(workers))));
1593      }
1594  
1595      /**
1596 <     * Returns true if at least one worker queue appears to be
1597 <     * nonempty. This is expensive but not often called. It is not
1598 <     * 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;
1431 <    }
1432 <
1433 <    /**
1434 <     * Add a spare worker if lock available and no more than the
1435 <     * expected numbers of threads exist
1596 >     * Adds a spare worker if lock available and no more than the
1597 >     * expected numbers of threads exist.
1598 >     *
1599       * @return true if successful
1600       */
1601      private boolean tryAddSpare(int expectedCounts) {
# Line 1465 | Line 1628 | public class ForkJoinPool extends Abstra
1628      }
1629  
1630      /**
1631 <     * Add the kth spare worker. On entry, pool coounts are already
1631 >     * Adds the kth spare worker. On entry, pool counts are already
1632       * adjusted to reflect addition.
1633       */
1634      private void createAndStartSpare(int k) {
# Line 1477 | Line 1640 | public class ForkJoinPool extends Abstra
1640              for (k = 0; k < len && ws[k] != null; ++k)
1641                  ;
1642          }
1643 <        if (k < len && (w = createWorker(k)) != null) {
1643 >        if (k < len && !isTerminating() && (w = createWorker(k)) != null) {
1644              ws[k] = w;
1645              w.start();
1646          }
1647          else
1648              updateWorkerCount(-1); // adjust on failure
1649 <        signalIdleWorkers(false);
1649 >        signalIdleWorkers();
1650      }
1651  
1652      /**
1653 <     * Suspend calling thread w if there are excess threads.  Called
1654 <     * only from sync.  Spares are enqueued in a Treiber stack
1655 <     * using the same WaitQueueNodes as barriers.  They are resumed
1656 <     * mainly in preJoin, but are also woken on pool events that
1657 <     * require all threads to check run state.
1653 >     * Suspends calling thread w if there are excess threads.  Called
1654 >     * only from sync.  Spares are enqueued in a Treiber stack using
1655 >     * the same WaitQueueNodes as barriers.  They are resumed mainly
1656 >     * in preJoin, but are also woken on pool events that require all
1657 >     * threads to check run state.
1658 >     *
1659       * @param w the caller
1660       */
1661      private boolean suspendIfSpare(ForkJoinWorkerThread w) {
# Line 1499 | Line 1663 | public class ForkJoinPool extends Abstra
1663          int s;
1664          while (parallelism < runningCountOf(s = workerCounts)) {
1665              if (node == null)
1666 <                node = new WaitQueueNode(w, 0);
1666 >                node = new WaitQueueNode(0, w);
1667              if (casWorkerCounts(s, s-1)) { // representation-dependent
1668                  // push onto stack
1669 <                do;while (!casSpareStack(node.next = spareStack, node));
1506 <
1669 >                do {} while (!casSpareStack(node.next = spareStack, node));
1670                  // block until released by resumeSpare
1671 <                while (node.thread != null) {
1509 <                    if (!Thread.interrupted())
1510 <                        LockSupport.park(this);
1511 <                }
1512 <                w.activate(); // help warm up
1671 >                node.awaitSpareRelease();
1672                  return true;
1673              }
1674          }
# Line 1517 | Line 1676 | public class ForkJoinPool extends Abstra
1676      }
1677  
1678      /**
1679 <     * Try to pop and resume a spare thread.
1679 >     * Tries to pop and resume a spare thread.
1680 >     *
1681       * @param updateCount if true, increment running count on success
1682       * @return true if successful
1683       */
# Line 1535 | Line 1695 | public class ForkJoinPool extends Abstra
1695      }
1696  
1697      /**
1698 <     * Pop and resume all spare threads. Same idea as
1699 <     * releaseIdleWorkers.
1698 >     * Pops and resumes all spare threads. Same idea as ensureSync.
1699 >     *
1700       * @return true if any spares released
1701       */
1702      private boolean resumeAllSpares() {
# Line 1554 | Line 1714 | public class ForkJoinPool extends Abstra
1714      }
1715  
1716      /**
1717 <     * Pop and shutdown excessive spare threads. Call only while
1717 >     * Pops and shuts down excessive spare threads. Call only while
1718       * holding lock. This is not guaranteed to eliminate all excess
1719       * threads, only those suspended as spares, which are the ones
1720       * unlikely to be needed in the future.
# Line 1577 | Line 1737 | public class ForkJoinPool extends Abstra
1737      }
1738  
1739      /**
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    /**
1740       * Interface for extending managed parallelism for tasks running
1741 <     * in ForkJoinPools. A ManagedBlocker provides two methods.
1742 <     * Method <code>isReleasable</code> must return true if blocking is not
1743 <     * necessary. Method <code>block</code> blocks the current thread
1744 <     * if necessary (perhaps internally invoking isReleasable before
1745 <     * 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:
1751 <     * <pre>
1752 <     *   class ManagedLocker implements ManagedBlocker {
1753 <     *     final ReentrantLock lock;
1754 <     *     boolean hasLock = false;
1755 <     *     ManagedLocker(ReentrantLock lock) { this.lock = lock; }
1756 <     *     public boolean block() {
1757 <     *        if (!hasLock)
1758 <     *           lock.lock();
1759 <     *        return true;
1607 <     *     }
1608 <     *     public boolean isReleasable() {
1609 <     *        return hasLock || (hasLock = lock.tryLock());
1610 <     *     }
1751 >     *  <pre> {@code
1752 >     * class ManagedLocker implements ManagedBlocker {
1753 >     *   final ReentrantLock lock;
1754 >     *   boolean hasLock = false;
1755 >     *   ManagedLocker(ReentrantLock lock) { this.lock = lock; }
1756 >     *   public boolean block() {
1757 >     *     if (!hasLock)
1758 >     *       lock.lock();
1759 >     *     return true;
1760       *   }
1761 <     * </pre>
1761 >     *   public boolean isReleasable() {
1762 >     *     return hasLock || (hasLock = lock.tryLock());
1763 >     *   }
1764 >     * }}</pre>
1765       */
1766      public static interface ManagedBlocker {
1767          /**
1768           * Possibly blocks the current thread, for example waiting for
1769           * a lock or condition.
1770 <         * @return true if no additional blocking is necessary (i.e.,
1771 <         * if isReleasable would return true).
1770 >         *
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 allowe to).
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</code> is true and the pool supports
1790 <     * it ({@link #getMaintainsParallelism}), this method attempts to
1791 <     * maintain the pool's nominal parallelism. Otherwise if 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.
1795 <     *
1796 <     * <p> If the caller is not a ForkJoinTask, this method is behaviorally
1797 <     * equivalent to
1798 <     * <pre>
1799 <     *   while (!blocker.isReleasable())
1800 <     *      if (blocker.block())
1801 <     *         return;
1802 <     * </pre>
1803 <     * If the caller is a ForkJoinTask, then the pool may first
1804 <     * be expanded to ensure parallelism, and later adjusted.
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 {@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 >     *
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.
1813 <     * @throws InterruptedException if blocker.block did so.
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,
1816                                      boolean maintainParallelism)
1817          throws InterruptedException {
1818          Thread t = Thread.currentThread();
1819 <        ForkJoinPool pool = (t instanceof ForkJoinWorkerThread?
1820 <                             ((ForkJoinWorkerThread)t).pool : null);
1819 >        ForkJoinPool pool = ((t instanceof ForkJoinWorkerThread) ?
1820 >                             ((ForkJoinWorkerThread) t).pool : null);
1821          if (!blocker.isReleasable()) {
1822              try {
1823                  if (pool == null ||
# Line 1677 | Line 1832 | public class ForkJoinPool extends Abstra
1832  
1833      private static void awaitBlocker(ManagedBlocker blocker)
1834          throws InterruptedException {
1835 <        do;while (!blocker.isReleasable() && !blocker.block());
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(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(callable);
1847 >        return (RunnableFuture<T>) ForkJoinTask.adapt(callable);
1848      }
1849  
1850 +    // Unsafe mechanics
1851  
1852 <    // Temporary Unsafe mechanics for preliminary release
1853 <
1854 <    static final Unsafe _unsafe;
1855 <    static final long eventCountOffset;
1856 <    static final long workerCountsOffset;
1857 <    static final long runControlOffset;
1858 <    static final long barrierStackOffset;
1859 <    static final long spareStackOffset;
1860 <
1861 <    static {
1862 <        try {
1705 <            if (ForkJoinPool.class.getClassLoader() != null) {
1706 <                Field f = Unsafe.class.getDeclaredField("theUnsafe");
1707 <                f.setAccessible(true);
1708 <                _unsafe = (Unsafe)f.get(null);
1709 <            }
1710 <            else
1711 <                _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) {
1723 <            throw new RuntimeException("Could not initialize intrinsics", e);
1724 <        }
1725 <    }
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);
1865 >        return UNSAFE.compareAndSwapLong(this, eventCountOffset, cmp, val);
1866      }
1867      private boolean casWorkerCounts(int cmp, int val) {
1868 <        return _unsafe.compareAndSwapInt(this, workerCountsOffset, cmp, val);
1868 >        return UNSAFE.compareAndSwapInt(this, workerCountsOffset, cmp, val);
1869      }
1870      private boolean casRunControl(int cmp, int val) {
1871 <        return _unsafe.compareAndSwapInt(this, runControlOffset, cmp, val);
1871 >        return UNSAFE.compareAndSwapInt(this, runControlOffset, cmp, val);
1872      }
1873      private boolean casSpareStack(WaitQueueNode cmp, WaitQueueNode val) {
1874 <        return _unsafe.compareAndSwapObject(this, spareStackOffset, cmp, val);
1874 >        return UNSAFE.compareAndSwapObject(this, spareStackOffset, cmp, val);
1875      }
1876      private boolean casBarrierStack(WaitQueueNode cmp, WaitQueueNode val) {
1877 <        return _unsafe.compareAndSwapObject(this, barrierStackOffset, cmp, 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