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.5 by jsr166, Thu Mar 19 05:10:42 2009 UTC vs.
Revision 1.42 by dl, Mon Aug 3 13:01:15 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
20 < * submitted tasks. Otherwise, use would not usually outweigh the
21 < * construction and bookkeeping overhead of creating a large set of
22 < * threads.
23 > * An {@link ExecutorService} for running {@link ForkJoinTask}s.
24 > * A {@code ForkJoinPool} provides the entry point for submissions
25 > * from non-{@code ForkJoinTask}s, as well as management and
26 > * monitoring operations.  
27   *
28 < * <p>ForkJoinPools differ from other kinds of Executors mainly in
29 < * that they provide <em>work-stealing</em>: all threads in the pool
30 < * attempt to find and execute subtasks created by other active tasks
31 < * (eventually blocking if none exist). This makes them efficient when
32 < * most tasks spawn other subtasks (as do most ForkJoinTasks), as well
33 < * as the mixed execution of some plain Runnable- or Callable- based
34 < * activities along with ForkJoinTasks. Otherwise, other
35 < * ExecutorService implementations are typically more appropriate
36 < * choices.
28 > * <p>A {@code ForkJoinPool} differs from other kinds of {@link
29 > * ExecutorService} mainly by virtue of employing
30 > * <em>work-stealing</em>: all threads in the pool attempt to find and
31 > * execute subtasks created by other active tasks (eventually blocking
32 > * waiting for work if none exist). This enables efficient processing
33 > * when most tasks spawn other subtasks (as do most {@code
34 > * ForkJoinTask}s). A {@code ForkJoinPool} may also be used for mixed
35 > * execution of some plain {@code Runnable}- or {@code Callable}-
36 > * based activities along with {@code ForkJoinTask}s. When setting
37 > * {@linkplain #setAsyncMode async mode}, a {@code ForkJoinPool} may
38 > * also be appropriate for use with fine-grained tasks of any form
39 > * that are never joined. Otherwise, other {@code ExecutorService}
40 > * implementations are typically more appropriate choices.
41   *
42 < * <p>A ForkJoinPool may be constructed with a given parallelism level
43 < * (target pool size), which it attempts to maintain by dynamically
44 < * adding, suspending, or resuming threads, even if some tasks are
45 < * waiting to join others. However, no such adjustments are performed
46 < * in the face of blocked IO or other unmanaged synchronization. The
47 < * nested <code>ManagedBlocker</code> interface enables extension of
48 < * the kinds of synchronization accommodated.  The target parallelism
49 < * level may also be changed dynamically (<code>setParallelism</code>)
50 < * and dynamically thread construction can be limited using methods
51 < * <code>setMaximumPoolSize</code> and/or
52 < * <code>setMaintainsParallelism</code>.
42 > * <p>A {@code ForkJoinPool} is constructed with a given target
43 > * parallelism level; by default, equal to the number of available
44 > * processors. Unless configured otherwise via {@link
45 > * #setMaintainsParallelism}, the pool attempts to maintain this
46 > * number of active (or available) threads by dynamically adding,
47 > * suspending, or resuming internal worker threads, even if some tasks
48 > * are waiting to join others. However, no such adjustments are
49 > * performed in the face of blocked IO or other unmanaged
50 > * synchronization. The nested {@link ManagedBlocker} interface
51 > * enables extension of the kinds of synchronization accommodated.
52 > * The target parallelism level may also be changed dynamically
53 > * ({@link #setParallelism}). The total number of threads may be
54 > * limited using method {@link #setMaximumPoolSize}, in which case it
55 > * may become possible for the activities of a pool to stall due to
56 > * the lack of available threads to process new tasks.
57   *
58   * <p>In addition to execution and lifecycle control methods, this
59   * class provides status check methods (for example
60 < * <code>getStealCount</code>) that are intended to aid in developing,
60 > * {@link #getStealCount}) that are intended to aid in developing,
61   * tuning, and monitoring fork/join applications. Also, method
62 < * <code>toString</code> returns indications of pool state in a
62 > * {@link #toString} returns indications of pool state in a
63   * convenient form for informal monitoring.
64   *
65 + * <p><b>Sample Usage.</b> Normally a single {@code ForkJoinPool} is
66 + * used for all parallel task execution in a program or subsystem.
67 + * Otherwise, use would not usually outweigh the construction and
68 + * bookkeeping overhead of creating a large set of threads. For
69 + * example a common pool could be used for the {@code SortTasks}
70 + * illustrated in {@link RecursiveAction}. Because {@code
71 + * ForkJoinPool} uses threads in {@linkplain java.lang.Thread#isDaemon
72 + * daemon} mode, there is typically no need to explictly {@link
73 + * #shutdown} such a pool upon program exit.
74 + *
75 + * <pre>
76 + * static final ForkJoinPool mainPool = new ForkJoinPool();
77 + * ...
78 + * public void sort(long[] array) {
79 + *   mainPool.invoke(new SortTask(array, 0, array.length));
80 + * }
81 + * </pre>
82 + *
83   * <p><b>Implementation notes</b>: This implementation restricts the
84   * maximum number of running threads to 32767. Attempts to create
85   * pools with greater than the maximum result in
86 < * IllegalArgumentExceptions.
86 > * {@code IllegalArgumentException}.
87 > *
88 > * @since 1.7
89 > * @author Doug Lea
90   */
91   public class ForkJoinPool extends AbstractExecutorService {
92  
# Line 69 | Line 102 | public class ForkJoinPool extends Abstra
102      private static final int MAX_THREADS =  0x7FFF;
103  
104      /**
105 <     * Factory for creating new ForkJoinWorkerThreads.  A
106 <     * ForkJoinWorkerThreadFactory must be defined and used for
107 <     * ForkJoinWorkerThread subclasses that extend base functionality
108 <     * or initialize threads with different contexts.
105 >     * Factory for creating new {@link ForkJoinWorkerThread}s.
106 >     * A {@code ForkJoinWorkerThreadFactory} must be defined and used
107 >     * for {@code ForkJoinWorkerThread} subclasses that extend base
108 >     * functionality or initialize threads with different contexts.
109       */
110      public static interface ForkJoinWorkerThreadFactory {
111          /**
112           * Returns a new worker thread operating in the given pool.
113           *
114           * @param pool the pool this thread works in
115 <         * @throws NullPointerException if pool is null;
115 >         * @throws NullPointerException if pool is null
116           */
117          public ForkJoinWorkerThread newThread(ForkJoinPool pool);
118      }
119  
120      /**
121 <     * Default ForkJoinWorkerThreadFactory implementation, creates a
121 >     * Default ForkJoinWorkerThreadFactory implementation; creates a
122       * new ForkJoinWorkerThread.
123       */
124      static class  DefaultForkJoinWorkerThreadFactory
# Line 131 | Line 164 | public class ForkJoinPool extends Abstra
164          new AtomicInteger();
165  
166      /**
167 <     * Array holding all worker threads in the pool. Array size must
168 <     * be a power of two.  Updates and replacements are protected by
169 <     * workerLock, but it is always kept in a consistent enough state
170 <     * to be randomly accessed without locking by workers performing
171 <     * work-stealing.
167 >     * Array holding all worker threads in the pool. Initialized upon
168 >     * first use. Array size must be a power of two.  Updates and
169 >     * replacements are protected by workerLock, but it is always kept
170 >     * in a consistent enough state to be randomly accessed without
171 >     * locking by workers performing work-stealing.
172       */
173      volatile ForkJoinWorkerThread[] workers;
174  
# Line 151 | Line 184 | public class ForkJoinPool extends Abstra
184  
185      /**
186       * The uncaught exception handler used when any worker
187 <     * abrupty terminates
187 >     * abruptly terminates
188       */
189      private Thread.UncaughtExceptionHandler ueh;
190  
# Line 179 | Line 212 | public class ForkJoinPool extends Abstra
212      private final LinkedTransferQueue<ForkJoinTask<?>> submissionQueue;
213  
214      /**
215 <     * Head of Treiber stack for barrier sync. See below for explanation
215 >     * Head of Treiber stack for barrier sync. See below for explanation.
216       */
217      private volatile WaitQueueNode syncStack;
218  
# Line 204 | Line 237 | public class ForkJoinPool extends Abstra
237      private volatile int parallelism;
238  
239      /**
240 +     * True if use local fifo, not default lifo, for local polling
241 +     */
242 +    private volatile boolean locallyFifo;
243 +
244 +    /**
245       * Holds number of total (i.e., created and not yet terminated)
246       * and running (i.e., not blocked on joins or other managed sync)
247       * threads, packed into one int to ensure consistent snapshot when
248       * making decisions about creating and suspending spare
249       * threads. Updated only by CAS.  Note: CASes in
250 <     * updateRunningCount and preJoin running active count is in low
251 <     * word, so need to be modified if this changes
250 >     * updateRunningCount and preJoin assume that running active count
251 >     * is in low word, so need to be modified if this changes.
252       */
253      private volatile int workerCounts;
254  
# Line 219 | Line 257 | public class ForkJoinPool extends Abstra
257      private static int workerCountsFor(int t, int r) { return (t << 16) + r; }
258  
259      /**
260 <     * Add delta (which may be negative) to running count.  This must
260 >     * Adds delta (which may be negative) to running count.  This must
261       * be called before (with negative arg) and after (with positive)
262 <     * any managed synchronization (i.e., mainly, joins)
262 >     * any managed synchronization (i.e., mainly, joins).
263 >     *
264       * @param delta the number to add
265       */
266      final void updateRunningCount(int delta) {
267          int s;
268 <        do;while (!casWorkerCounts(s = workerCounts, s + delta));
268 >        do {} while (!casWorkerCounts(s = workerCounts, s + delta));
269      }
270  
271      /**
272 <     * Add delta (which may be negative) to both total and running
272 >     * Adds delta (which may be negative) to both total and running
273       * count.  This must be called upon creation and termination of
274       * worker threads.
275 +     *
276       * @param delta the number to add
277       */
278      private void updateWorkerCount(int delta) {
279          int d = delta + (delta << 16); // add to both lo and hi parts
280          int s;
281 <        do;while (!casWorkerCounts(s = workerCounts, s + d));
281 >        do {} while (!casWorkerCounts(s = workerCounts, s + d));
282      }
283  
284      /**
# Line 264 | Line 304 | public class ForkJoinPool extends Abstra
304      private static int runControlFor(int r, int a)   { return (r << 16) + a; }
305  
306      /**
307 <     * Try incrementing active count; fail on contention. Called by
308 <     * workers before/during executing tasks.
309 <     * @return true on success;
307 >     * Tries incrementing active count; fails on contention.
308 >     * Called by workers before/during executing tasks.
309 >     *
310 >     * @return true on success
311       */
312      final boolean tryIncrementActiveCount() {
313          int c = runControl;
# Line 274 | Line 315 | public class ForkJoinPool extends Abstra
315      }
316  
317      /**
318 <     * Try decrementing active count; fail on contention.
319 <     * Possibly trigger termination on success
318 >     * Tries decrementing active count; fails on contention.
319 >     * Possibly triggers termination on success.
320       * Called by workers when they can't find tasks.
321 +     *
322       * @return true on success
323       */
324      final boolean tryDecrementActiveCount() {
# Line 290 | Line 332 | public class ForkJoinPool extends Abstra
332      }
333  
334      /**
335 <     * Return true if argument represents zero active count and
336 <     * nonzero runstate, which is the triggering condition for
335 >     * Returns {@code true} if argument represents zero active count
336 >     * and nonzero runstate, which is the triggering condition for
337       * terminating on shutdown.
338       */
339      private static boolean canTerminateOnShutdown(int c) {
340 <        return ((c & -c) >>> 16) != 0; // i.e. least bit is nonzero runState bit
340 >        // i.e. least bit is nonzero runState bit
341 >        return ((c & -c) >>> 16) != 0;
342      }
343  
344      /**
# Line 320 | Line 363 | public class ForkJoinPool extends Abstra
363      // Constructors
364  
365      /**
366 <     * Creates a ForkJoinPool with a pool size equal to the number of
367 <     * processors available on the system and using the default
368 <     * ForkJoinWorkerThreadFactory,
366 >     * Creates a {@code ForkJoinPool} with parallelism equal to {@link
367 >     * java.lang.Runtime#availableProcessors}, and using the {@linkplain
368 >     * #defaultForkJoinWorkerThreadFactory default thread factory}.
369 >     *
370       * @throws SecurityException if a security manager exists and
371       *         the caller is not permitted to modify threads
372       *         because it does not hold {@link
373 <     *         java.lang.RuntimePermission}<code>("modifyThread")</code>,
373 >     *         java.lang.RuntimePermission}{@code ("modifyThread")}
374       */
375      public ForkJoinPool() {
376          this(Runtime.getRuntime().availableProcessors(),
# Line 334 | Line 378 | public class ForkJoinPool extends Abstra
378      }
379  
380      /**
381 <     * Creates a ForkJoinPool with the indicated parellelism level
382 <     * threads, and using the default ForkJoinWorkerThreadFactory,
383 <     * @param parallelism the number of worker threads
381 >     * Creates a {@code ForkJoinPool} with the indicated parallelism
382 >     * level and using the {@linkplain
383 >     * #defaultForkJoinWorkerThreadFactory default thread factory}.
384 >     *
385 >     * @param parallelism the parallelism level
386       * @throws IllegalArgumentException if parallelism less than or
387       * equal to zero
388       * @throws SecurityException if a security manager exists and
389       *         the caller is not permitted to modify threads
390       *         because it does not hold {@link
391 <     *         java.lang.RuntimePermission}<code>("modifyThread")</code>,
391 >     *         java.lang.RuntimePermission}{@code ("modifyThread")}
392       */
393      public ForkJoinPool(int parallelism) {
394          this(parallelism, defaultForkJoinWorkerThreadFactory);
395      }
396  
397      /**
398 <     * Creates a ForkJoinPool with parallelism equal to the number of
399 <     * processors available on the system and using the given
400 <     * ForkJoinWorkerThreadFactory,
398 >     * Creates a {@code ForkJoinPool} with parallelism equal to {@link
399 >     * java.lang.Runtime#availableProcessors}, and using the given
400 >     * thread factory.
401 >     *
402       * @param factory the factory for creating new threads
403       * @throws NullPointerException if factory is null
404       * @throws SecurityException if a security manager exists and
405       *         the caller is not permitted to modify threads
406       *         because it does not hold {@link
407 <     *         java.lang.RuntimePermission}<code>("modifyThread")</code>,
407 >     *         java.lang.RuntimePermission}{@code ("modifyThread")}
408       */
409      public ForkJoinPool(ForkJoinWorkerThreadFactory factory) {
410          this(Runtime.getRuntime().availableProcessors(), factory);
411      }
412  
413      /**
414 <     * Creates a ForkJoinPool with the given parallelism and factory.
414 >     * Creates a {@code ForkJoinPool} with the given parallelism and
415 >     * thread factory.
416       *
417 <     * @param parallelism the targeted number of worker threads
417 >     * @param parallelism the parallelism level
418       * @param factory the factory for creating new threads
419       * @throws IllegalArgumentException if parallelism less than or
420 <     * equal to zero, or greater than implementation limit.
420 >     * equal to zero, or greater than implementation limit
421       * @throws NullPointerException if factory is null
422       * @throws SecurityException if a security manager exists and
423       *         the caller is not permitted to modify threads
424       *         because it does not hold {@link
425 <     *         java.lang.RuntimePermission}<code>("modifyThread")</code>,
425 >     *         java.lang.RuntimePermission}{@code ("modifyThread")}
426       */
427      public ForkJoinPool(int parallelism, ForkJoinWorkerThreadFactory factory) {
428          if (parallelism <= 0 || parallelism > MAX_THREADS)
# Line 391 | Line 439 | public class ForkJoinPool extends Abstra
439          this.termination = workerLock.newCondition();
440          this.stealCount = new AtomicLong();
441          this.submissionQueue = new LinkedTransferQueue<ForkJoinTask<?>>();
442 <        createAndStartInitialWorkers(parallelism);
442 >        // worker array and workers are lazily constructed
443      }
444  
445      /**
446 <     * Create new worker using factory.
446 >     * Creates a new worker thread using factory.
447 >     *
448       * @param index the index to assign worker
449 <     * @return new worker, or null of factory failed
449 >     * @return new worker, or null if factory failed
450       */
451      private ForkJoinWorkerThread createWorker(int index) {
452          Thread.UncaughtExceptionHandler h = ueh;
# Line 405 | Line 454 | public class ForkJoinPool extends Abstra
454          if (w != null) {
455              w.poolIndex = index;
456              w.setDaemon(true);
457 +            w.setAsyncMode(locallyFifo);
458              w.setName("ForkJoinPool-" + poolNumber + "-worker-" + index);
459              if (h != null)
460                  w.setUncaughtExceptionHandler(h);
# Line 413 | Line 463 | public class ForkJoinPool extends Abstra
463      }
464  
465      /**
466 <     * Return a good size for worker array given pool size.
466 >     * Returns a good size for worker array given pool size.
467       * Currently requires size to be a power of two.
468       */
469 <    private static int arraySizeFor(int ps) {
470 <        return ps <= 1? 1 : (1 << (32 - Integer.numberOfLeadingZeros(ps-1)));
469 >    private static int arraySizeFor(int poolSize) {
470 >        if (poolSize <= 1)
471 >            return 1;
472 >        // See Hackers Delight, sec 3.2
473 >        int c = poolSize >= MAX_THREADS ? MAX_THREADS : (poolSize - 1);
474 >        c |= c >>>  1;
475 >        c |= c >>>  2;
476 >        c |= c >>>  4;
477 >        c |= c >>>  8;
478 >        c |= c >>> 16;
479 >        return c + 1;
480      }
481  
482      /**
483 <     * Create or resize array if necessary to hold newLength
483 >     * Creates or resizes array if necessary to hold newLength.
484 >     * Call only under exclusion.
485 >     *
486       * @return the array
487       */
488      private ForkJoinWorkerThread[] ensureWorkerArrayCapacity(int newLength) {
# Line 435 | Line 496 | public class ForkJoinPool extends Abstra
496      }
497  
498      /**
499 <     * Try to shrink workers into smaller array after one or more terminate
499 >     * Tries to shrink workers into smaller array after one or more terminate.
500       */
501      private void tryShrinkWorkerArray() {
502          ForkJoinWorkerThread[] ws = workers;
503 <        int len = ws.length;
504 <        int last = len - 1;
505 <        while (last >= 0 && ws[last] == null)
506 <            --last;
507 <        int newLength = arraySizeFor(last+1);
508 <        if (newLength < len)
509 <            workers = Arrays.copyOf(ws, newLength);
503 >        if (ws != null) {
504 >            int len = ws.length;
505 >            int last = len - 1;
506 >            while (last >= 0 && ws[last] == null)
507 >                --last;
508 >            int newLength = arraySizeFor(last+1);
509 >            if (newLength < len)
510 >                workers = Arrays.copyOf(ws, newLength);
511 >        }
512      }
513  
514      /**
515 <     * Initial worker array and worker creation and startup. (This
453 <     * must be done under lock to avoid interference by some of the
454 <     * newly started threads while creating others.)
515 >     * Initializes workers if necessary.
516       */
517 <    private void createAndStartInitialWorkers(int ps) {
518 <        final ReentrantLock lock = this.workerLock;
519 <        lock.lock();
520 <        try {
521 <            ForkJoinWorkerThread[] ws = ensureWorkerArrayCapacity(ps);
522 <            for (int i = 0; i < ps; ++i) {
523 <                ForkJoinWorkerThread w = createWorker(i);
524 <                if (w != null) {
525 <                    ws[i] = w;
526 <                    w.start();
527 <                    updateWorkerCount(1);
517 >    final void ensureWorkerInitialization() {
518 >        ForkJoinWorkerThread[] ws = workers;
519 >        if (ws == null) {
520 >            final ReentrantLock lock = this.workerLock;
521 >            lock.lock();
522 >            try {
523 >                ws = workers;
524 >                if (ws == null) {
525 >                    int ps = parallelism;
526 >                    ws = ensureWorkerArrayCapacity(ps);
527 >                    for (int i = 0; i < ps; ++i) {
528 >                        ForkJoinWorkerThread w = createWorker(i);
529 >                        if (w != null) {
530 >                            ws[i] = w;
531 >                            w.start();
532 >                            updateWorkerCount(1);
533 >                        }
534 >                    }
535                  }
536 +            } finally {
537 +                lock.unlock();
538              }
469        } finally {
470            lock.unlock();
539          }
540      }
541  
# Line 511 | Line 579 | public class ForkJoinPool extends Abstra
579       * Common code for execute, invoke and submit
580       */
581      private <T> void doSubmit(ForkJoinTask<T> task) {
582 +        if (task == null)
583 +            throw new NullPointerException();
584          if (isShutdown())
585              throw new RejectedExecutionException();
586 +        if (workers == null)
587 +            ensureWorkerInitialization();
588          submissionQueue.offer(task);
589          signalIdleWorkers();
590      }
591  
592      /**
593 <     * Performs the given task; returning its result upon completion
593 >     * Performs the given task, returning its result upon completion.
594 >     *
595       * @param task the task
596       * @return the task's result
597       * @throws NullPointerException if task is null
# Line 531 | Line 604 | public class ForkJoinPool extends Abstra
604  
605      /**
606       * Arranges for (asynchronous) execution of the given task.
607 +     *
608       * @param task the task
609       * @throws NullPointerException if task is null
610       * @throws RejectedExecutionException if pool is shut down
611       */
612 <    public <T> void execute(ForkJoinTask<T> task) {
612 >    public void execute(ForkJoinTask<?> task) {
613          doSubmit(task);
614      }
615  
616      // AbstractExecutorService methods
617  
618      public void execute(Runnable task) {
619 <        doSubmit(new AdaptedRunnable<Void>(task, null));
619 >        ForkJoinTask<?> job;
620 >        if (task instanceof ForkJoinTask<?>) // avoid re-wrap
621 >            job = (ForkJoinTask<?>) task;
622 >        else
623 >            job = ForkJoinTask.adapt(task, null);
624 >        doSubmit(job);
625      }
626  
627      public <T> ForkJoinTask<T> submit(Callable<T> task) {
628 <        ForkJoinTask<T> job = new AdaptedCallable<T>(task);
628 >        ForkJoinTask<T> job = ForkJoinTask.adapt(task);
629          doSubmit(job);
630          return job;
631      }
632  
633      public <T> ForkJoinTask<T> submit(Runnable task, T result) {
634 <        ForkJoinTask<T> job = new AdaptedRunnable<T>(task, result);
634 >        ForkJoinTask<T> job = ForkJoinTask.adapt(task, result);
635          doSubmit(job);
636          return job;
637      }
638  
639      public ForkJoinTask<?> submit(Runnable task) {
640 <        ForkJoinTask<Void> job = new AdaptedRunnable<Void>(task, null);
640 >        ForkJoinTask<?> job;
641 >        if (task instanceof ForkJoinTask<?>) // avoid re-wrap
642 >            job = (ForkJoinTask<?>) task;
643 >        else
644 >            job = ForkJoinTask.adapt(task, null);
645          doSubmit(job);
646          return job;
647      }
648  
649      /**
650 <     * Adaptor for Runnables. This implements RunnableFuture
651 <     * to be compliant with AbstractExecutorService constraints
650 >     * Submits a ForkJoinTask for execution.
651 >     *
652 >     * @param task the task to submit
653 >     * @return the task
654 >     * @throws RejectedExecutionException if the task cannot be
655 >     *         scheduled for execution
656 >     * @throws NullPointerException if the task is null
657       */
658 <    static final class AdaptedRunnable<T> extends ForkJoinTask<T>
659 <        implements RunnableFuture<T> {
660 <        final Runnable runnable;
573 <        final T resultOnCompletion;
574 <        T result;
575 <        AdaptedRunnable(Runnable runnable, T result) {
576 <            if (runnable == null) throw new NullPointerException();
577 <            this.runnable = runnable;
578 <            this.resultOnCompletion = result;
579 <        }
580 <        public T getRawResult() { return result; }
581 <        public void setRawResult(T v) { result = v; }
582 <        public boolean exec() {
583 <            runnable.run();
584 <            result = resultOnCompletion;
585 <            return true;
586 <        }
587 <        public void run() { invoke(); }
658 >    public <T> ForkJoinTask<T> submit(ForkJoinTask<T> task) {
659 >        doSubmit(task);
660 >        return task;
661      }
662  
590    /**
591     * Adaptor for Callables
592     */
593    static final class AdaptedCallable<T> extends ForkJoinTask<T>
594        implements RunnableFuture<T> {
595        final Callable<T> callable;
596        T result;
597        AdaptedCallable(Callable<T> callable) {
598            if (callable == null) throw new NullPointerException();
599            this.callable = callable;
600        }
601        public T getRawResult() { return result; }
602        public void setRawResult(T v) { result = v; }
603        public boolean exec() {
604            try {
605                result = callable.call();
606                return true;
607            } catch (Error err) {
608                throw err;
609            } catch (RuntimeException rex) {
610                throw rex;
611            } catch (Exception ex) {
612                throw new RuntimeException(ex);
613            }
614        }
615        public void run() { invoke(); }
616    }
663  
664      public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) {
665 <        ArrayList<ForkJoinTask<T>> ts =
665 >        ArrayList<ForkJoinTask<T>> forkJoinTasks =
666              new ArrayList<ForkJoinTask<T>>(tasks.size());
667 <        for (Callable<T> c : tasks)
668 <            ts.add(new AdaptedCallable<T>(c));
669 <        invoke(new InvokeAll<T>(ts));
670 <        return (List<Future<T>>)(List)ts;
667 >        for (Callable<T> task : tasks)
668 >            forkJoinTasks.add(ForkJoinTask.adapt(task));
669 >        invoke(new InvokeAll<T>(forkJoinTasks));
670 >
671 >        @SuppressWarnings({"unchecked", "rawtypes"})
672 >        List<Future<T>> futures = (List<Future<T>>) (List) forkJoinTasks;
673 >        return futures;
674      }
675  
676      static final class InvokeAll<T> extends RecursiveAction {
677          final ArrayList<ForkJoinTask<T>> tasks;
678          InvokeAll(ArrayList<ForkJoinTask<T>> tasks) { this.tasks = tasks; }
679          public void compute() {
680 <            try { invokeAll(tasks); } catch(Exception ignore) {}
680 >            try { invokeAll(tasks); }
681 >            catch (Exception ignore) {}
682          }
683 +        private static final long serialVersionUID = -7914297376763021607L;
684      }
685  
686      // Configuration and status settings and queries
687  
688      /**
689 <     * Returns the factory used for constructing new workers
689 >     * Returns the factory used for constructing new workers.
690       *
691       * @return the factory used for constructing new workers
692       */
# Line 646 | Line 697 | public class ForkJoinPool extends Abstra
697      /**
698       * Returns the handler for internal worker threads that terminate
699       * due to unrecoverable errors encountered while executing tasks.
700 <     * @return the handler, or null if none
700 >     *
701 >     * @return the handler, or {@code null} if none
702       */
703      public Thread.UncaughtExceptionHandler getUncaughtExceptionHandler() {
704          Thread.UncaughtExceptionHandler h;
# Line 667 | Line 719 | public class ForkJoinPool extends Abstra
719       * as handler.
720       *
721       * @param h the new handler
722 <     * @return the old handler, or null if none
722 >     * @return the old handler, or {@code null} if none
723       * @throws SecurityException if a security manager exists and
724       *         the caller is not permitted to modify threads
725       *         because it does not hold {@link
726 <     *         java.lang.RuntimePermission}<code>("modifyThread")</code>,
726 >     *         java.lang.RuntimePermission}{@code ("modifyThread")}
727       */
728      public Thread.UncaughtExceptionHandler
729          setUncaughtExceptionHandler(Thread.UncaughtExceptionHandler h) {
# Line 683 | Line 735 | public class ForkJoinPool extends Abstra
735              old = ueh;
736              ueh = h;
737              ForkJoinWorkerThread[] ws = workers;
738 <            for (int i = 0; i < ws.length; ++i) {
739 <                ForkJoinWorkerThread w = ws[i];
740 <                if (w != null)
741 <                    w.setUncaughtExceptionHandler(h);
738 >            if (ws != null) {
739 >                for (int i = 0; i < ws.length; ++i) {
740 >                    ForkJoinWorkerThread w = ws[i];
741 >                    if (w != null)
742 >                        w.setUncaughtExceptionHandler(h);
743 >                }
744              }
745          } finally {
746              lock.unlock();
# Line 696 | Line 750 | public class ForkJoinPool extends Abstra
750  
751  
752      /**
753 <     * Sets the target paralleism level of this pool.
753 >     * Sets the target parallelism level of this pool.
754 >     *
755       * @param parallelism the target parallelism
756       * @throws IllegalArgumentException if parallelism less than or
757 <     * equal to zero or greater than maximum size bounds.
757 >     * equal to zero or greater than maximum size bounds
758       * @throws SecurityException if a security manager exists and
759       *         the caller is not permitted to modify threads
760       *         because it does not hold {@link
761 <     *         java.lang.RuntimePermission}<code>("modifyThread")</code>,
761 >     *         java.lang.RuntimePermission}{@code ("modifyThread")}
762       */
763      public void setParallelism(int parallelism) {
764          checkPermission();
# Line 712 | Line 767 | public class ForkJoinPool extends Abstra
767          final ReentrantLock lock = this.workerLock;
768          lock.lock();
769          try {
770 <            if (!isTerminating()) {
770 >            if (isProcessingTasks()) {
771                  int p = this.parallelism;
772                  this.parallelism = parallelism;
773                  if (parallelism > p)
# Line 727 | Line 782 | public class ForkJoinPool extends Abstra
782      }
783  
784      /**
785 <     * Returns the targeted number of worker threads in this pool.
785 >     * Returns the targeted parallelism level of this pool.
786       *
787 <     * @return the targeted number of worker threads in this pool
787 >     * @return the targeted parallelism level of this pool
788       */
789      public int getParallelism() {
790          return parallelism;
# Line 738 | Line 793 | public class ForkJoinPool extends Abstra
793      /**
794       * Returns the number of worker threads that have started but not
795       * yet terminated.  This result returned by this method may differ
796 <     * from <code>getParallelism</code> when threads are created to
796 >     * from {@link #getParallelism} when threads are created to
797       * maintain parallelism when others are cooperatively blocked.
798       *
799       * @return the number of worker threads
# Line 749 | Line 804 | public class ForkJoinPool extends Abstra
804  
805      /**
806       * Returns the maximum number of threads allowed to exist in the
807 <     * pool, even if there are insufficient unblocked running threads.
807 >     * pool.  Unless set using {@link #setMaximumPoolSize}, the
808 >     * maximum is an implementation-defined value designed only to
809 >     * prevent runaway growth.
810 >     *
811       * @return the maximum
812       */
813      public int getMaximumPoolSize() {
# Line 758 | Line 816 | public class ForkJoinPool extends Abstra
816  
817      /**
818       * Sets the maximum number of threads allowed to exist in the
819 <     * pool, even if there are insufficient unblocked running threads.
820 <     * Setting this value has no effect on current pool size. It
821 <     * controls construction of new threads.
822 <     * @throws IllegalArgumentException if negative or greater then
823 <     * internal implementation limit.
819 >     * pool.  Setting this value has no effect on current pool
820 >     * size. It controls construction of new threads.
821 >     *
822 >     * @throws IllegalArgumentException if negative or greater than
823 >     * internal implementation limit
824       */
825      public void setMaximumPoolSize(int newMax) {
826          if (newMax < 0 || newMax > MAX_THREADS)
# Line 772 | Line 830 | public class ForkJoinPool extends Abstra
830  
831  
832      /**
833 <     * Returns true if this pool dynamically maintains its target
834 <     * parallelism level. If false, new threads are added only to
835 <     * avoid possible starvation.
836 <     * This setting is by default true;
837 <     * @return true if maintains parallelism
833 >     * Returns {@code true} if this pool dynamically maintains its
834 >     * target parallelism level. If false, new threads are added only
835 >     * to avoid possible starvation.  This setting is by default true.
836 >     *
837 >     * @return {@code true} if maintains parallelism
838       */
839      public boolean getMaintainsParallelism() {
840          return maintainsParallelism;
# Line 786 | Line 844 | public class ForkJoinPool extends Abstra
844       * Sets whether this pool dynamically maintains its target
845       * parallelism level. If false, new threads are added only to
846       * avoid possible starvation.
847 <     * @param enable true to maintains parallelism
847 >     *
848 >     * @param enable {@code true} to maintain parallelism
849       */
850      public void setMaintainsParallelism(boolean enable) {
851          maintainsParallelism = enable;
852      }
853  
854      /**
855 +     * Establishes local first-in-first-out scheduling mode for forked
856 +     * tasks that are never joined. This mode may be more appropriate
857 +     * than default locally stack-based mode in applications in which
858 +     * worker threads only process asynchronous tasks.  This method is
859 +     * designed to be invoked only when the pool is quiescent, and
860 +     * typically only before any tasks are submitted. The effects of
861 +     * invocations at other times may be unpredictable.
862 +     *
863 +     * @param async if {@code true}, use locally FIFO scheduling
864 +     * @return the previous mode
865 +     * @see #getAsyncMode
866 +     */
867 +    public boolean setAsyncMode(boolean async) {
868 +        boolean oldMode = locallyFifo;
869 +        locallyFifo = async;
870 +        ForkJoinWorkerThread[] ws = workers;
871 +        if (ws != null) {
872 +            for (int i = 0; i < ws.length; ++i) {
873 +                ForkJoinWorkerThread t = ws[i];
874 +                if (t != null)
875 +                    t.setAsyncMode(async);
876 +            }
877 +        }
878 +        return oldMode;
879 +    }
880 +
881 +    /**
882 +     * Returns {@code true} if this pool uses local first-in-first-out
883 +     * scheduling mode for forked tasks that are never joined.
884 +     *
885 +     * @return {@code true} if this pool uses async mode
886 +     * @see #setAsyncMode
887 +     */
888 +    public boolean getAsyncMode() {
889 +        return locallyFifo;
890 +    }
891 +
892 +    /**
893       * Returns an estimate of the number of worker threads that are
894       * not blocked waiting to join tasks or for other managed
895       * synchronization.
# Line 807 | Line 904 | public class ForkJoinPool extends Abstra
904       * Returns an estimate of the number of threads that are currently
905       * stealing or executing tasks. This method may overestimate the
906       * number of active threads.
907 <     * @return the number of active threads.
907 >     *
908 >     * @return the number of active threads
909       */
910      public int getActiveThreadCount() {
911          return activeCountOf(runControl);
# Line 817 | Line 915 | public class ForkJoinPool extends Abstra
915       * Returns an estimate of the number of threads that are currently
916       * idle waiting for tasks. This method may underestimate the
917       * number of idle threads.
918 <     * @return the number of idle threads.
918 >     *
919 >     * @return the number of idle threads
920       */
921      final int getIdleThreadCount() {
922          int c = runningCountOf(workerCounts) - activeCountOf(runControl);
923 <        return (c <= 0)? 0 : c;
923 >        return (c <= 0) ? 0 : c;
924      }
925  
926      /**
927 <     * Returns true if all worker threads are currently idle. An idle
928 <     * worker is one that cannot obtain a task to execute because none
929 <     * are available to steal from other threads, and there are no
930 <     * pending submissions to the pool. This method is conservative:
931 <     * It might not return true immediately upon idleness of all
932 <     * threads, but will eventually become true if threads remain
933 <     * inactive.
934 <     * @return true if all threads are currently idle
927 >     * Returns {@code true} if all worker threads are currently idle.
928 >     * An idle worker is one that cannot obtain a task to execute
929 >     * because none are available to steal from other threads, and
930 >     * there are no pending submissions to the pool. This method is
931 >     * conservative; it might not return {@code true} immediately upon
932 >     * idleness of all threads, but will eventually become true if
933 >     * threads remain inactive.
934 >     *
935 >     * @return {@code true} if all threads are currently idle
936       */
937      public boolean isQuiescent() {
938          return activeCountOf(runControl) == 0;
# Line 843 | Line 943 | public class ForkJoinPool extends Abstra
943       * one thread's work queue by another. The reported value
944       * underestimates the actual total number of steals when the pool
945       * is not quiescent. This value may be useful for monitoring and
946 <     * tuning fork/join programs: In general, steal counts should be
946 >     * tuning fork/join programs: in general, steal counts should be
947       * high enough to keep threads busy, but low enough to avoid
948       * overhead and contention across threads.
949 <     * @return the number of steals.
949 >     *
950 >     * @return the number of steals
951       */
952      public long getStealCount() {
953          return stealCount.get();
954      }
955  
956      /**
957 <     * Accumulate steal count from a worker. Call only
958 <     * when worker known to be idle.
957 >     * Accumulates steal count from a worker.
958 >     * Call only when worker known to be idle.
959       */
960      private void updateStealCount(ForkJoinWorkerThread w) {
961          int sc = w.getAndClearStealCount();
# Line 869 | Line 970 | public class ForkJoinPool extends Abstra
970       * an approximation, obtained by iterating across all threads in
971       * the pool. This method may be useful for tuning task
972       * granularities.
973 <     * @return the number of queued tasks.
973 >     *
974 >     * @return the number of queued tasks
975       */
976      public long getQueuedTaskCount() {
977          long count = 0;
978          ForkJoinWorkerThread[] ws = workers;
979 <        for (int i = 0; i < ws.length; ++i) {
980 <            ForkJoinWorkerThread t = ws[i];
981 <            if (t != null)
982 <                count += t.getQueueSize();
979 >        if (ws != null) {
980 >            for (int i = 0; i < ws.length; ++i) {
981 >                ForkJoinWorkerThread t = ws[i];
982 >                if (t != null)
983 >                    count += t.getQueueSize();
984 >            }
985          }
986          return count;
987      }
988  
989      /**
990 <     * Returns an estimate of the number tasks submitted to this pool
991 <     * that have not yet begun executing. This method takes time
990 >     * Returns an estimate of the number of tasks submitted to this
991 >     * pool that have not yet begun executing.  This method takes time
992       * proportional to the number of submissions.
993 <     * @return the number of queued submissions.
993 >     *
994 >     * @return the number of queued submissions
995       */
996      public int getQueuedSubmissionCount() {
997          return submissionQueue.size();
998      }
999  
1000      /**
1001 <     * Returns true if there are any tasks submitted to this pool
1002 <     * that have not yet begun executing.
1003 <     * @return <code>true</code> if there are any queued submissions.
1001 >     * Returns {@code true} if there are any tasks submitted to this
1002 >     * pool that have not yet begun executing.
1003 >     *
1004 >     * @return {@code true} if there are any queued submissions
1005       */
1006      public boolean hasQueuedSubmissions() {
1007          return !submissionQueue.isEmpty();
# Line 905 | Line 1011 | public class ForkJoinPool extends Abstra
1011       * Removes and returns the next unexecuted submission if one is
1012       * available.  This method may be useful in extensions to this
1013       * class that re-assign work in systems with multiple pools.
1014 <     * @return the next submission, or null if none
1014 >     *
1015 >     * @return the next submission, or {@code null} if none
1016       */
1017      protected ForkJoinTask<?> pollSubmission() {
1018          return submissionQueue.poll();
1019      }
1020  
1021      /**
1022 +     * Removes all available unexecuted submitted and forked tasks
1023 +     * from scheduling queues and adds them to the given collection,
1024 +     * without altering their execution status. These may include
1025 +     * artificially generated or wrapped tasks. This method is
1026 +     * designed to be invoked only when the pool is known to be
1027 +     * quiescent. Invocations at other times may not remove all
1028 +     * tasks. A failure encountered while attempting to add elements
1029 +     * to collection {@code c} may result in elements being in
1030 +     * neither, either or both collections when the associated
1031 +     * exception is thrown.  The behavior of this operation is
1032 +     * undefined if the specified collection is modified while the
1033 +     * operation is in progress.
1034 +     *
1035 +     * @param c the collection to transfer elements into
1036 +     * @return the number of elements transferred
1037 +     */
1038 +    protected int drainTasksTo(Collection<? super ForkJoinTask<?>> c) {
1039 +        int n = submissionQueue.drainTo(c);
1040 +        ForkJoinWorkerThread[] ws = workers;
1041 +        if (ws != null) {
1042 +            for (int i = 0; i < ws.length; ++i) {
1043 +                ForkJoinWorkerThread w = ws[i];
1044 +                if (w != null)
1045 +                    n += w.drainTasksTo(c);
1046 +            }
1047 +        }
1048 +        return n;
1049 +    }
1050 +
1051 +    /**
1052       * Returns a string identifying this pool, as well as its state,
1053       * including indications of run state, parallelism level, and
1054       * worker and task counts.
# Line 955 | Line 1092 | public class ForkJoinPool extends Abstra
1092       * Invocation has no additional effect if already shut down.
1093       * Tasks that are in the process of being submitted concurrently
1094       * during the course of this method may or may not be rejected.
1095 +     *
1096       * @throws SecurityException if a security manager exists and
1097       *         the caller is not permitted to modify threads
1098       *         because it does not hold {@link
1099 <     *         java.lang.RuntimePermission}<code>("modifyThread")</code>,
1099 >     *         java.lang.RuntimePermission}{@code ("modifyThread")}
1100       */
1101      public void shutdown() {
1102          checkPermission();
1103          transitionRunStateTo(SHUTDOWN);
1104 <        if (canTerminateOnShutdown(runControl))
1104 >        if (canTerminateOnShutdown(runControl)) {
1105 >            if (workers == null) { // shutting down before workers created
1106 >                final ReentrantLock lock = this.workerLock;
1107 >                lock.lock();
1108 >                try {
1109 >                    if (workers == null) {
1110 >                        terminate();
1111 >                        transitionRunStateTo(TERMINATED);
1112 >                        termination.signalAll();
1113 >                    }
1114 >                } finally {
1115 >                    lock.unlock();
1116 >                }
1117 >            }
1118              terminateOnShutdown();
1119 +        }
1120      }
1121  
1122      /**
1123 <     * Attempts to stop all actively executing tasks, and cancels all
1124 <     * waiting tasks.  Tasks that are in the process of being
1125 <     * submitted or executed concurrently during the course of this
1126 <     * method may or may not be rejected. Unlike some other executors,
1127 <     * this method cancels rather than collects non-executed tasks,
1128 <     * so always returns an empty list.
1123 >     * Attempts to cancel and/or stop all tasks, and reject all
1124 >     * subsequently submitted tasks.  Tasks that are in the process of
1125 >     * being submitted or executed concurrently during the course of
1126 >     * this method may or may not be rejected. This method cancels
1127 >     * both existing and unexecuted tasks, in order to permit
1128 >     * termination in the presence of task dependencies. So the method
1129 >     * always returns an empty list (unlike the case for some other
1130 >     * Executors).
1131 >     *
1132       * @return an empty list
1133       * @throws SecurityException if a security manager exists and
1134       *         the caller is not permitted to modify threads
1135       *         because it does not hold {@link
1136 <     *         java.lang.RuntimePermission}<code>("modifyThread")</code>,
1136 >     *         java.lang.RuntimePermission}{@code ("modifyThread")}
1137       */
1138      public List<Runnable> shutdownNow() {
1139          checkPermission();
# Line 987 | Line 1142 | public class ForkJoinPool extends Abstra
1142      }
1143  
1144      /**
1145 <     * Returns <code>true</code> if all tasks have completed following shut down.
1145 >     * Returns {@code true} if all tasks have completed following shut down.
1146       *
1147 <     * @return <code>true</code> if all tasks have completed following shut down
1147 >     * @return {@code true} if all tasks have completed following shut down
1148       */
1149      public boolean isTerminated() {
1150          return runStateOf(runControl) == TERMINATED;
1151      }
1152  
1153      /**
1154 <     * Returns <code>true</code> if the process of termination has
1155 <     * commenced but possibly not yet completed.
1154 >     * Returns {@code true} if the process of termination has
1155 >     * commenced but not yet completed.  This method may be useful for
1156 >     * debugging. A return of {@code true} reported a sufficient
1157 >     * period after shutdown may indicate that submitted tasks have
1158 >     * ignored or suppressed interruption, causing this executor not
1159 >     * to properly terminate.
1160       *
1161 <     * @return <code>true</code> if terminating
1161 >     * @return {@code true} if terminating but not yet terminated
1162       */
1163      public boolean isTerminating() {
1164 <        return runStateOf(runControl) >= TERMINATING;
1164 >        return runStateOf(runControl) == TERMINATING;
1165      }
1166  
1167      /**
1168 <     * Returns <code>true</code> if this pool has been shut down.
1168 >     * Returns {@code true} if this pool has been shut down.
1169       *
1170 <     * @return <code>true</code> if this pool has been shut down
1170 >     * @return {@code true} if this pool has been shut down
1171       */
1172      public boolean isShutdown() {
1173          return runStateOf(runControl) >= SHUTDOWN;
1174      }
1175  
1176      /**
1177 +     * Returns true if pool is not terminating or terminated.
1178 +     * Used internally to suppress execution when terminating.
1179 +     */
1180 +    final boolean isProcessingTasks() {
1181 +        return runStateOf(runControl) < TERMINATING;
1182 +    }
1183 +
1184 +    /**
1185       * Blocks until all tasks have completed execution after a shutdown
1186       * request, or the timeout occurs, or the current thread is
1187       * interrupted, whichever happens first.
1188       *
1189       * @param timeout the maximum time to wait
1190       * @param unit the time unit of the timeout argument
1191 <     * @return <code>true</code> if this executor terminated and
1192 <     *         <code>false</code> if the timeout elapsed before termination
1191 >     * @return {@code true} if this executor terminated and
1192 >     *         {@code false} if the timeout elapsed before termination
1193       * @throws InterruptedException if interrupted while waiting
1194       */
1195      public boolean awaitTermination(long timeout, TimeUnit unit)
# Line 1046 | Line 1213 | public class ForkJoinPool extends Abstra
1213      // Shutdown and termination support
1214  
1215      /**
1216 <     * Callback from terminating worker. Null out the corresponding
1217 <     * workers slot, and if terminating, try to terminate, else try to
1218 <     * shrink workers array.
1216 >     * Callback from terminating worker. Nulls out the corresponding
1217 >     * workers slot, and if terminating, tries to terminate; else
1218 >     * tries to shrink workers array.
1219 >     *
1220       * @param w the worker
1221       */
1222      final void workerTerminated(ForkJoinWorkerThread w) {
# Line 1058 | Line 1226 | public class ForkJoinPool extends Abstra
1226          lock.lock();
1227          try {
1228              ForkJoinWorkerThread[] ws = workers;
1229 <            int idx = w.poolIndex;
1230 <            if (idx >= 0 && idx < ws.length && ws[idx] == w)
1231 <                ws[idx] = null;
1232 <            if (totalCountOf(workerCounts) == 0) {
1233 <                terminate(); // no-op if already terminating
1234 <                transitionRunStateTo(TERMINATED);
1235 <                termination.signalAll();
1236 <            }
1237 <            else if (!isTerminating()) {
1238 <                tryShrinkWorkerArray();
1239 <                tryResumeSpare(true); // allow replacement
1229 >            if (ws != null) {
1230 >                int idx = w.poolIndex;
1231 >                if (idx >= 0 && idx < ws.length && ws[idx] == w)
1232 >                    ws[idx] = null;
1233 >                if (totalCountOf(workerCounts) == 0) {
1234 >                    terminate(); // no-op if already terminating
1235 >                    transitionRunStateTo(TERMINATED);
1236 >                    termination.signalAll();
1237 >                }
1238 >                else if (isProcessingTasks()) {
1239 >                    tryShrinkWorkerArray();
1240 >                    tryResumeSpare(true); // allow replacement
1241 >                }
1242              }
1243          } finally {
1244              lock.unlock();
# Line 1077 | Line 1247 | public class ForkJoinPool extends Abstra
1247      }
1248  
1249      /**
1250 <     * Initiate termination.
1250 >     * Initiates termination.
1251       */
1252      private void terminate() {
1253          if (transitionRunStateTo(TERMINATING)) {
# Line 1092 | Line 1262 | public class ForkJoinPool extends Abstra
1262      }
1263  
1264      /**
1265 <     * Possibly terminate when on shutdown state
1265 >     * Possibly terminates when on shutdown state.
1266       */
1267      private void terminateOnShutdown() {
1268          if (!hasQueuedSubmissions() && canTerminateOnShutdown(runControl))
# Line 1100 | Line 1270 | public class ForkJoinPool extends Abstra
1270      }
1271  
1272      /**
1273 <     * Clear out and cancel submissions
1273 >     * Clears out and cancels submissions.
1274       */
1275      private void cancelQueuedSubmissions() {
1276          ForkJoinTask<?> task;
# Line 1109 | Line 1279 | public class ForkJoinPool extends Abstra
1279      }
1280  
1281      /**
1282 <     * Clean out worker queues.
1282 >     * Cleans out worker queues.
1283       */
1284      private void cancelQueuedWorkerTasks() {
1285          final ReentrantLock lock = this.workerLock;
1286          lock.lock();
1287          try {
1288              ForkJoinWorkerThread[] ws = workers;
1289 <            for (int i = 0; i < ws.length; ++i) {
1290 <                ForkJoinWorkerThread t = ws[i];
1291 <                if (t != null)
1292 <                    t.cancelTasks();
1289 >            if (ws != null) {
1290 >                for (int i = 0; i < ws.length; ++i) {
1291 >                    ForkJoinWorkerThread t = ws[i];
1292 >                    if (t != null)
1293 >                        t.cancelTasks();
1294 >                }
1295              }
1296          } finally {
1297              lock.unlock();
# Line 1127 | Line 1299 | public class ForkJoinPool extends Abstra
1299      }
1300  
1301      /**
1302 <     * Set each worker's status to terminating. Requires lock to avoid
1303 <     * conflicts with add/remove
1302 >     * Sets each worker's status to terminating. Requires lock to avoid
1303 >     * conflicts with add/remove.
1304       */
1305      private void stopAllWorkers() {
1306          final ReentrantLock lock = this.workerLock;
1307          lock.lock();
1308          try {
1309              ForkJoinWorkerThread[] ws = workers;
1310 <            for (int i = 0; i < ws.length; ++i) {
1311 <                ForkJoinWorkerThread t = ws[i];
1312 <                if (t != null)
1313 <                    t.shutdownNow();
1310 >            if (ws != null) {
1311 >                for (int i = 0; i < ws.length; ++i) {
1312 >                    ForkJoinWorkerThread t = ws[i];
1313 >                    if (t != null)
1314 >                        t.shutdownNow();
1315 >                }
1316              }
1317          } finally {
1318              lock.unlock();
# Line 1146 | Line 1320 | public class ForkJoinPool extends Abstra
1320      }
1321  
1322      /**
1323 <     * Interrupt all unterminated workers.  This is not required for
1323 >     * Interrupts all unterminated workers.  This is not required for
1324       * sake of internal control, but may help unstick user code during
1325       * shutdown.
1326       */
# Line 1155 | Line 1329 | public class ForkJoinPool extends Abstra
1329          lock.lock();
1330          try {
1331              ForkJoinWorkerThread[] ws = workers;
1332 <            for (int i = 0; i < ws.length; ++i) {
1333 <                ForkJoinWorkerThread t = ws[i];
1334 <                if (t != null && !t.isTerminated()) {
1335 <                    try {
1336 <                        t.interrupt();
1337 <                    } catch (SecurityException ignore) {
1332 >            if (ws != null) {
1333 >                for (int i = 0; i < ws.length; ++i) {
1334 >                    ForkJoinWorkerThread t = ws[i];
1335 >                    if (t != null && !t.isTerminated()) {
1336 >                        try {
1337 >                            t.interrupt();
1338 >                        } catch (SecurityException ignore) {
1339 >                        }
1340                      }
1341                  }
1342              }
# Line 1214 | Line 1390 | public class ForkJoinPool extends Abstra
1390          }
1391  
1392          /**
1393 <         * Wake up waiter, returning false if known to already
1393 >         * Wakes up waiter, returning false if known to already
1394           */
1395          boolean signal() {
1396              ForkJoinWorkerThread t = thread;
# Line 1226 | Line 1402 | public class ForkJoinPool extends Abstra
1402          }
1403  
1404          /**
1405 <         * Await release on sync
1405 >         * Awaits release on sync.
1406           */
1407          void awaitSyncRelease(ForkJoinPool p) {
1408              while (thread != null && !p.syncIsReleasable(this))
# Line 1234 | Line 1410 | public class ForkJoinPool extends Abstra
1410          }
1411  
1412          /**
1413 <         * Await resumption as spare
1413 >         * Awaits resumption as spare.
1414           */
1415          void awaitSpareRelease() {
1416              while (thread != null) {
# Line 1248 | Line 1424 | public class ForkJoinPool extends Abstra
1424       * Ensures that no thread is waiting for count to advance from the
1425       * current value of eventCount read on entry to this method, by
1426       * releasing waiting threads if necessary.
1427 +     *
1428       * @return the count
1429       */
1430      final long ensureSync() {
# Line 1269 | Line 1446 | public class ForkJoinPool extends Abstra
1446       */
1447      private void signalIdleWorkers() {
1448          long c;
1449 <        do;while (!casEventCount(c = eventCount, c+1));
1449 >        do {} while (!casEventCount(c = eventCount, c+1));
1450          ensureSync();
1451      }
1452  
1453      /**
1454 <     * Signal threads waiting to poll a task. Because method sync
1454 >     * Signals threads waiting to poll a task. Because method sync
1455       * rechecks availability, it is OK to only proceed if queue
1456       * appears to be non-empty, and OK to skip under contention to
1457       * increment count (since some other thread succeeded).
# Line 1293 | Line 1470 | public class ForkJoinPool extends Abstra
1470       * Waits until event count advances from last value held by
1471       * caller, or if excess threads, caller is resumed as spare, or
1472       * caller or pool is terminating. Updates caller's event on exit.
1473 +     *
1474       * @param w the calling worker thread
1475       */
1476      final void sync(ForkJoinWorkerThread w) {
1477          updateStealCount(w); // Transfer w's count while it is idle
1478  
1479 <        while (!w.isShutdown() && !isTerminating() && !suspendIfSpare(w)) {
1479 >        while (!w.isShutdown() && isProcessingTasks() && !suspendIfSpare(w)) {
1480              long prev = w.lastEventCount;
1481              WaitQueueNode node = null;
1482              WaitQueueNode h;
# Line 1320 | Line 1498 | public class ForkJoinPool extends Abstra
1498      }
1499  
1500      /**
1501 <     * Returns true if worker waiting on sync can proceed:
1501 >     * Returns {@code true} if worker waiting on sync can proceed:
1502       *  - on signal (thread == null)
1503       *  - on event count advance (winning race to notify vs signaller)
1504 <     *  - on Interrupt
1504 >     *  - on interrupt
1505       *  - if the first queued node, we find work available
1506       * If node was not signalled and event count not advanced on exit,
1507       * then we also help advance event count.
1508 <     * @return true if node can be released
1508 >     *
1509 >     * @return {@code true} if node can be released
1510       */
1511      final boolean syncIsReleasable(WaitQueueNode node) {
1512          long prev = node.count;
# Line 1346 | Line 1525 | public class ForkJoinPool extends Abstra
1525      }
1526  
1527      /**
1528 <     * Returns true if a new sync event occurred since last call to
1529 <     * sync or this method, if so, updating caller's count.
1528 >     * Returns {@code true} if a new sync event occurred since last
1529 >     * call to sync or this method, if so, updating caller's count.
1530       */
1531      final boolean hasNewSyncEvent(ForkJoinWorkerThread w) {
1532          long lc = w.lastEventCount;
# Line 1361 | Line 1540 | public class ForkJoinPool extends Abstra
1540      //  Parallelism maintenance
1541  
1542      /**
1543 <     * Decrement running count; if too low, add spare.
1543 >     * Decrements running count; if too low, adds spare.
1544       *
1545       * Conceptually, all we need to do here is add or resume a
1546       * spare thread when one is about to block (and remove or
1547       * suspend it later when unblocked -- see suspendIfSpare).
1548       * However, implementing this idea requires coping with
1549 <     * several problems: We have imperfect information about the
1549 >     * several problems: we have imperfect information about the
1550       * states of threads. Some count updates can and usually do
1551       * lag run state changes, despite arrangements to keep them
1552       * accurate (for example, when possible, updating counts
# Line 1381 | Line 1560 | public class ForkJoinPool extends Abstra
1560       * only be suspended or removed when they are idle, not
1561       * immediately when they aren't needed. So adding threads will
1562       * raise parallelism level for longer than necessary.  Also,
1563 <     * FJ applications often enounter highly transient peaks when
1563 >     * FJ applications often encounter highly transient peaks when
1564       * many threads are blocked joining, but for less time than it
1565       * takes to create or resume spares.
1566       *
# Line 1390 | Line 1569 | public class ForkJoinPool extends Abstra
1569       * target counts, else create only to avoid starvation
1570       * @return true if joinMe known to be done
1571       */
1572 <    final boolean preJoin(ForkJoinTask<?> joinMe, boolean maintainParallelism) {
1572 >    final boolean preJoin(ForkJoinTask<?> joinMe,
1573 >                          boolean maintainParallelism) {
1574          maintainParallelism &= maintainsParallelism; // overrride
1575          boolean dec = false;  // true when running count decremented
1576          while (spareStack == null || !tryResumeSpare(dec)) {
1577              int counts = workerCounts;
1578 <            if (dec || (dec = casWorkerCounts(counts, --counts))) { // CAS cheat
1578 >            if (dec || (dec = casWorkerCounts(counts, --counts))) {
1579 >                // CAS cheat
1580                  if (!needSpare(counts, maintainParallelism))
1581                      break;
1582                  if (joinMe.status < 0)
# Line 1410 | Line 1591 | public class ForkJoinPool extends Abstra
1591      /**
1592       * Same idea as preJoin
1593       */
1594 <    final boolean preBlock(ManagedBlocker blocker, boolean maintainParallelism){
1594 >    final boolean preBlock(ManagedBlocker blocker,
1595 >                           boolean maintainParallelism) {
1596          maintainParallelism &= maintainsParallelism;
1597          boolean dec = false;
1598          while (spareStack == null || !tryResumeSpare(dec)) {
# Line 1428 | Line 1610 | public class ForkJoinPool extends Abstra
1610      }
1611  
1612      /**
1613 <     * Returns true if a spare thread appears to be needed.  If
1614 <     * maintaining parallelism, returns true when the deficit in
1613 >     * Returns {@code true} if a spare thread appears to be needed.
1614 >     * If maintaining parallelism, returns true when the deficit in
1615       * running threads is more than the surplus of total threads, and
1616       * there is apparently some work to do.  This self-limiting rule
1617       * means that the more threads that have already been added, the
1618       * less parallelism we will tolerate before adding another.
1619 +     *
1620       * @param counts current worker counts
1621       * @param maintainParallelism try to maintain parallelism
1622       */
# Line 1451 | Line 1634 | public class ForkJoinPool extends Abstra
1634      }
1635  
1636      /**
1637 <     * Add a spare worker if lock available and no more than the
1638 <     * expected numbers of threads exist
1637 >     * Adds a spare worker if lock available and no more than the
1638 >     * expected numbers of threads exist.
1639 >     *
1640       * @return true if successful
1641       */
1642      private boolean tryAddSpare(int expectedCounts) {
# Line 1485 | Line 1669 | public class ForkJoinPool extends Abstra
1669      }
1670  
1671      /**
1672 <     * Add the kth spare worker. On entry, pool coounts are already
1672 >     * Adds the kth spare worker. On entry, pool counts are already
1673       * adjusted to reflect addition.
1674       */
1675      private void createAndStartSpare(int k) {
# Line 1497 | Line 1681 | public class ForkJoinPool extends Abstra
1681              for (k = 0; k < len && ws[k] != null; ++k)
1682                  ;
1683          }
1684 <        if (k < len && !isTerminating() && (w = createWorker(k)) != null) {
1684 >        if (k < len && isProcessingTasks() && (w = createWorker(k)) != null) {
1685              ws[k] = w;
1686              w.start();
1687          }
# Line 1507 | Line 1691 | public class ForkJoinPool extends Abstra
1691      }
1692  
1693      /**
1694 <     * Suspend calling thread w if there are excess threads.  Called
1695 <     * only from sync.  Spares are enqueued in a Treiber stack
1696 <     * using the same WaitQueueNodes as barriers.  They are resumed
1697 <     * mainly in preJoin, but are also woken on pool events that
1698 <     * require all threads to check run state.
1694 >     * Suspends calling thread w if there are excess threads.  Called
1695 >     * only from sync.  Spares are enqueued in a Treiber stack using
1696 >     * the same WaitQueueNodes as barriers.  They are resumed mainly
1697 >     * in preJoin, but are also woken on pool events that require all
1698 >     * threads to check run state.
1699 >     *
1700       * @param w the caller
1701       */
1702      private boolean suspendIfSpare(ForkJoinWorkerThread w) {
# Line 1522 | Line 1707 | public class ForkJoinPool extends Abstra
1707                  node = new WaitQueueNode(0, w);
1708              if (casWorkerCounts(s, s-1)) { // representation-dependent
1709                  // push onto stack
1710 <                do;while (!casSpareStack(node.next = spareStack, node));
1710 >                do {} while (!casSpareStack(node.next = spareStack, node));
1711                  // block until released by resumeSpare
1712                  node.awaitSpareRelease();
1713                  return true;
# Line 1532 | Line 1717 | public class ForkJoinPool extends Abstra
1717      }
1718  
1719      /**
1720 <     * Try to pop and resume a spare thread.
1720 >     * Tries to pop and resume a spare thread.
1721 >     *
1722       * @param updateCount if true, increment running count on success
1723       * @return true if successful
1724       */
# Line 1550 | Line 1736 | public class ForkJoinPool extends Abstra
1736      }
1737  
1738      /**
1739 <     * Pop and resume all spare threads. Same idea as ensureSync.
1739 >     * Pops and resumes all spare threads. Same idea as ensureSync.
1740 >     *
1741       * @return true if any spares released
1742       */
1743      private boolean resumeAllSpares() {
# Line 1568 | Line 1755 | public class ForkJoinPool extends Abstra
1755      }
1756  
1757      /**
1758 <     * Pop and shutdown excessive spare threads. Call only while
1758 >     * Pops and shuts down excessive spare threads. Call only while
1759       * holding lock. This is not guaranteed to eliminate all excess
1760       * threads, only those suspended as spares, which are the ones
1761       * unlikely to be needed in the future.
# Line 1592 | Line 1779 | public class ForkJoinPool extends Abstra
1779  
1780      /**
1781       * Interface for extending managed parallelism for tasks running
1782 <     * in ForkJoinPools. A ManagedBlocker provides two methods.
1783 <     * Method <code>isReleasable</code> must return true if blocking is not
1784 <     * necessary. Method <code>block</code> blocks the current thread
1785 <     * if necessary (perhaps internally invoking isReleasable before
1786 <     * actually blocking.).
1782 >     * in {@link ForkJoinPool}s.
1783 >     *
1784 >     * <p>A {@code ManagedBlocker} provides two methods.
1785 >     * Method {@code isReleasable} must return {@code true} if
1786 >     * blocking is not necessary. Method {@code block} blocks the
1787 >     * current thread if necessary (perhaps internally invoking
1788 >     * {@code isReleasable} before actually blocking).
1789 >     *
1790       * <p>For example, here is a ManagedBlocker based on a
1791       * ReentrantLock:
1792 <     * <pre>
1793 <     *   class ManagedLocker implements ManagedBlocker {
1794 <     *     final ReentrantLock lock;
1795 <     *     boolean hasLock = false;
1796 <     *     ManagedLocker(ReentrantLock lock) { this.lock = lock; }
1797 <     *     public boolean block() {
1798 <     *        if (!hasLock)
1799 <     *           lock.lock();
1800 <     *        return true;
1611 <     *     }
1612 <     *     public boolean isReleasable() {
1613 <     *        return hasLock || (hasLock = lock.tryLock());
1614 <     *     }
1792 >     *  <pre> {@code
1793 >     * class ManagedLocker implements ManagedBlocker {
1794 >     *   final ReentrantLock lock;
1795 >     *   boolean hasLock = false;
1796 >     *   ManagedLocker(ReentrantLock lock) { this.lock = lock; }
1797 >     *   public boolean block() {
1798 >     *     if (!hasLock)
1799 >     *       lock.lock();
1800 >     *     return true;
1801       *   }
1802 <     * </pre>
1802 >     *   public boolean isReleasable() {
1803 >     *     return hasLock || (hasLock = lock.tryLock());
1804 >     *   }
1805 >     * }}</pre>
1806       */
1807      public static interface ManagedBlocker {
1808          /**
1809           * Possibly blocks the current thread, for example waiting for
1810           * a lock or condition.
1811 <         * @return true if no additional blocking is necessary (i.e.,
1812 <         * if isReleasable would return true).
1811 >         *
1812 >         * @return {@code true} if no additional blocking is necessary
1813 >         * (i.e., if isReleasable would return true)
1814           * @throws InterruptedException if interrupted while waiting
1815 <         * (the method is not required to do so, but is allowe to).
1815 >         * (the method is not required to do so, but is allowed to)
1816           */
1817          boolean block() throws InterruptedException;
1818  
1819          /**
1820 <         * Returns true if blocking is unnecessary.
1820 >         * Returns {@code true} if blocking is unnecessary.
1821           */
1822          boolean isReleasable();
1823      }
1824  
1825      /**
1826       * Blocks in accord with the given blocker.  If the current thread
1827 <     * is a ForkJoinWorkerThread, this method possibly arranges for a
1828 <     * spare thread to be activated if necessary to ensure parallelism
1829 <     * while the current thread is blocked.  If
1830 <     * <code>maintainParallelism</code> is true and the pool supports
1831 <     * it ({@link #getMaintainsParallelism}), this method attempts to
1832 <     * maintain the pool's nominal parallelism. Otherwise if activates
1833 <     * a thread only if necessary to avoid complete starvation. This
1834 <     * option may be preferable when blockages use timeouts, or are
1835 <     * almost always brief.
1836 <     *
1837 <     * <p> If the caller is not a ForkJoinTask, this method is behaviorally
1838 <     * equivalent to
1839 <     * <pre>
1840 <     *   while (!blocker.isReleasable())
1841 <     *      if (blocker.block())
1842 <     *         return;
1843 <     * </pre>
1844 <     * If the caller is a ForkJoinTask, then the pool may first
1845 <     * be expanded to ensure parallelism, and later adjusted.
1827 >     * is a {@link ForkJoinWorkerThread}, this method possibly
1828 >     * arranges for a spare thread to be activated if necessary to
1829 >     * ensure parallelism while the current thread is blocked.
1830 >     *
1831 >     * <p>If {@code maintainParallelism} is {@code true} and the pool
1832 >     * supports it ({@link #getMaintainsParallelism}), this method
1833 >     * attempts to maintain the pool's nominal parallelism. Otherwise
1834 >     * it activates a thread only if necessary to avoid complete
1835 >     * starvation. This option may be preferable when blockages use
1836 >     * timeouts, or are almost always brief.
1837 >     *
1838 >     * <p>If the caller is not a {@link ForkJoinTask}, this method is
1839 >     * behaviorally equivalent to
1840 >     *  <pre> {@code
1841 >     * while (!blocker.isReleasable())
1842 >     *   if (blocker.block())
1843 >     *     return;
1844 >     * }</pre>
1845 >     *
1846 >     * If the caller is a {@code ForkJoinTask}, then the pool may
1847 >     * first be expanded to ensure parallelism, and later adjusted.
1848       *
1849       * @param blocker the blocker
1850 <     * @param maintainParallelism if true and supported by this pool,
1851 <     * attempt to maintain the pool's nominal parallelism; otherwise
1852 <     * activate a thread only if necessary to avoid complete
1853 <     * starvation.
1854 <     * @throws InterruptedException if blocker.block did so.
1850 >     * @param maintainParallelism if {@code true} and supported by
1851 >     * this pool, attempt to maintain the pool's nominal parallelism;
1852 >     * otherwise activate a thread only if necessary to avoid
1853 >     * complete starvation.
1854 >     * @throws InterruptedException if blocker.block did so
1855       */
1856      public static void managedBlock(ManagedBlocker blocker,
1857                                      boolean maintainParallelism)
1858          throws InterruptedException {
1859          Thread t = Thread.currentThread();
1860 <        ForkJoinPool pool = (t instanceof ForkJoinWorkerThread?
1861 <                             ((ForkJoinWorkerThread)t).pool : null);
1860 >        ForkJoinPool pool = ((t instanceof ForkJoinWorkerThread) ?
1861 >                             ((ForkJoinWorkerThread) t).pool : null);
1862          if (!blocker.isReleasable()) {
1863              try {
1864                  if (pool == null ||
# Line 1681 | Line 1873 | public class ForkJoinPool extends Abstra
1873  
1874      private static void awaitBlocker(ManagedBlocker blocker)
1875          throws InterruptedException {
1876 <        do;while (!blocker.isReleasable() && !blocker.block());
1876 >        do {} while (!blocker.isReleasable() && !blocker.block());
1877      }
1878  
1879 <    // AbstractExecutorService overrides
1879 >    // AbstractExecutorService overrides.  These rely on undocumented
1880 >    // fact that ForkJoinTask.adapt returns ForkJoinTasks that also
1881 >    // implement RunnableFuture.
1882  
1883      protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
1884 <        return new AdaptedRunnable(runnable, value);
1884 >        return (RunnableFuture<T>) ForkJoinTask.adapt(runnable, value);
1885      }
1886  
1887      protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
1888 <        return new AdaptedCallable(callable);
1695 <    }
1696 <
1697 <
1698 <    // Temporary Unsafe mechanics for preliminary release
1699 <    private static Unsafe getUnsafe() throws Throwable {
1700 <        try {
1701 <            return Unsafe.getUnsafe();
1702 <        } catch (SecurityException se) {
1703 <            try {
1704 <                return java.security.AccessController.doPrivileged
1705 <                    (new java.security.PrivilegedExceptionAction<Unsafe>() {
1706 <                        public Unsafe run() throws Exception {
1707 <                            return getUnsafePrivileged();
1708 <                        }});
1709 <            } catch (java.security.PrivilegedActionException e) {
1710 <                throw e.getCause();
1711 <            }
1712 <        }
1888 >        return (RunnableFuture<T>) ForkJoinTask.adapt(callable);
1889      }
1890  
1891 <    private static Unsafe getUnsafePrivileged()
1716 <            throws NoSuchFieldException, IllegalAccessException {
1717 <        Field f = Unsafe.class.getDeclaredField("theUnsafe");
1718 <        f.setAccessible(true);
1719 <        return (Unsafe) f.get(null);
1720 <    }
1721 <
1722 <    private static long fieldOffset(String fieldName)
1723 <            throws NoSuchFieldException {
1724 <        return _unsafe.objectFieldOffset
1725 <            (ForkJoinPool.class.getDeclaredField(fieldName));
1726 <    }
1891 >    // Unsafe mechanics
1892  
1893 <    static final Unsafe _unsafe;
1894 <    static final long eventCountOffset;
1895 <    static final long workerCountsOffset;
1896 <    static final long runControlOffset;
1897 <    static final long syncStackOffset;
1898 <    static final long spareStackOffset;
1899 <
1900 <    static {
1901 <        try {
1902 <            _unsafe = getUnsafe();
1903 <            eventCountOffset = fieldOffset("eventCount");
1739 <            workerCountsOffset = fieldOffset("workerCounts");
1740 <            runControlOffset = fieldOffset("runControl");
1741 <            syncStackOffset = fieldOffset("syncStack");
1742 <            spareStackOffset = fieldOffset("spareStack");
1743 <        } catch (Throwable e) {
1744 <            throw new RuntimeException("Could not initialize intrinsics", e);
1745 <        }
1746 <    }
1893 >    private static final sun.misc.Unsafe UNSAFE = getUnsafe();
1894 >    private static final long eventCountOffset =
1895 >        objectFieldOffset("eventCount", ForkJoinPool.class);
1896 >    private static final long workerCountsOffset =
1897 >        objectFieldOffset("workerCounts", ForkJoinPool.class);
1898 >    private static final long runControlOffset =
1899 >        objectFieldOffset("runControl", ForkJoinPool.class);
1900 >    private static final long syncStackOffset =
1901 >        objectFieldOffset("syncStack",ForkJoinPool.class);
1902 >    private static final long spareStackOffset =
1903 >        objectFieldOffset("spareStack", ForkJoinPool.class);
1904  
1905      private boolean casEventCount(long cmp, long val) {
1906 <        return _unsafe.compareAndSwapLong(this, eventCountOffset, cmp, val);
1906 >        return UNSAFE.compareAndSwapLong(this, eventCountOffset, cmp, val);
1907      }
1908      private boolean casWorkerCounts(int cmp, int val) {
1909 <        return _unsafe.compareAndSwapInt(this, workerCountsOffset, cmp, val);
1909 >        return UNSAFE.compareAndSwapInt(this, workerCountsOffset, cmp, val);
1910      }
1911      private boolean casRunControl(int cmp, int val) {
1912 <        return _unsafe.compareAndSwapInt(this, runControlOffset, cmp, val);
1912 >        return UNSAFE.compareAndSwapInt(this, runControlOffset, cmp, val);
1913      }
1914      private boolean casSpareStack(WaitQueueNode cmp, WaitQueueNode val) {
1915 <        return _unsafe.compareAndSwapObject(this, spareStackOffset, cmp, val);
1915 >        return UNSAFE.compareAndSwapObject(this, spareStackOffset, cmp, val);
1916      }
1917      private boolean casBarrierStack(WaitQueueNode cmp, WaitQueueNode val) {
1918 <        return _unsafe.compareAndSwapObject(this, syncStackOffset, cmp, val);
1918 >        return UNSAFE.compareAndSwapObject(this, syncStackOffset, cmp, val);
1919 >    }
1920 >
1921 >    private static long objectFieldOffset(String field, Class<?> klazz) {
1922 >        try {
1923 >            return UNSAFE.objectFieldOffset(klazz.getDeclaredField(field));
1924 >        } catch (NoSuchFieldException e) {
1925 >            // Convert Exception to corresponding Error
1926 >            NoSuchFieldError error = new NoSuchFieldError(field);
1927 >            error.initCause(e);
1928 >            throw error;
1929 >        }
1930 >    }
1931 >
1932 >    /**
1933 >     * Returns a sun.misc.Unsafe.  Suitable for use in a 3rd party package.
1934 >     * Replace with a simple call to Unsafe.getUnsafe when integrating
1935 >     * into a jdk.
1936 >     *
1937 >     * @return a sun.misc.Unsafe
1938 >     */
1939 >    private static sun.misc.Unsafe getUnsafe() {
1940 >        try {
1941 >            return sun.misc.Unsafe.getUnsafe();
1942 >        } catch (SecurityException se) {
1943 >            try {
1944 >                return java.security.AccessController.doPrivileged
1945 >                    (new java.security
1946 >                     .PrivilegedExceptionAction<sun.misc.Unsafe>() {
1947 >                        public sun.misc.Unsafe run() throws Exception {
1948 >                            java.lang.reflect.Field f = sun.misc
1949 >                                .Unsafe.class.getDeclaredField("theUnsafe");
1950 >                            f.setAccessible(true);
1951 >                            return (sun.misc.Unsafe) f.get(null);
1952 >                        }});
1953 >            } catch (java.security.PrivilegedActionException e) {
1954 >                throw new RuntimeException("Could not initialize intrinsics",
1955 >                                           e.getCause());
1956 >            }
1957 >        }
1958      }
1959   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines