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.64 by dl, Tue Aug 17 18:30:32 2010 UTC vs.
Revision 1.83 by dl, Sun Oct 24 19:37:26 2010 UTC

# Line 6 | Line 6
6  
7   package jsr166y;
8  
9 import java.util.concurrent.*;
10
9   import java.util.ArrayList;
10   import java.util.Arrays;
11   import java.util.Collection;
12   import java.util.Collections;
13   import java.util.List;
14 + import java.util.concurrent.AbstractExecutorService;
15 + import java.util.concurrent.Callable;
16 + import java.util.concurrent.ExecutorService;
17 + import java.util.concurrent.Future;
18 + import java.util.concurrent.RejectedExecutionException;
19 + import java.util.concurrent.RunnableFuture;
20 + import java.util.concurrent.TimeUnit;
21 + import java.util.concurrent.TimeoutException;
22 + import java.util.concurrent.atomic.AtomicInteger;
23   import java.util.concurrent.locks.LockSupport;
24   import java.util.concurrent.locks.ReentrantLock;
18 import java.util.concurrent.atomic.AtomicInteger;
19 import java.util.concurrent.CountDownLatch;
25  
26   /**
27   * An {@link ExecutorService} for running {@link ForkJoinTask}s.
# Line 69 | Line 74 | import java.util.concurrent.CountDownLat
74   *    <td ALIGN=CENTER> <b>Call from within fork/join computations</b></td>
75   *  </tr>
76   *  <tr>
77 < *    <td> <b>Arange async execution</td>
77 > *    <td> <b>Arrange async execution</td>
78   *    <td> {@link #execute(ForkJoinTask)}</td>
79   *    <td> {@link ForkJoinTask#fork}</td>
80   *  </tr>
# Line 140 | Line 145 | public class ForkJoinPool extends Abstra
145       * Beyond work-stealing support and essential bookkeeping, the
146       * main responsibility of this framework is to take actions when
147       * one worker is waiting to join a task stolen (or always held by)
148 <     * another.  Becauae we are multiplexing many tasks on to a pool
148 >     * another.  Because we are multiplexing many tasks on to a pool
149       * of workers, we can't just let them block (as in Thread.join).
150       * We also cannot just reassign the joiner's run-time stack with
151       * another and replace it later, which would be a form of
# Line 157 | Line 162 | public class ForkJoinPool extends Abstra
162       *      links to try to find such a task.
163       *
164       *   Compensating: Unless there are already enough live threads,
165 <     *      method helpMaintainParallelism() may create or or
165 >     *      method helpMaintainParallelism() may create or
166       *      re-activate a spare thread to compensate for blocked
167       *      joiners until they unblock.
168       *
169 <     * Because the determining existence of conservatively safe
170 <     * helping targets, the availability of already-created spares,
171 <     * and the apparent need to create new spares are all racy and
172 <     * require heuristic guidance, we rely on multiple retries of
173 <     * each. Further, because it is impossible to keep exactly the
174 <     * target (parallelism) number of threads running at any given
175 <     * time, we allow compensation during joins to fail, and enlist
176 <     * all other threads to help out whenever they are not otherwise
177 <     * occupied (i.e., mainly in method preStep).
169 >     * It is impossible to keep exactly the target (parallelism)
170 >     * number of threads running at any given time.  Determining
171 >     * existence of conservatively safe helping targets, the
172 >     * availability of already-created spares, and the apparent need
173 >     * to create new spares are all racy and require heuristic
174 >     * guidance, so we rely on multiple retries of each.  Compensation
175 >     * occurs in slow-motion. It is triggered only upon timeouts of
176 >     * Object.wait used for joins. This reduces poor decisions that
177 >     * would otherwise be made when threads are waiting for others
178 >     * that are stalled because of unrelated activities such as
179 >     * garbage collection.
180       *
181       * The ManagedBlocker extension API can't use helping so relies
182       * only on compensation in method awaitBlocker.
# Line 224 | Line 231 | public class ForkJoinPool extends Abstra
231       * ManagedBlocker), we may create or resume others to take their
232       * place until they unblock (see below). Implementing this
233       * requires counts of the number of "running" threads (i.e., those
234 <     * that are neither blocked nor artifically suspended) as well as
234 >     * that are neither blocked nor artificially suspended) as well as
235       * the total number.  These two values are packed into one field,
236       * "workerCounts" because we need accurate snapshots when deciding
237       * to create, resume or suspend.  Note however that the
238 <     * correspondance of these counts to reality is not guaranteed. In
238 >     * correspondence of these counts to reality is not guaranteed. In
239       * particular updates for unblocked threads may lag until they
240       * actually wake up.
241       *
# Line 271 | Line 278 | public class ForkJoinPool extends Abstra
278       * In addition to allowing simpler decisions about need for
279       * wakeup, the event count bits in eventWaiters serve the role of
280       * tags to avoid ABA errors in Treiber stacks. Upon any wakeup,
281 <     * released threads also try to release others (but give up upon
282 <     * contention to reduce useless flailing).  The net effect is a
283 <     * tree-like diffusion of signals, where released threads (and
284 <     * possibly others) help with unparks.  To further reduce
285 <     * contention effects a bit, failed CASes to increment field
279 <     * eventCount are tolerated without retries in signalWork.
281 >     * released threads also try to release at most two others.  The
282 >     * net effect is a tree-like diffusion of signals, where released
283 >     * threads (and possibly others) help with unparks.  To further
284 >     * reduce contention effects a bit, failed CASes to increment
285 >     * field eventCount are tolerated without retries in signalWork.
286       * Conceptually they are merged into the same event, which is OK
287       * when their only purpose is to enable workers to scan for work.
288       *
289 <     * 5. Managing suspension of extra workers. When a worker is about
290 <     * to block waiting for a join (or via ManagedBlockers), we may
291 <     * create a new thread to maintain parallelism level, or at least
292 <     * avoid starvation. Usually, extra threads are needed for only
293 <     * very short periods, yet join dependencies are such that we
294 <     * sometimes need them in bursts. Rather than create new threads
295 <     * each time this happens, we suspend no-longer-needed extra ones
296 <     * as "spares". For most purposes, we don't distinguish "extra"
297 <     * spare threads from normal "core" threads: On each call to
298 <     * preStep (the only point at which we can do this) a worker
299 <     * checks to see if there are now too many running workers, and if
300 <     * so, suspends itself.  Method helpMaintainParallelism looks for
301 <     * suspended threads to resume before considering creating a new
302 <     * replacement. The spares themselves are encoded on another
303 <     * variant of a Treiber Stack, headed at field "spareWaiters".
304 <     * Note that the use of spares is intrinsically racy.  One thread
305 <     * may become a spare at about the same time as another is
306 <     * needlessly being created. We counteract this and related slop
307 <     * in part by requiring resumed spares to immediately recheck (in
308 <     * preStep) to see whether they they should re-suspend.
309 <     *
310 <     * 6. Killing off unneeded workers. The Spare and Event queues use
311 <     * similar mechanisms to shed unused workers: The oldest (first)
312 <     * waiter uses a timed rather than hard wait. When this wait times
313 <     * out without a normal wakeup, it tries to shutdown any one (for
314 <     * convenience the newest) other waiter via tryShutdownSpare or
315 <     * tryShutdownWaiter, respectively. The wakeup rates for spares
316 <     * are much shorter than for waiters. Together, they will
317 <     * eventually reduce the number of worker threads to a minimum of
318 <     * one after a long enough period without use.
289 >     * 5. Managing suspension of extra workers. When a worker notices
290 >     * (usually upon timeout of a wait()) that there are too few
291 >     * running threads, we may create a new thread to maintain
292 >     * parallelism level, or at least avoid starvation. Usually, extra
293 >     * threads are needed for only very short periods, yet join
294 >     * dependencies are such that we sometimes need them in
295 >     * bursts. Rather than create new threads each time this happens,
296 >     * we suspend no-longer-needed extra ones as "spares". For most
297 >     * purposes, we don't distinguish "extra" spare threads from
298 >     * normal "core" threads: On each call to preStep (the only point
299 >     * at which we can do this) a worker checks to see if there are
300 >     * now too many running workers, and if so, suspends itself.
301 >     * Method helpMaintainParallelism looks for suspended threads to
302 >     * resume before considering creating a new replacement. The
303 >     * spares themselves are encoded on another variant of a Treiber
304 >     * Stack, headed at field "spareWaiters".  Note that the use of
305 >     * spares is intrinsically racy.  One thread may become a spare at
306 >     * about the same time as another is needlessly being created. We
307 >     * counteract this and related slop in part by requiring resumed
308 >     * spares to immediately recheck (in preStep) to see whether they
309 >     * should re-suspend.
310 >     *
311 >     * 6. Killing off unneeded workers. A timeout mechanism is used to
312 >     * shed unused workers: The oldest (first) event queue waiter uses
313 >     * a timed rather than hard wait. When this wait times out without
314 >     * a normal wakeup, it tries to shutdown any one (for convenience
315 >     * the newest) other spare or event waiter via
316 >     * tryShutdownUnusedWorker. This eventually reduces the number of
317 >     * worker threads to a minimum of one after a long enough period
318 >     * without use.
319       *
320       * 7. Deciding when to create new workers. The main dynamic
321       * control in this class is deciding when to create extra threads
322       * in method helpMaintainParallelism. We would like to keep
323 <     * exactly #parallelism threads running, which is an impossble
323 >     * exactly #parallelism threads running, which is an impossible
324       * task. We always need to create one when the number of running
325       * threads would become zero and all workers are busy. Beyond
326 <     * this, we must rely on heuristics that work well in the the
327 <     * presence of transients phenomena such as GC stalls, dynamic
326 >     * this, we must rely on heuristics that work well in the
327 >     * presence of transient phenomena such as GC stalls, dynamic
328       * compilation, and wake-up lags. These transients are extremely
329       * common -- we are normally trying to fully saturate the CPUs on
330       * a machine, so almost any activity other than running tasks
331 <     * impedes accuracy. Our main defense is to allow some slack in
332 <     * creation thresholds, using rules that reflect the fact that the
333 <     * more threads we have running, the more likely that we are
334 <     * underestimating the number running threads. (We also include
335 <     * some heuristic use of Thread.yield when all workers appear to
336 <     * be busy, to improve likelihood of counts settling.) The rules
337 <     * also better cope with the fact that some of the methods in this
338 <     * class tend to never become compiled (but are interpreted), so
339 <     * some components of the entire set of controls might execute 100
334 <     * times faster than others. And similarly for cases where the
335 <     * apparent lack of work is just due to GC stalls and other
336 <     * transient system activity.
331 >     * impedes accuracy. Our main defense is to allow parallelism to
332 >     * lapse for a while during joins, and use a timeout to see if,
333 >     * after the resulting settling, there is still a need for
334 >     * additional workers.  This also better copes with the fact that
335 >     * some of the methods in this class tend to never become compiled
336 >     * (but are interpreted), so some components of the entire set of
337 >     * controls might execute 100 times faster than others. And
338 >     * similarly for cases where the apparent lack of work is just due
339 >     * to GC stalls and other transient system activity.
340       *
341       * Beware that there is a lot of representation-level coupling
342       * among classes ForkJoinPool, ForkJoinWorkerThread, and
# Line 348 | Line 351 | public class ForkJoinPool extends Abstra
351       * "while ((local = field) != 0)") which are usually the simplest
352       * way to ensure the required read orderings (which are sometimes
353       * critical). Also several occurrences of the unusual "do {}
354 <     * while(!cas...)" which is the simplest way to force an update of
354 >     * while (!cas...)" which is the simplest way to force an update of
355       * a CAS'ed variable. There are also other coding oddities that
356       * help some methods perform reasonably even when interpreted (not
357       * compiled), at the expense of some messy constructions that
# Line 420 | Line 423 | public class ForkJoinPool extends Abstra
423          new AtomicInteger();
424  
425      /**
426 +     * The time to block in a join (see awaitJoin) before checking if
427 +     * a new worker should be (re)started to maintain parallelism
428 +     * level. The value should be short enough to maintain global
429 +     * responsiveness and progress but long enough to avoid
430 +     * counterproductive firings during GC stalls or unrelated system
431 +     * activity, and to not bog down systems with continual re-firings
432 +     * on GCs or legitimately long waits.
433 +     */
434 +    private static final long JOIN_TIMEOUT_MILLIS = 250L; // 4 per second
435 +
436 +    /**
437       * The wakeup interval (in nanoseconds) for the oldest worker
438 <     * worker waiting for an event invokes tryShutdownWaiter to shrink
439 <     * the number of workers.  The exact value does not matter too
440 <     * much, but should be long enough to slowly release resources
441 <     * during long periods without use without disrupting normal use.
438 >     * waiting for an event to invoke tryShutdownUnusedWorker to
439 >     * shrink the number of workers.  The exact value does not matter
440 >     * too much. It must be short enough to release resources during
441 >     * sustained periods of idleness, but not so short that threads
442 >     * are continually re-created.
443       */
444      private static final long SHRINK_RATE_NANOS =
445 <        60L * 1000L * 1000L * 1000L; // one minute
445 >        30L * 1000L * 1000L * 1000L; // 2 per minute
446  
447      /**
448       * Absolute bound for parallelism level. Twice this number plus
# Line 474 | Line 489 | public class ForkJoinPool extends Abstra
489      private volatile long stealCount;
490  
491      /**
492 <     * Encoded record of top of treiber stack of threads waiting for
492 >     * Encoded record of top of Treiber stack of threads waiting for
493       * events. The top 32 bits contain the count being waited for. The
494       * bottom 16 bits contains one plus the pool index of waiting
495       * worker thread. (Bits 16-31 are unused.)
# Line 493 | Line 508 | public class ForkJoinPool extends Abstra
508      private volatile int eventCount;
509  
510      /**
511 <     * Encoded record of top of treiber stack of spare threads waiting
511 >     * Encoded record of top of Treiber stack of spare threads waiting
512       * for resumption. The top 16 bits contain an arbitrary count to
513       * avoid ABA effects. The bottom 16bits contains one plus the pool
514       * index of waiting worker thread.
# Line 507 | Line 522 | public class ForkJoinPool extends Abstra
522       * Lifecycle control. The low word contains the number of workers
523       * that are (probably) executing tasks. This value is atomically
524       * incremented before a worker gets a task to run, and decremented
525 <     * when worker has no tasks and cannot find any.  Bits 16-18
525 >     * when a worker has no tasks and cannot find any.  Bits 16-18
526       * contain runLevel value. When all are zero, the pool is
527       * running. Level transitions are monotonic (running -> shutdown
528       * -> terminating -> terminated) so each transition adds a bit.
# Line 567 | Line 582 | public class ForkJoinPool extends Abstra
582       */
583      private final int poolNumber;
584  
570
585      // Utilities for CASing fields. Note that most of these
586      // are usually manually inlined by callers
587  
# Line 597 | Line 611 | public class ForkJoinPool extends Abstra
611       * (rarely) necessary when other count updates lag.
612       *
613       * @param dr -- either zero or ONE_RUNNING
614 <     * @param dt == either zero or ONE_TOTAL
614 >     * @param dt -- either zero or ONE_TOTAL
615       */
616      private void decrementWorkerCounts(int dr, int dt) {
617          for (;;) {
# Line 615 | Line 629 | public class ForkJoinPool extends Abstra
629      }
630  
631      /**
618     * Increments event count
619     */
620    private void advanceEventCount() {
621        int c;
622        do {} while(!UNSAFE.compareAndSwapInt(this, eventCountOffset,
623                                              c = eventCount, c+1));
624    }
625
626    /**
627     * Tries incrementing active count; fails on contention.
628     * Called by workers before executing tasks.
629     *
630     * @return true on success
631     */
632    final boolean tryIncrementActiveCount() {
633        int c;
634        return UNSAFE.compareAndSwapInt(this, runStateOffset,
635                                        c = runState, c + 1);
636    }
637
638    /**
632       * Tries decrementing active count; fails on contention.
633       * Called when workers cannot find tasks to run.
634       */
# Line 687 | Line 680 | public class ForkJoinPool extends Abstra
680      }
681  
682      /**
683 <     * Nulls out record of worker in workers array
683 >     * Nulls out record of worker in workers array.
684       */
685      private void forgetWorker(ForkJoinWorkerThread w) {
686          int idx = w.poolIndex;
687 <        // Locking helps method recordWorker avoid unecessary expansion
687 >        // Locking helps method recordWorker avoid unnecessary expansion
688          final ReentrantLock lock = this.workerLock;
689          lock.lock();
690          try {
# Line 703 | Line 696 | public class ForkJoinPool extends Abstra
696          }
697      }
698  
706    // adding and removing workers
707
708    /**
709     * Tries to create and add new worker. Assumes that worker counts
710     * are already updated to accommodate the worker, so adjusts on
711     * failure.
712     *
713     * @return the worker, or null on failure
714     */
715    private ForkJoinWorkerThread addWorker() {
716        ForkJoinWorkerThread w = null;
717        try {
718            w = factory.newThread(this);
719        } finally { // Adjust on either null or exceptional factory return
720            if (w == null) {
721                decrementWorkerCounts(ONE_RUNNING, ONE_TOTAL);
722                tryTerminate(false); // in case of failure during shutdown
723            }
724        }
725        if (w != null) {
726            w.start(recordWorker(w), ueh);
727            advanceEventCount();
728        }
729        return w;
730    }
731
699      /**
700       * Final callback from terminating worker.  Removes record of
701       * worker from array, and adjusts counts. If pool is shutting
702 <     * down, tries to complete terminatation.
702 >     * down, tries to complete termination.
703       *
704       * @param w the worker
705       */
706      final void workerTerminated(ForkJoinWorkerThread w) {
707          forgetWorker(w);
708 <        decrementWorkerCounts(w.isTrimmed()? 0 : ONE_RUNNING, ONE_TOTAL);
708 >        decrementWorkerCounts(w.isTrimmed() ? 0 : ONE_RUNNING, ONE_TOTAL);
709          while (w.stealCount != 0) // collect final count
710              tryAccumulateStealCount(w);
711          tryTerminate(false);
# Line 750 | Line 717 | public class ForkJoinPool extends Abstra
717       * Releases workers blocked on a count not equal to current count.
718       * Normally called after precheck that eventWaiters isn't zero to
719       * avoid wasted array checks. Gives up upon a change in count or
720 <     * contention, letting other workers take over.
720 >     * upon releasing two workers, letting others take over.
721       */
722      private void releaseEventWaiters() {
723          ForkJoinWorkerThread[] ws = workers;
724          int n = ws.length;
725          long h = eventWaiters;
726          int ec = eventCount;
727 +        boolean releasedOne = false;
728          ForkJoinWorkerThread w; int id;
729 <        while ((int)(h >>> EVENT_COUNT_SHIFT) != ec &&
730 <               (id = ((int)(h & WAITER_ID_MASK)) - 1) >= 0 &&
731 <               id < n && (w = ws[id]) != null &&
732 <               UNSAFE.compareAndSwapLong(this, eventWaitersOffset,
733 <                                         h,  h = w.nextWaiter)) {
734 <            LockSupport.unpark(w);
735 <            if (eventWaiters != h || eventCount != ec)
729 >        while ((id = ((int)(h & WAITER_ID_MASK)) - 1) >= 0 &&
730 >               (int)(h >>> EVENT_COUNT_SHIFT) != ec &&
731 >               id < n && (w = ws[id]) != null) {
732 >            if (UNSAFE.compareAndSwapLong(this, eventWaitersOffset,
733 >                                          h,  w.nextWaiter)) {
734 >                LockSupport.unpark(w);
735 >                if (releasedOne) // exit on second release
736 >                    break;
737 >                releasedOne = true;
738 >            }
739 >            if (eventCount != ec)
740                  break;
741 +            h = eventWaiters;
742          }
743      }
744  
# Line 782 | Line 755 | public class ForkJoinPool extends Abstra
755  
756      /**
757       * Adds the given worker to event queue and blocks until
758 <     * terminating or event count advances from the workers
786 <     * lastEventCount value
758 >     * terminating or event count advances from the given value
759       *
760       * @param w the calling worker thread
761 +     * @param ec the count
762       */
763 <    private void eventSync(ForkJoinWorkerThread w) {
791 <        int ec = w.lastEventCount;
763 >    private void eventSync(ForkJoinWorkerThread w, int ec) {
764          long nh = (((long)ec) << EVENT_COUNT_SHIFT) | ((long)(w.poolIndex+1));
765          long h;
766          while ((runState < SHUTDOWN || !tryTerminate(false)) &&
# Line 808 | Line 780 | public class ForkJoinPool extends Abstra
780       * event waiter) until terminating or event count advances from
781       * the given value. The oldest (first) waiter uses a timed wait to
782       * occasionally one-by-one shrink the number of workers (to a
783 <     * minumum of one) if the pool has not been used for extended
783 >     * minimum of one) if the pool has not been used for extended
784       * periods.
785       *
786       * @param w the calling worker thread
# Line 819 | Line 791 | public class ForkJoinPool extends Abstra
791              if (tryAccumulateStealCount(w)) { // transfer while idle
792                  boolean untimed = (w.nextWaiter != 0L ||
793                                     (workerCounts & RUNNING_COUNT_MASK) <= 1);
794 <                long startTime = untimed? 0 : System.nanoTime();
794 >                long startTime = untimed ? 0 : System.nanoTime();
795                  Thread.interrupted();         // clear/ignore interrupt
796 <                if (eventCount != ec || !w.isRunning() ||
797 <                    runState >= TERMINATING)  // recheck after clear
826 <                    break;
796 >                if (eventCount != ec || w.isTerminating())
797 >                    break;                    // recheck after clear
798                  if (untimed)
799                      LockSupport.park(w);
800                  else {
801                      LockSupport.parkNanos(w, SHRINK_RATE_NANOS);
802 <                    if (eventCount != ec || !w.isRunning() ||
832 <                        runState >= TERMINATING)
802 >                    if (eventCount != ec || w.isTerminating())
803                          break;
804                      if (System.nanoTime() - startTime >= SHRINK_RATE_NANOS)
805 <                        tryShutdownWaiter(ec);
805 >                        tryShutdownUnusedWorker(ec);
806                  }
807              }
808          }
809      }
810  
811 <    /**
842 <     * Callback from the oldest waiter in awaitEvent waking up after a
843 <     * period of non-use. Tries (once) to shutdown an event waiter (or
844 <     * a spare, if one exists). Note that we don't need CAS or locks
845 <     * here because the method is called only from one thread
846 <     * occasionally waking (and even misfires are OK). Note that
847 <     * until the shutdown worker fully terminates, workerCounts
848 <     * will overestimate total count, which is tolerable.
849 <     *
850 <     * @param ec the event count waited on by caller (to abort
851 <     * attempt if count has since changed).
852 <     */
853 <    private void tryShutdownWaiter(int ec) {
854 <        if (spareWaiters != 0) { // prefer killing spares
855 <            tryShutdownSpare();
856 <            return;
857 <        }
858 <        ForkJoinWorkerThread[] ws = workers;
859 <        int n = ws.length;
860 <        long h = eventWaiters;
861 <        ForkJoinWorkerThread w; int id; long nh;
862 <        if (runState == 0 &&
863 <            submissionQueue.isEmpty() &&
864 <            eventCount == ec &&
865 <            (id = ((int)(h & WAITER_ID_MASK)) - 1) >= 0 &&
866 <            id < n && (w = ws[id]) != null &&
867 <            (nh = w.nextWaiter) != 0L && // keep at least one worker
868 <            UNSAFE.compareAndSwapLong(this, eventWaitersOffset, h, nh)) {
869 <            w.shutdown();
870 <            LockSupport.unpark(w);
871 <        }
872 <        releaseEventWaiters();
873 <    }
874 <
875 <    // Maintaining spares
811 >    // Maintaining parallelism
812  
813      /**
814 <     * Pushes worker onto the spare stack
814 >     * Pushes worker onto the spare stack.
815       */
816      final void pushSpare(ForkJoinWorkerThread w) {
817          int ns = (++w.spareCount << SPARE_COUNT_SHIFT) | (w.poolIndex + 1);
# Line 884 | Line 820 | public class ForkJoinPool extends Abstra
820      }
821  
822      /**
823 <     * Callback from oldest spare occasionally waking up.  Tries
824 <     * (once) to shutdown a spare. Same idea as tryShutdownWaiter.
823 >     * Tries (once) to resume a spare if the number of running
824 >     * threads is less than target.
825       */
826 <    final void tryShutdownSpare() {
826 >    private void tryResumeSpare() {
827          int sw, id;
892        ForkJoinWorkerThread w;
893        ForkJoinWorkerThread[] ws;
894        if ((id = ((sw = spareWaiters) & SPARE_ID_MASK) - 1) >= 0 &&
895            id < (ws = workers).length && (w = ws[id]) != null &&
896            (workerCounts & RUNNING_COUNT_MASK) >= parallelism &&
897            UNSAFE.compareAndSwapInt(this, spareWaitersOffset,
898                                     sw, w.nextSpare)) {
899            w.shutdown();
900            LockSupport.unpark(w);
901            advanceEventCount();
902        }
903    }
904
905    /**
906     * Tries (once) to resume a spare if worker counts match
907     * the given count.
908     *
909     * @param wc workerCounts value on invocation of this method
910     */
911    private void tryResumeSpare(int wc) {
828          ForkJoinWorkerThread[] ws = workers;
829          int n = ws.length;
830 <        int sw, id, rs;  ForkJoinWorkerThread w;
831 <        if ((id = ((sw = spareWaiters) & SPARE_ID_MASK) - 1) >= 0 &&
830 >        ForkJoinWorkerThread w;
831 >        if ((sw = spareWaiters) != 0 &&
832 >            (id = (sw & SPARE_ID_MASK) - 1) >= 0 &&
833              id < n && (w = ws[id]) != null &&
834 <            (rs = runState) < TERMINATING &&
835 <            eventWaiters == 0L && workerCounts == wc) {
836 <            // In case all workers busy, heuristically back off to let settle
837 <            Thread.yield();
838 <            if (eventWaiters == 0L && runState == rs && // recheck
839 <                workerCounts == wc && spareWaiters == sw &&
840 <                UNSAFE.compareAndSwapInt(this, spareWaitersOffset,
841 <                                         sw, w.nextSpare)) {
842 <                int c;              // increment running count before resume
843 <                do {} while(!UNSAFE.compareAndSwapInt
844 <                            (this, workerCountsOffset,
845 <                             c = workerCounts, c + ONE_RUNNING));
929 <                if (w.tryUnsuspend())
930 <                    LockSupport.unpark(w);
931 <                else               // back out if w was shutdown
932 <                    decrementWorkerCounts(ONE_RUNNING, 0);
933 <            }
834 >            (workerCounts & RUNNING_COUNT_MASK) < parallelism &&
835 >            spareWaiters == sw &&
836 >            UNSAFE.compareAndSwapInt(this, spareWaitersOffset,
837 >                                     sw, w.nextSpare)) {
838 >            int c; // increment running count before resume
839 >            do {} while (!UNSAFE.compareAndSwapInt
840 >                         (this, workerCountsOffset,
841 >                          c = workerCounts, c + ONE_RUNNING));
842 >            if (w.tryUnsuspend())
843 >                LockSupport.unpark(w);
844 >            else   // back out if w was shutdown
845 >                decrementWorkerCounts(ONE_RUNNING, 0);
846          }
847      }
848  
937    // adding workers on demand
938
849      /**
850 <     * Adds one or more workers if needed to establish target parallelism.
851 <     * Retries upon contention.
850 >     * Tries to increase the number of running workers if below target
851 >     * parallelism: If a spare exists tries to resume it via
852 >     * tryResumeSpare.  Otherwise, if not enough total workers or all
853 >     * existing workers are busy, adds a new worker. In all cases also
854 >     * helps wake up releasable workers waiting for work.
855       */
856 <    private void addWorkerIfBelowTarget() {
856 >    private void helpMaintainParallelism() {
857          int pc = parallelism;
858 <        int wc;
859 <        while (((wc = workerCounts) >>> TOTAL_COUNT_SHIFT) < pc &&
860 <               runState < TERMINATING) {
861 <            if (UNSAFE.compareAndSwapInt(this, workerCountsOffset, wc,
862 <                                         wc + (ONE_RUNNING|ONE_TOTAL))) {
863 <                if (addWorker() == null)
858 >        int wc, rs, tc;
859 >        while (((wc = workerCounts) & RUNNING_COUNT_MASK) < pc &&
860 >               (rs = runState) < TERMINATING) {
861 >            if (spareWaiters != 0)
862 >                tryResumeSpare();
863 >            else if ((tc = wc >>> TOTAL_COUNT_SHIFT) >= MAX_WORKERS ||
864 >                     (tc >= pc && (rs & ACTIVE_COUNT_MASK) != tc))
865 >                break;   // enough total
866 >            else if (runState == rs && workerCounts == wc &&
867 >                     UNSAFE.compareAndSwapInt(this, workerCountsOffset, wc,
868 >                                              wc + (ONE_RUNNING|ONE_TOTAL))) {
869 >                ForkJoinWorkerThread w = null;
870 >                Throwable fail = null;
871 >                try {
872 >                    w = factory.newThread(this);
873 >                } catch (Throwable ex) {
874 >                    fail = ex;
875 >                }
876 >                if (w == null) { // null or exceptional factory return
877 >                    decrementWorkerCounts(ONE_RUNNING, ONE_TOTAL);
878 >                    tryTerminate(false); // handle failure during shutdown
879 >                    // If originating from an external caller,
880 >                    // propagate exception, else ignore
881 >                    if (fail != null && runState < TERMINATING &&
882 >                        !(Thread.currentThread() instanceof
883 >                          ForkJoinWorkerThread))
884 >                        UNSAFE.throwException(fail);
885                      break;
886 +                }
887 +                w.start(recordWorker(w), ueh);
888 +                if ((workerCounts >>> TOTAL_COUNT_SHIFT) >= pc) {
889 +                    int c; // advance event count
890 +                    UNSAFE.compareAndSwapInt(this, eventCountOffset,
891 +                                             c = eventCount, c+1);
892 +                    break; // add at most one unless total below target
893 +                }
894              }
895          }
896 +        if (eventWaiters != 0L)
897 +            releaseEventWaiters();
898      }
899  
900      /**
901 <     * Tries (once) to add a new worker if all existing workers are
902 <     * busy, and there are either no running workers or the deficit is
903 <     * at least twice the surplus.
904 <     *
905 <     * @param wc workerCounts value on invocation of this method
906 <     */
907 <    private void tryAddWorkerIfBusy(int wc) {
964 <        int tc, rc, rs;
965 <        int pc = parallelism;
966 <        if ((tc = wc >>> TOTAL_COUNT_SHIFT) < MAX_WORKERS &&
967 <            ((rc = wc & RUNNING_COUNT_MASK) == 0 ||
968 <             rc < pc - ((tc - pc) << 1)) &&
969 <            (rs = runState) < TERMINATING &&
970 <            (rs & ACTIVE_COUNT_MASK) == tc) {
971 <            // Since all workers busy, heuristically back off to let settle
972 <            Thread.yield();
973 <            if (eventWaiters == 0L && spareWaiters == 0 && // recheck
974 <                runState == rs && workerCounts == wc &&
975 <                UNSAFE.compareAndSwapInt(this, workerCountsOffset, wc,
976 <                                         wc + (ONE_RUNNING|ONE_TOTAL)))
977 <                addWorker();
978 <        }
979 <    }
980 <
981 <    /**
982 <     * Does at most one of:
983 <     *
984 <     * 1. Help wake up existing workers waiting for work via
985 <     *    releaseEventWaiters. (If any exist, then it doesn't
986 <     *    matter right now if under target parallelism level.)
987 <     *
988 <     * 2. If a spare exists, try (once) to resume it via tryResumeSpare.
989 <     *
990 <     * 3. If there are not enough total workers, add some
991 <     *    via addWorkerIfBelowTarget;
901 >     * Callback from the oldest waiter in awaitEvent waking up after a
902 >     * period of non-use. If all workers are idle, tries (once) to
903 >     * shutdown an event waiter or a spare, if one exists. Note that
904 >     * we don't need CAS or locks here because the method is called
905 >     * only from one thread occasionally waking (and even misfires are
906 >     * OK). Note that until the shutdown worker fully terminates,
907 >     * workerCounts will overestimate total count, which is tolerable.
908       *
909 <     * 4. Try (once) to add a new worker if all existing workers
910 <     *     are busy, via tryAddWorkerIfBusy
909 >     * @param ec the event count waited on by caller (to abort
910 >     * attempt if count has since changed).
911       */
912 <    private void helpMaintainParallelism() {
913 <        long h; int pc, wc;
914 <        if (((int)((h = eventWaiters) & WAITER_ID_MASK)) != 0) {
915 <            if ((int)(h >>> EVENT_COUNT_SHIFT) != eventCount)
916 <                releaseEventWaiters(); // avoid useless call
917 <        }
918 <        else if ((pc = parallelism) >
919 <                 ((wc = workerCounts) & RUNNING_COUNT_MASK)) {
920 <            if (spareWaiters != 0)
921 <                tryResumeSpare(wc);
922 <            else if ((wc >>> TOTAL_COUNT_SHIFT) < pc)
923 <                addWorkerIfBelowTarget();
924 <            else
925 <                tryAddWorkerIfBusy(wc);
912 >    private void tryShutdownUnusedWorker(int ec) {
913 >        if (runState == 0 && eventCount == ec) { // only trigger if all idle
914 >            ForkJoinWorkerThread[] ws = workers;
915 >            int n = ws.length;
916 >            ForkJoinWorkerThread w = null;
917 >            boolean shutdown = false;
918 >            int sw;
919 >            long h;
920 >            if ((sw = spareWaiters) != 0) { // prefer killing spares
921 >                int id = (sw & SPARE_ID_MASK) - 1;
922 >                if (id >= 0 && id < n && (w = ws[id]) != null &&
923 >                    UNSAFE.compareAndSwapInt(this, spareWaitersOffset,
924 >                                             sw, w.nextSpare))
925 >                    shutdown = true;
926 >            }
927 >            else if ((h = eventWaiters) != 0L) {
928 >                long nh;
929 >                int id = ((int)(h & WAITER_ID_MASK)) - 1;
930 >                if (id >= 0 && id < n && (w = ws[id]) != null &&
931 >                    (nh = w.nextWaiter) != 0L && // keep at least one worker
932 >                    UNSAFE.compareAndSwapLong(this, eventWaitersOffset, h, nh))
933 >                    shutdown = true;
934 >            }
935 >            if (w != null && shutdown) {
936 >                w.shutdown();
937 >                LockSupport.unpark(w);
938 >            }
939          }
940 +        releaseEventWaiters(); // in case of interference
941      }
942  
943      /**
# Line 1015 | Line 945 | public class ForkJoinPool extends Abstra
945       * stealing a task or taking a submission and running it).
946       * Performs one or more of the following:
947       *
948 <     * 1. If the worker is active, try to set its active status to
949 <     *    inactive and update activeCount. On contention, we may try
950 <     *    again on this or subsequent call.
951 <     *
952 <     * 2. Release any existing event waiters that are now relesable
953 <     *
954 <     * 3. If there are too many running threads, suspend this worker
955 <     *    (first forcing inactive if necessary).  If it is not
956 <     *    needed, it may be killed while suspended via
957 <     *    tryShutdownSpare. Otherwise, upon resume it rechecks to make
958 <     *    sure that it is still needed.
959 <     *
960 <     * 4. If more than 1 miss, await the next task event via
961 <     *    eventSync (first forcing inactivation if necessary), upon
962 <     *    which worker may also be killed, via tryShutdownWaiter.
963 <     *
964 <     * 5. Help reactivate other workers via helpMaintainParallelism
948 >     * 1. If the worker is active and either did not run a task
949 >     *    or there are too many workers, try to set its active status
950 >     *    to inactive and update activeCount. On contention, we may
951 >     *    try again in this or a subsequent call.
952 >     *
953 >     * 2. If not enough total workers, help create some.
954 >     *
955 >     * 3. If there are too many running workers, suspend this worker
956 >     *    (first forcing inactive if necessary).  If it is not needed,
957 >     *    it may be shutdown while suspended (via
958 >     *    tryShutdownUnusedWorker).  Otherwise, upon resume it
959 >     *    rechecks running thread count and need for event sync.
960 >     *
961 >     * 4. If worker did not run a task, await the next task event via
962 >     *    eventSync if necessary (first forcing inactivation), upon
963 >     *    which the worker may be shutdown via
964 >     *    tryShutdownUnusedWorker.  Otherwise, help release any
965 >     *    existing event waiters that are now releasable,
966       *
967       * @param w the worker
968 <     * @param misses the number of scans by caller failing to find work
1038 <     * (saturating at 2 to avoid wraparound)
968 >     * @param ran true if worker ran a task since last call to this method
969       */
970 <    final void preStep(ForkJoinWorkerThread w, int misses) {
970 >    final void preStep(ForkJoinWorkerThread w, boolean ran) {
971 >        int wec = w.lastEventCount;
972          boolean active = w.active;
973 +        boolean inactivate = false;
974          int pc = parallelism;
975 <        for (;;) {
976 <            int rs, wc, rc, ec; long h;
977 <            if (active && UNSAFE.compareAndSwapInt(this, runStateOffset,
978 <                                                   rs = runState, rs - 1))
979 <                active = w.active = false;
1048 <            if (((int)((h = eventWaiters) & WAITER_ID_MASK)) != 0 &&
1049 <                (int)(h >>> EVENT_COUNT_SHIFT) != eventCount) {
1050 <                releaseEventWaiters();
1051 <                if (misses > 1)
1052 <                    continue;                  // clear before sync below
975 >        while (w.runState == 0) {
976 >            int rs = runState;
977 >            if (rs >= TERMINATING) { // propagate shutdown
978 >                w.shutdown();
979 >                break;
980              }
981 <            if ((rc = ((wc = workerCounts) & RUNNING_COUNT_MASK)) > pc) {
982 <                if (!active &&                 // must inactivate to suspend
981 >            if ((inactivate || (active && (rs & ACTIVE_COUNT_MASK) >= pc)) &&
982 >                UNSAFE.compareAndSwapInt(this, runStateOffset, rs, rs - 1))
983 >                inactivate = active = w.active = false;
984 >            int wc = workerCounts;
985 >            if ((wc & RUNNING_COUNT_MASK) > pc) {
986 >                if (!(inactivate |= active) && // must inactivate to suspend
987                      workerCounts == wc &&      // try to suspend as spare
988                      UNSAFE.compareAndSwapInt(this, workerCountsOffset,
989 <                                             wc, wc - ONE_RUNNING)) {
989 >                                             wc, wc - ONE_RUNNING))
990                      w.suspendAsSpare();
1060                    if (!w.isRunning())
1061                        break;                 // was killed while spare
1062                }
1063                continue;
991              }
992 <            if (misses > 0) {
993 <                if ((ec = eventCount) == w.lastEventCount && misses > 1) {
994 <                    if (!active) {             // must inactivate to sync
995 <                        eventSync(w);
996 <                        if (w.isRunning())
997 <                            misses = 1;        // don't re-sync
998 <                        else
999 <                            break;             // was killed while waiting
1000 <                    }
1001 <                    continue;
992 >            else if ((wc >>> TOTAL_COUNT_SHIFT) < pc)
993 >                helpMaintainParallelism();     // not enough workers
994 >            else if (!ran) {
995 >                long h = eventWaiters;
996 >                int ec = eventCount;
997 >                if (h != 0L && (int)(h >>> EVENT_COUNT_SHIFT) != ec)
998 >                    releaseEventWaiters();     // release others before waiting
999 >                else if (ec != wec) {
1000 >                    w.lastEventCount = ec;     // no need to wait
1001 >                    break;
1002                  }
1003 <                w.lastEventCount = ec;
1003 >                else if (!(inactivate |= active))
1004 >                    eventSync(w, wec);         // must inactivate before sync
1005              }
1006 <            if (rc < pc)
1007 <                helpMaintainParallelism();
1080 <            break;
1006 >            else
1007 >                break;
1008          }
1009      }
1010  
1011      /**
1012       * Helps and/or blocks awaiting join of the given task.
1013 <     * Alternates between helpJoinTask() and helpMaintainParallelism()
1087 <     * as many times as there is a deficit in running count (or longer
1088 <     * if running count would become zero), then blocks if task still
1089 <     * not done.
1013 >     * See above for explanation.
1014       *
1015       * @param joinMe the task to join
1016 <     */
1017 <    final void awaitJoin(ForkJoinTask<?> joinMe, ForkJoinWorkerThread worker) {
1018 <        int threshold = parallelism;         // descend blocking thresholds
1016 >     * @param worker the current worker thread
1017 >     * @param timed true if wait should time out
1018 >     * @param nanos timeout value if timed
1019 >     */
1020 >    final void awaitJoin(ForkJoinTask<?> joinMe, ForkJoinWorkerThread worker,
1021 >                         boolean timed, long nanos) {
1022 >        long startTime = timed? System.nanoTime() : 0L;
1023 >        int retries = 2 + (parallelism >> 2); // #helpJoins before blocking
1024          while (joinMe.status >= 0) {
1025 <            boolean block; int wc;
1025 >            int wc;
1026 >            long nt = 0L;
1027 >            if (runState >= TERMINATING) {
1028 >                joinMe.cancelIgnoringExceptions();
1029 >                break;
1030 >            }
1031              worker.helpJoinTask(joinMe);
1032              if (joinMe.status < 0)
1033                  break;
1034 <            if (((wc = workerCounts) & RUNNING_COUNT_MASK) <= threshold) {
1035 <                if (threshold > 0)
1036 <                    --threshold;
1037 <                else
1038 <                    advanceEventCount(); // force release
1039 <                block = false;
1040 <            }
1041 <            else
1042 <                block = UNSAFE.compareAndSwapInt(this, workerCountsOffset,
1043 <                                                 wc, wc - ONE_RUNNING);
1044 <            helpMaintainParallelism();
1045 <            if (block) {
1046 <                int c;
1047 <                joinMe.internalAwaitDone();
1034 >            else if (retries > 0)
1035 >                --retries;
1036 >            else if (timed &&
1037 >                     (nt = nanos - (System.nanoTime() - startTime)) <= 0L)
1038 >                break;
1039 >            else if (((wc = workerCounts) & RUNNING_COUNT_MASK) != 0 &&
1040 >                     UNSAFE.compareAndSwapInt(this, workerCountsOffset,
1041 >                                              wc, wc - ONE_RUNNING)) {
1042 >                int stat, c; long h;
1043 >                while ((stat = joinMe.status) >= 0 &&
1044 >                       (h = eventWaiters) != 0L && // help release others
1045 >                       (int)(h >>> EVENT_COUNT_SHIFT) != eventCount)
1046 >                    releaseEventWaiters();
1047 >                if (stat >= 0) {
1048 >                    if ((workerCounts & RUNNING_COUNT_MASK) != 0) {
1049 >                        long ms; int ns;
1050 >                        if (!timed) {
1051 >                            ms = JOIN_TIMEOUT_MILLIS;
1052 >                            ns = 0;
1053 >                        }
1054 >                        else { // at most JOIN_TIMEOUT_MILLIS per wait
1055 >                            ms = nt / 1000000;
1056 >                            if (ms > JOIN_TIMEOUT_MILLIS) {
1057 >                                ms = JOIN_TIMEOUT_MILLIS;
1058 >                                ns = 0;
1059 >                            }
1060 >                            else
1061 >                                ns = (int) (nt % 1000000);
1062 >                        }
1063 >                        stat = joinMe.internalAwaitDone(ms, ns);
1064 >                    }
1065 >                    if (stat >= 0) // timeout or no running workers
1066 >                        helpMaintainParallelism();
1067 >                }
1068                  do {} while (!UNSAFE.compareAndSwapInt
1069                               (this, workerCountsOffset,
1070                                c = workerCounts, c + ONE_RUNNING));
1071 <                break;
1071 >                if (stat < 0)
1072 >                    break;   // else restart
1073              }
1074          }
1075      }
1076  
1077      /**
1078 <     * Same idea as awaitJoin, but no helping
1078 >     * Same idea as awaitJoin, but no helping, retries, or timeouts.
1079       */
1080      final void awaitBlocker(ManagedBlocker blocker)
1081          throws InterruptedException {
1127        int threshold = parallelism;
1082          while (!blocker.isReleasable()) {
1083 <            boolean block; int wc;
1084 <            if (((wc = workerCounts) & RUNNING_COUNT_MASK) <= threshold) {
1085 <                if (threshold > 0)
1086 <                    --threshold;
1133 <                else
1134 <                    advanceEventCount();
1135 <                block = false;
1136 <            }
1137 <            else
1138 <                block = UNSAFE.compareAndSwapInt(this, workerCountsOffset,
1139 <                                                 wc, wc - ONE_RUNNING);
1140 <            helpMaintainParallelism();
1141 <            if (block) {
1083 >            int wc = workerCounts;
1084 >            if ((wc & RUNNING_COUNT_MASK) != 0 &&
1085 >                UNSAFE.compareAndSwapInt(this, workerCountsOffset,
1086 >                                         wc, wc - ONE_RUNNING)) {
1087                  try {
1088 <                    do {} while (!blocker.isReleasable() && !blocker.block());
1088 >                    while (!blocker.isReleasable()) {
1089 >                        long h = eventWaiters;
1090 >                        if (h != 0L &&
1091 >                            (int)(h >>> EVENT_COUNT_SHIFT) != eventCount)
1092 >                            releaseEventWaiters();
1093 >                        else if ((workerCounts & RUNNING_COUNT_MASK) == 0 &&
1094 >                                 runState < TERMINATING)
1095 >                            helpMaintainParallelism();
1096 >                        else if (blocker.block())
1097 >                            break;
1098 >                    }
1099                  } finally {
1100                      int c;
1101                      do {} while (!UNSAFE.compareAndSwapInt
# Line 1178 | Line 1133 | public class ForkJoinPool extends Abstra
1133          return true;
1134      }
1135  
1136 +
1137      /**
1138       * Actions on transition to TERMINATING
1139       *
# Line 1190 | Line 1146 | public class ForkJoinPool extends Abstra
1146      private void startTerminating() {
1147          cancelSubmissions();
1148          for (int passes = 0; passes < 4 && workerCounts != 0; ++passes) {
1149 <            advanceEventCount();
1149 >            int c; // advance event count
1150 >            UNSAFE.compareAndSwapInt(this, eventCountOffset,
1151 >                                     c = eventCount, c+1);
1152              eventWaiters = 0L; // clobber lists
1153              spareWaiters = 0;
1154 <            ForkJoinWorkerThread[] ws = workers;
1197 <            int n = ws.length;
1198 <            for (int i = 0; i < n; ++i) {
1199 <                ForkJoinWorkerThread w = ws[i];
1154 >            for (ForkJoinWorkerThread w : workers) {
1155                  if (w != null) {
1156                      w.shutdown();
1157                      if (passes > 0 && !w.isTerminated()) {
1158                          w.cancelTasks();
1159                          LockSupport.unpark(w);
1160 <                        if (passes > 1) {
1160 >                        if (passes > 1 && !w.isInterrupted()) {
1161                              try {
1162                                  w.interrupt();
1163                              } catch (SecurityException ignore) {
# Line 1215 | Line 1170 | public class ForkJoinPool extends Abstra
1170      }
1171  
1172      /**
1173 <     * Clear out and cancel submissions, ignoring exceptions
1173 >     * Clears out and cancels submissions, ignoring exceptions.
1174       */
1175      private void cancelSubmissions() {
1176          ForkJoinTask<?> task;
# Line 1230 | Line 1185 | public class ForkJoinPool extends Abstra
1185      // misc support for ForkJoinWorkerThread
1186  
1187      /**
1188 <     * Returns pool number
1188 >     * Returns pool number.
1189       */
1190      final int getPoolNumber() {
1191          return poolNumber;
1192      }
1193  
1194      /**
1195 <     * Tries to accumulates steal count from a worker, clearing
1196 <     * the worker's value.
1195 >     * Tries to accumulate steal count from a worker, clearing
1196 >     * the worker's value if successful.
1197       *
1198       * @return true if worker steal count now zero
1199       */
# Line 1260 | Line 1215 | public class ForkJoinPool extends Abstra
1215       */
1216      final int idlePerActive() {
1217          int pc = parallelism; // use parallelism, not rc
1218 <        int ac = runState;    // no mask -- artifically boosts during shutdown
1218 >        int ac = runState;    // no mask -- artificially boosts during shutdown
1219          // Use exact results for small values, saturate past 4
1220 <        return pc <= ac? 0 : pc >>> 1 <= ac? 1 : pc >>> 2 <= ac? 3 : pc >>> 3;
1220 >        return ((pc <= ac) ? 0 :
1221 >                (pc >>> 1 <= ac) ? 1 :
1222 >                (pc >>> 2 <= ac) ? 3 :
1223 >                pc >>> 3);
1224      }
1225  
1226      // Public and protected methods
# Line 1312 | Line 1270 | public class ForkJoinPool extends Abstra
1270       * use {@link #defaultForkJoinWorkerThreadFactory}.
1271       * @param handler the handler for internal worker threads that
1272       * terminate due to unrecoverable errors encountered while executing
1273 <     * tasks. For default value, use <code>null</code>.
1273 >     * tasks. For default value, use {@code null}.
1274       * @param asyncMode if true,
1275       * establishes local first-in-first-out scheduling mode for forked
1276       * tasks that are never joined. This mode may be more appropriate
1277       * than default locally stack-based mode in applications in which
1278       * worker threads only process event-style asynchronous tasks.
1279 <     * For default value, use <code>false</code>.
1279 >     * For default value, use {@code false}.
1280       * @throws IllegalArgumentException if parallelism less than or
1281       *         equal to zero, or greater than implementation limit
1282       * @throws NullPointerException if the factory is null
# Line 1353 | Line 1311 | public class ForkJoinPool extends Abstra
1311       * @param pc the initial parallelism level
1312       */
1313      private static int initialArraySizeFor(int pc) {
1314 <        // See Hackers Delight, sec 3.2. We know MAX_WORKERS < (1 >>> 16)
1314 >        // If possible, initially allocate enough space for one spare
1315          int size = pc < MAX_WORKERS ? pc + 1 : MAX_WORKERS;
1316 +        // See Hackers Delight, sec 3.2. We know MAX_WORKERS < (1 >>> 16)
1317          size |= size >>> 1;
1318          size |= size >>> 2;
1319          size |= size >>> 4;
# Line 1365 | Line 1324 | public class ForkJoinPool extends Abstra
1324      // Execution methods
1325  
1326      /**
1327 <     * Common code for execute, invoke and submit
1327 >     * Submits task and creates, starts, or resumes some workers if necessary
1328       */
1329      private <T> void doSubmit(ForkJoinTask<T> task) {
1371        if (task == null)
1372            throw new NullPointerException();
1373        if (runState >= SHUTDOWN)
1374            throw new RejectedExecutionException();
1330          submissionQueue.offer(task);
1331 <        advanceEventCount();
1332 <        if (eventWaiters != 0L)
1333 <            releaseEventWaiters();
1379 <        if ((workerCounts >>> TOTAL_COUNT_SHIFT) < parallelism)
1380 <            addWorkerIfBelowTarget();
1331 >        int c; // try to increment event count -- CAS failure OK
1332 >        UNSAFE.compareAndSwapInt(this, eventCountOffset, c = eventCount, c+1);
1333 >        helpMaintainParallelism();
1334      }
1335  
1336      /**
# Line 1390 | Line 1343 | public class ForkJoinPool extends Abstra
1343       *         scheduled for execution
1344       */
1345      public <T> T invoke(ForkJoinTask<T> task) {
1346 <        doSubmit(task);
1347 <        return task.join();
1346 >        if (task == null)
1347 >            throw new NullPointerException();
1348 >        if (runState >= SHUTDOWN)
1349 >            throw new RejectedExecutionException();
1350 >        Thread t = Thread.currentThread();
1351 >        if ((t instanceof ForkJoinWorkerThread) &&
1352 >            ((ForkJoinWorkerThread)t).pool == this)
1353 >            return task.invoke();  // bypass submit if in same pool
1354 >        else {
1355 >            doSubmit(task);
1356 >            return task.join();
1357 >        }
1358 >    }
1359 >
1360 >    /**
1361 >     * Unless terminating, forks task if within an ongoing FJ
1362 >     * computation in the current pool, else submits as external task.
1363 >     */
1364 >    private <T> void forkOrSubmit(ForkJoinTask<T> task) {
1365 >        if (runState >= SHUTDOWN)
1366 >            throw new RejectedExecutionException();
1367 >        Thread t = Thread.currentThread();
1368 >        if ((t instanceof ForkJoinWorkerThread) &&
1369 >            ((ForkJoinWorkerThread)t).pool == this)
1370 >            task.fork();
1371 >        else
1372 >            doSubmit(task);
1373      }
1374  
1375      /**
# Line 1403 | Line 1381 | public class ForkJoinPool extends Abstra
1381       *         scheduled for execution
1382       */
1383      public void execute(ForkJoinTask<?> task) {
1384 <        doSubmit(task);
1384 >        if (task == null)
1385 >            throw new NullPointerException();
1386 >        forkOrSubmit(task);
1387      }
1388  
1389      // AbstractExecutorService methods
# Line 1414 | Line 1394 | public class ForkJoinPool extends Abstra
1394       *         scheduled for execution
1395       */
1396      public void execute(Runnable task) {
1397 +        if (task == null)
1398 +            throw new NullPointerException();
1399          ForkJoinTask<?> job;
1400          if (task instanceof ForkJoinTask<?>) // avoid re-wrap
1401              job = (ForkJoinTask<?>) task;
1402          else
1403              job = ForkJoinTask.adapt(task, null);
1404 <        doSubmit(job);
1404 >        forkOrSubmit(job);
1405      }
1406  
1407      /**
# Line 1432 | Line 1414 | public class ForkJoinPool extends Abstra
1414       *         scheduled for execution
1415       */
1416      public <T> ForkJoinTask<T> submit(ForkJoinTask<T> task) {
1417 <        doSubmit(task);
1417 >        if (task == null)
1418 >            throw new NullPointerException();
1419 >        forkOrSubmit(task);
1420          return task;
1421      }
1422  
# Line 1442 | Line 1426 | public class ForkJoinPool extends Abstra
1426       *         scheduled for execution
1427       */
1428      public <T> ForkJoinTask<T> submit(Callable<T> task) {
1429 +        if (task == null)
1430 +            throw new NullPointerException();
1431          ForkJoinTask<T> job = ForkJoinTask.adapt(task);
1432 <        doSubmit(job);
1432 >        forkOrSubmit(job);
1433          return job;
1434      }
1435  
# Line 1453 | Line 1439 | public class ForkJoinPool extends Abstra
1439       *         scheduled for execution
1440       */
1441      public <T> ForkJoinTask<T> submit(Runnable task, T result) {
1442 +        if (task == null)
1443 +            throw new NullPointerException();
1444          ForkJoinTask<T> job = ForkJoinTask.adapt(task, result);
1445 <        doSubmit(job);
1445 >        forkOrSubmit(job);
1446          return job;
1447      }
1448  
# Line 1464 | Line 1452 | public class ForkJoinPool extends Abstra
1452       *         scheduled for execution
1453       */
1454      public ForkJoinTask<?> submit(Runnable task) {
1455 +        if (task == null)
1456 +            throw new NullPointerException();
1457          ForkJoinTask<?> job;
1458          if (task instanceof ForkJoinTask<?>) // avoid re-wrap
1459              job = (ForkJoinTask<?>) task;
1460          else
1461              job = ForkJoinTask.adapt(task, null);
1462 <        doSubmit(job);
1462 >        forkOrSubmit(job);
1463          return job;
1464      }
1465  
# Line 1529 | Line 1519 | public class ForkJoinPool extends Abstra
1519  
1520      /**
1521       * Returns the number of worker threads that have started but not
1522 <     * yet terminated.  This result returned by this method may differ
1522 >     * yet terminated.  The result returned by this method may differ
1523       * from {@link #getParallelism} when threads are created to
1524       * maintain parallelism when others are cooperatively blocked.
1525       *
# Line 1614 | Line 1604 | public class ForkJoinPool extends Abstra
1604       */
1605      public long getQueuedTaskCount() {
1606          long count = 0;
1607 <        ForkJoinWorkerThread[] ws = workers;
1618 <        int n = ws.length;
1619 <        for (int i = 0; i < n; ++i) {
1620 <            ForkJoinWorkerThread w = ws[i];
1607 >        for (ForkJoinWorkerThread w : workers)
1608              if (w != null)
1609                  count += w.getQueueSize();
1623        }
1610          return count;
1611      }
1612  
# Line 1675 | Line 1661 | public class ForkJoinPool extends Abstra
1661       */
1662      protected int drainTasksTo(Collection<? super ForkJoinTask<?>> c) {
1663          int count = submissionQueue.drainTo(c);
1664 <        ForkJoinWorkerThread[] ws = workers;
1679 <        int n = ws.length;
1680 <        for (int i = 0; i < n; ++i) {
1681 <            ForkJoinWorkerThread w = ws[i];
1664 >        for (ForkJoinWorkerThread w : workers)
1665              if (w != null)
1666                  count += w.drainTasksTo(c);
1684        }
1667          return count;
1668      }
1669  
# Line 1785 | Line 1767 | public class ForkJoinPool extends Abstra
1767      }
1768  
1769      /**
1770 +     * Returns true if terminating or terminated. Used by ForkJoinWorkerThread.
1771 +     */
1772 +    final boolean isAtLeastTerminating() {
1773 +        return runState >= TERMINATING;
1774 +    }
1775 +
1776 +    /**
1777       * Returns {@code true} if this pool has been shut down.
1778       *
1779       * @return {@code true} if this pool has been shut down
# Line 1808 | Line 1797 | public class ForkJoinPool extends Abstra
1797          throws InterruptedException {
1798          try {
1799              return termination.awaitAdvanceInterruptibly(0, timeout, unit) > 0;
1800 <        } catch(TimeoutException ex) {
1800 >        } catch (TimeoutException ex) {
1801              return false;
1802          }
1803      }
# Line 1855 | Line 1844 | public class ForkJoinPool extends Abstra
1844       *   QueueTaker(BlockingQueue<E> q) { this.queue = q; }
1845       *   public boolean block() throws InterruptedException {
1846       *     if (item == null)
1847 <     *       item = queue.take
1847 >     *       item = queue.take();
1848       *     return true;
1849       *   }
1850       *   public boolean isReleasable() {
1851 <     *     return item != null || (item = queue.poll) != null;
1851 >     *     return item != null || (item = queue.poll()) != null;
1852       *   }
1853       *   public E getItem() { // call after pool.managedBlock completes
1854       *     return item;
# Line 1938 | Line 1927 | public class ForkJoinPool extends Abstra
1927      private static final long eventCountOffset =
1928          objectFieldOffset("eventCount", ForkJoinPool.class);
1929      private static final long eventWaitersOffset =
1930 <        objectFieldOffset("eventWaiters",ForkJoinPool.class);
1930 >        objectFieldOffset("eventWaiters", ForkJoinPool.class);
1931      private static final long stealCountOffset =
1932 <        objectFieldOffset("stealCount",ForkJoinPool.class);
1932 >        objectFieldOffset("stealCount", ForkJoinPool.class);
1933      private static final long spareWaitersOffset =
1934 <        objectFieldOffset("spareWaiters",ForkJoinPool.class);
1934 >        objectFieldOffset("spareWaiters", ForkJoinPool.class);
1935  
1936      private static long objectFieldOffset(String field, Class<?> klazz) {
1937          try {

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines