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.62 by dl, Wed Aug 11 20:28:22 2010 UTC vs.
Revision 1.80 by dl, Fri Sep 17 14:24:56 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 259 | Line 266 | public class ForkJoinPool extends Abstra
266       * workers that previously could not find a task to now find one:
267       * Submission of a new task to the pool, or another worker pushing
268       * a task onto a previously empty queue.  (We also use this
269 <     * mechanism for termination actions that require wakeups of idle
270 <     * workers).  Each worker maintains its last known event count,
271 <     * and blocks when a scan for work did not find a task AND its
272 <     * lastEventCount matches the current eventCount. Waiting idle
273 <     * workers are recorded in a variant of Treiber stack headed by
274 <     * field eventWaiters which, when nonzero, encodes the thread
275 <     * index and count awaited for by the worker thread most recently
276 <     * calling eventSync. This thread in turn has a record (field
277 <     * nextEventWaiter) for the next waiting worker.  In addition to
278 <     * allowing simpler decisions about need for wakeup, the event
279 <     * count bits in eventWaiters serve the role of tags to avoid ABA
280 <     * errors in Treiber stacks.  To reduce delays in task diffusion,
281 <     * workers not otherwise occupied may invoke method
282 <     * releaseEventWaiters, that removes and signals (unparks) workers
283 <     * not waiting on current count. To reduce stalls, To minimize
284 <     * task production stalls associate with signalling, any worker
285 <     * pushing a task on an empty queue invokes the weaker method
279 <     * signalWork, that only releases idle workers until it detects
280 <     * interference by other threads trying to release, and lets them
281 <     * take over.  The net effect is a tree-like diffusion of signals,
282 <     * where released threads (and possibly others) help with unparks.
283 <     * To further reduce contention effects a bit, failed CASes to
284 <     * increment field eventCount are tolerated without retries.
269 >     * mechanism for configuration and termination actions that
270 >     * require wakeups of idle workers).  Each worker maintains its
271 >     * last known event count, and blocks when a scan for work did not
272 >     * find a task AND its lastEventCount matches the current
273 >     * eventCount. Waiting idle workers are recorded in a variant of
274 >     * Treiber stack headed by field eventWaiters which, when nonzero,
275 >     * encodes the thread index and count awaited for by the worker
276 >     * thread most recently calling eventSync. This thread in turn has
277 >     * a record (field nextEventWaiter) for the next waiting worker.
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 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.  To avoid
309 <     * long-term build-up of spares, the oldest spare (see
310 <     * ForkJoinWorkerThread.suspendAsSpare) occasionally wakes up if
311 <     * not signalled and calls tryTrimSpare, which uses two different
312 <     * thresholds: Always killing if the number of spares is greater
313 <     * that 25% of total, and killing others only at a slower rate
314 <     * (UNUSED_SPARE_TRIM_RATE_NANOS).
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 <     * 6. Deciding when to create new workers. The main dynamic
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. The rules also
335 <     * better cope with the fact that some of the methods in this
336 <     * class tend to never become compiled (but are interpreted), so
337 <     * some components of the entire set of controls might execute 100
338 <     * times faster than others. And similarly for cases where the
339 <     * apparent lack of work is just due to GC stalls and other
335 <     * 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 347 | 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 419 | 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 +     * 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 +        30L * 1000L * 1000L * 1000L; // 2 per minute
446 +
447 +    /**
448       * Absolute bound for parallelism level. Twice this number plus
449       * one (i.e., 0xfff) must fit into a 16bit field to enable
450       * word-packing for some counts and indices.
# Line 463 | Line 489 | public class ForkJoinPool extends Abstra
489      private volatile long stealCount;
490  
491      /**
492 <     * The last nanoTime that a spare thread was trimmed
467 <     */
468 <    private volatile long trimTime;
469 <
470 <    /**
471 <     * The rate at which to trim unused spares
472 <     */
473 <    static final long UNUSED_SPARE_TRIM_RATE_NANOS =
474 <        1000L * 1000L * 1000L; // 1 sec
475 <
476 <    /**
477 <     * 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.
529       * These are bundled together to ensure consistent read for
530       * termination checks (i.e., that runLevel is at least SHUTDOWN
531       * and active threads is zero).
532 +     *
533 +     * Notes: Most direct CASes are dependent on these bitfield
534 +     * positions.  Also, this field is non-private to enable direct
535 +     * performance-sensitive CASes in ForkJoinWorkerThread.
536       */
537 <    private volatile int runState;
537 >    volatile int runState;
538  
539      // Note: The order among run level values matters.
540      private static final int RUNLEVEL_SHIFT     = 16;
# Line 523 | Line 542 | public class ForkJoinPool extends Abstra
542      private static final int TERMINATING        = 1 << (RUNLEVEL_SHIFT + 1);
543      private static final int TERMINATED         = 1 << (RUNLEVEL_SHIFT + 2);
544      private static final int ACTIVE_COUNT_MASK  = (1 << RUNLEVEL_SHIFT) - 1;
526    private static final int ONE_ACTIVE         = 1; // active update delta
545  
546      /**
547       * Holds number of total (i.e., created and not yet terminated)
# Line 564 | Line 582 | public class ForkJoinPool extends Abstra
582       */
583      private final int poolNumber;
584  
585 <
586 <    // Utilities for CASing fields. Note that several of these
569 <    // are manually inlined by callers
585 >    // Utilities for CASing fields. Note that most of these
586 >    // are usually manually inlined by callers
587  
588      /**
589       * Increments running count part of workerCounts
# Line 594 | 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 (;;) {
618              int wc = workerCounts;
602            if (wc == 0 && (runState & TERMINATED) != 0)
603                return; // lagging termination on a backout
619              if ((wc & RUNNING_COUNT_MASK)  - dr < 0 ||
620 <                (wc >>> TOTAL_COUNT_SHIFT) - dt < 0)
620 >                (wc >>> TOTAL_COUNT_SHIFT) - dt < 0) {
621 >                if ((runState & TERMINATED) != 0)
622 >                    return; // lagging termination on a backout
623                  Thread.yield();
624 +            }
625              if (UNSAFE.compareAndSwapInt(this, workerCountsOffset,
626                                           wc, wc - (dr + dt)))
627                  return;
# Line 611 | Line 629 | public class ForkJoinPool extends Abstra
629      }
630  
631      /**
614     * Increments event count
615     */
616    private void advanceEventCount() {
617        int c;
618        do {} while(!UNSAFE.compareAndSwapInt(this, eventCountOffset,
619                                              c = eventCount, c+1));
620    }
621
622    /**
623     * Tries incrementing active count; fails on contention.
624     * Called by workers before executing tasks.
625     *
626     * @return true on success
627     */
628    final boolean tryIncrementActiveCount() {
629        int c;
630        return UNSAFE.compareAndSwapInt(this, runStateOffset,
631                                        c = runState, c + ONE_ACTIVE);
632    }
633
634    /**
632       * Tries decrementing active count; fails on contention.
633       * Called when workers cannot find tasks to run.
634       */
635      final boolean tryDecrementActiveCount() {
636          int c;
637          return UNSAFE.compareAndSwapInt(this, runStateOffset,
638 <                                        c = runState, c - ONE_ACTIVE);
638 >                                        c = runState, c - 1);
639      }
640  
641      /**
# Line 683 | 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 699 | Line 696 | public class ForkJoinPool extends Abstra
696          }
697      }
698  
702    // adding and removing workers
703
704    /**
705     * Tries to create and add new worker. Assumes that worker counts
706     * are already updated to accommodate the worker, so adjusts on
707     * failure.
708     */
709    private void addWorker() {
710        ForkJoinWorkerThread w = null;
711        try {
712            w = factory.newThread(this);
713        } finally { // Adjust on either null or exceptional factory return
714            if (w == null) {
715                decrementWorkerCounts(ONE_RUNNING, ONE_TOTAL);
716                tryTerminate(false); // in case of failure during shutdown
717            }
718        }
719        if (w != null)
720            w.start(recordWorker(w), ueh);
721    }
722
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       */
# Line 740 | Line 716 | public class ForkJoinPool extends Abstra
716      /**
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.
720 <     *
745 <     * @param signalling true if caller is a signalling worker so can
746 <     * exit upon (conservatively) detected contention by other threads
747 <     * who will continue to release
719 >     * avoid wasted array checks. Gives up upon a change in count or
720 >     * upon releasing two workers, letting others take over.
721       */
722 <    private void releaseEventWaiters(boolean signalling) {
722 >    private void releaseEventWaiters() {
723          ForkJoinWorkerThread[] ws = workers;
724          int n = ws.length;
725 <        long h; // head of stack
726 <        ForkJoinWorkerThread w; int id, ec;
727 <        while ((id = ((int)((h = eventWaiters) & WAITER_ID_MASK)) - 1) >= 0 &&
728 <               (int)(h >>> EVENT_COUNT_SHIFT) != (ec = eventCount) &&
725 >        long h = eventWaiters;
726 >        int ec = eventCount;
727 >        boolean releasedOne = false;
728 >        ForkJoinWorkerThread w; int id;
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, h = w.nextWaiter))
733 >                                          h,  w.nextWaiter)) {
734                  LockSupport.unpark(w);
735 <            if (signalling && (eventCount != ec || eventWaiters != h))
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 770 | Line 750 | public class ForkJoinPool extends Abstra
750          int c; // try to increment event count -- CAS failure OK
751          UNSAFE.compareAndSwapInt(this, eventCountOffset, c = eventCount, c+1);
752          if (eventWaiters != 0L)
753 <            releaseEventWaiters(true);
753 >            releaseEventWaiters();
754      }
755  
756      /**
757 <     * Blocks worker until terminating or event count
758 <     * advances from last value held by worker
757 >     * Adds the given worker to event queue and blocks until
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) {
764 <        int wec = w.lastEventCount;
784 <        long nh = (((long)wec) << EVENT_COUNT_SHIFT) | ((long)(w.poolIndex+1));
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)) &&
767 <               ((h = eventWaiters) == 0L ||
768 <                (int)(h >>> EVENT_COUNT_SHIFT) == wec) &&
769 <               eventCount == wec) {
767 >               (((int)((h = eventWaiters) & WAITER_ID_MASK)) == 0 ||
768 >                (int)(h >>> EVENT_COUNT_SHIFT) == ec) &&
769 >               eventCount == ec) {
770              if (UNSAFE.compareAndSwapLong(this, eventWaitersOffset,
771                                            w.nextWaiter = h, nh)) {
772 <                while (runState < TERMINATING && eventCount == wec) {
773 <                    if (!tryAccumulateStealCount(w))  // transfer while idle
774 <                        continue;
775 <                    Thread.interrupted();             // clear/ignore interrupt
776 <                    if (eventCount != wec)
777 <                        break;
772 >                awaitEvent(w, ec);
773 >                break;
774 >            }
775 >        }
776 >    }
777 >
778 >    /**
779 >     * Blocks the given worker (that has already been entered as an
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 >     * minimum of one) if the pool has not been used for extended
784 >     * periods.
785 >     *
786 >     * @param w the calling worker thread
787 >     * @param ec the count
788 >     */
789 >    private void awaitEvent(ForkJoinWorkerThread w, int ec) {
790 >        while (eventCount == ec) {
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();
795 >                Thread.interrupted();         // clear/ignore interrupt
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.isTerminating())
803 +                        break;
804 +                    if (System.nanoTime() - startTime >= SHRINK_RATE_NANOS)
805 +                        tryShutdownUnusedWorker(ec);
806                  }
800                break;
807              }
808          }
803        w.lastEventCount = eventCount;
809      }
810  
811 <    // 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);
817 >        int ns = (++w.spareCount << SPARE_COUNT_SHIFT) | (w.poolIndex + 1);
818          do {} while (!UNSAFE.compareAndSwapInt(this, spareWaitersOffset,
819                                                 w.nextSpare = spareWaiters,ns));
820      }
821  
822      /**
823 <     * Tries (once) to resume a spare if running count is less than
824 <     * target parallelism. Fails on contention or stale workers.
823 >     * Tries (once) to resume a spare if the number of running
824 >     * threads is less than target.
825       */
826      private void tryResumeSpare() {
827          int sw, id;
828 +        ForkJoinWorkerThread[] ws = workers;
829 +        int n = ws.length;
830          ForkJoinWorkerThread w;
831 <        ForkJoinWorkerThread[] ws;
832 <        if ((id = ((sw = spareWaiters) & SPARE_ID_MASK) - 1) >= 0 &&
833 <            id < (ws = workers).length && (w = ws[id]) != null &&
831 >        if ((sw = spareWaiters) != 0 &&
832 >            (id = (sw & SPARE_ID_MASK) - 1) >= 0 &&
833 >            id < n && (w = ws[id]) != null &&
834              (workerCounts & RUNNING_COUNT_MASK) < parallelism &&
828            eventWaiters == 0L &&
835              spareWaiters == sw &&
836              UNSAFE.compareAndSwapInt(this, spareWaitersOffset,
837 <                                     sw, w.nextSpare) &&
838 <            w.tryUnsuspend()) {
839 <            int c; // try increment; if contended, finish after unpark
840 <            boolean inc = UNSAFE.compareAndSwapInt(this, workerCountsOffset,
841 <                                                   c = workerCounts,
842 <                                                   c + ONE_RUNNING);
843 <            LockSupport.unpark(w);
844 <            if (!inc) {
845 <                do {} while(!UNSAFE.compareAndSwapInt(this, workerCountsOffset,
840 <                                                      c = workerCounts,
841 <                                                      c + ONE_RUNNING));
842 <            }
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  
849      /**
850 <     * Callback from oldest spare occasionally waking up.  Tries
851 <     * (once) to shutdown a spare if more than 25% spare overage, or
852 <     * if UNUSED_SPARE_TRIM_RATE_NANOS have elapsed and there are at
853 <     * least #parallelism running threads. Note that we don't need CAS
854 <     * or locks here because the method is called only from the oldest
855 <     * suspended spare occasionally waking (and even misfires are OK).
856 <     *
854 <     * @param now the wake up nanoTime of caller
855 <     */
856 <    final void tryTrimSpare(long now) {
857 <        long lastTrim = trimTime;
858 <        trimTime = now;
859 <        helpMaintainParallelism(); // first, help wake up any needed spares
860 <        int sw, id;
861 <        ForkJoinWorkerThread w;
862 <        ForkJoinWorkerThread[] ws;
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 helpMaintainParallelism() {
857          int pc = parallelism;
858 <        int wc = workerCounts;
859 <        if ((wc & RUNNING_COUNT_MASK) >= pc &&
860 <            (((wc >>> TOTAL_COUNT_SHIFT) - pc) > (pc >>> 2) + 1 ||// approx 25%
861 <             now - lastTrim >= UNUSED_SPARE_TRIM_RATE_NANOS) &&
862 <            (id = ((sw = spareWaiters) & SPARE_ID_MASK) - 1) >= 0 &&
863 <            id < (ws = workers).length && (w = ws[id]) != null &&
864 <            UNSAFE.compareAndSwapInt(this, spareWaitersOffset,
865 <                                     sw, w.nextSpare))
866 <            w.shutdown(false);
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 <     * Does at most one of:
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 <     * 1. Help wake up existing workers waiting for work via
910 <     *    releaseEventWaiters. (If any exist, then it probably doesn't
880 <     *    matter right now if under target parallelism level.)
881 <     *
882 <     * 2. If below parallelism level and a spare exists, try (once)
883 <     *    to resume it via tryResumeSpare.
884 <     *
885 <     * 3. If neither of the above, tries (once) to add a new
886 <     *    worker if either there are not enough total, or if all
887 <     *    existing workers are busy, there are either no running
888 <     *    workers or the deficit is at least twice the surplus.
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 <        // uglified to work better when not compiled
914 <        int pc, wc, rc, tc, rs; long h;
915 <        if ((h = eventWaiters) != 0L) {
916 <            if ((int)(h >>> EVENT_COUNT_SHIFT) != eventCount)
917 <                releaseEventWaiters(false); // avoid useless call
918 <        }
919 <        else if ((pc = parallelism) >
920 <                 (rc = ((wc = workerCounts) & RUNNING_COUNT_MASK))) {
921 <            if (spareWaiters != 0)
922 <                tryResumeSpare();
923 <            else if ((rs = runState) < TERMINATING &&
924 <                     ((tc = wc >>> TOTAL_COUNT_SHIFT) < pc ||
925 <                      (tc == (rs & ACTIVE_COUNT_MASK) && // all busy
926 <                       (rc == 0 ||                       // must add
927 <                        rc < pc - ((tc - pc) << 1)) &&   // within slack
928 <                       tc < MAX_WORKERS && runState == rs)) && // recheck busy
929 <                     workerCounts == wc &&
930 <                     UNSAFE.compareAndSwapInt(this, workerCountsOffset, wc,
931 <                                              wc + (ONE_RUNNING|ONE_TOTAL)))
932 <                addWorker();
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      /**
944       * Callback from workers invoked upon each top-level action (i.e.,
945 <     * stealing a task or taking a submission and running
946 <     * it). Performs one or more of the following:
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 cannot find work (misses > 0), updates its
949 <     *    active status to inactive and updates activeCount unless
950 <     *    this is the first miss and there is contention, in which
951 <     *    case it may try again (either in this or a subsequent
952 <     *    call).
953 <     *
954 <     * 2. If there are at least 2 misses, awaits the next task event
955 <     *    via eventSync
956 <     *
957 <     * 3. If there are too many running threads, suspends this worker
958 <     *    (first forcing inactivation if necessary).  If it is not
959 <     *    needed, it may be killed while suspended via
960 <     *    tryTrimSpare. Otherwise, upon resume it rechecks to make
961 <     *    sure that it is still needed.
962 <     *
963 <     * 4. Helps release and/or reactivate other workers via
964 <     *    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
939 <     * (saturating at 2 just 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 wc = workerCounts;
977 <            int rc = wc & RUNNING_COUNT_MASK;
978 <            if (active && (misses > 0 || rc > pc)) {
979 <                int rs;                      // try inactivate
949 <                if (UNSAFE.compareAndSwapInt(this, runStateOffset,
950 <                                             rs = runState, rs - ONE_ACTIVE))
951 <                    active = w.active = false;
952 <                else if (misses > 1 || rc > pc ||
953 <                         (rs & ACTIVE_COUNT_MASK) >= pc)
954 <                    continue;                // force inactivate
955 <            }
956 <            if (misses > 1) {
957 <                misses = 0;                  // don't re-sync
958 <                eventSync(w);                // continue loop to recheck rc
975 >        while (w.runState == 0) {
976 >            int rs = runState;
977 >            if (rs >= TERMINATING) { // propagate shutdown
978 >                w.shutdown();
979 >                break;
980              }
981 <            else if (rc > pc) {
982 <                if (workerCounts == wc &&   // try to suspend as spare
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) &&
990 <                    !w.suspendAsSpare())    // false if killed
989 >                                             wc, wc - ONE_RUNNING))
990 >                    w.suspendAsSpare();
991 >            }
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 +                else if (!(inactivate |= active))
1004 +                    eventSync(w, wec);         // must inactivate before sync
1005              }
1006 <            else {
968 <                if (rc < pc || eventWaiters != 0L)
969 <                    helpMaintainParallelism();
1006 >            else
1007                  break;
971            }
1008          }
1009      }
1010  
1011      /**
1012       * Helps and/or blocks awaiting join of the given task.
1013 <     * Alternates between helpJoinTask() and helpMaintainParallelism()
978 <     * as many times as there is a deficit in running count (or longer
979 <     * if running count would become zero), then blocks if task still
980 <     * not done.
1013 >     * See above for explanation.
1014       *
1015       * @param joinMe the task to join
1016 +     * @param worker the current worker thread
1017       */
1018      final void awaitJoin(ForkJoinTask<?> joinMe, ForkJoinWorkerThread worker) {
1019 <        int threshold = parallelism;         // descend blocking thresholds
1019 >        int retries = 2 + (parallelism >> 2); // #helpJoins before blocking
1020          while (joinMe.status >= 0) {
1021 <            boolean block; int wc;
1021 >            int wc;
1022              worker.helpJoinTask(joinMe);
1023              if (joinMe.status < 0)
1024                  break;
1025 <            if (((wc = workerCounts) & RUNNING_COUNT_MASK) <= threshold) {
1026 <                if (threshold > 0)
1027 <                    --threshold;
1028 <                else
1029 <                    advanceEventCount(); // force release
1030 <                block = false;
1031 <            }
1032 <            else
1033 <                block = UNSAFE.compareAndSwapInt(this, workerCountsOffset,
1034 <                                                 wc, wc - ONE_RUNNING);
1035 <            helpMaintainParallelism();
1036 <            if (block) {
1037 <                int c;
1038 <                joinMe.internalAwaitDone();
1025 >            else if (retries > 0)
1026 >                --retries;
1027 >            else if (((wc = workerCounts) & RUNNING_COUNT_MASK) != 0 &&
1028 >                     UNSAFE.compareAndSwapInt(this, workerCountsOffset,
1029 >                                              wc, wc - ONE_RUNNING)) {
1030 >                int stat, c; long h;
1031 >                while ((stat = joinMe.status) >= 0 &&
1032 >                       (h = eventWaiters) != 0L && // help release others
1033 >                       (int)(h >>> EVENT_COUNT_SHIFT) != eventCount)
1034 >                    releaseEventWaiters();
1035 >                if (stat >= 0 &&
1036 >                    ((workerCounts & RUNNING_COUNT_MASK) == 0 ||
1037 >                     (stat =
1038 >                      joinMe.internalAwaitDone(JOIN_TIMEOUT_MILLIS)) >= 0))
1039 >                    helpMaintainParallelism(); // timeout or no running workers
1040                  do {} while (!UNSAFE.compareAndSwapInt
1041                               (this, workerCountsOffset,
1042                                c = workerCounts, c + ONE_RUNNING));
1043 <                break;
1043 >                if (stat < 0)
1044 >                    break;   // else restart
1045              }
1046          }
1047      }
1048  
1049      /**
1050 <     * Same idea as awaitJoin, but no helping
1050 >     * Same idea as awaitJoin, but no helping, retries, or timeouts.
1051       */
1052      final void awaitBlocker(ManagedBlocker blocker)
1053          throws InterruptedException {
1018        int threshold = parallelism;
1054          while (!blocker.isReleasable()) {
1055 <            boolean block; int wc;
1056 <            if (((wc = workerCounts) & RUNNING_COUNT_MASK) <= threshold) {
1057 <                if (threshold > 0)
1058 <                    --threshold;
1024 <                else
1025 <                    advanceEventCount();
1026 <                block = false;
1027 <            }
1028 <            else
1029 <                block = UNSAFE.compareAndSwapInt(this, workerCountsOffset,
1030 <                                                 wc, wc - ONE_RUNNING);
1031 <            helpMaintainParallelism();
1032 <            if (block) {
1055 >            int wc = workerCounts;
1056 >            if ((wc & RUNNING_COUNT_MASK) != 0 &&
1057 >                UNSAFE.compareAndSwapInt(this, workerCountsOffset,
1058 >                                         wc, wc - ONE_RUNNING)) {
1059                  try {
1060 <                    do {} while (!blocker.isReleasable() && !blocker.block());
1060 >                    while (!blocker.isReleasable()) {
1061 >                        long h = eventWaiters;
1062 >                        if (h != 0L &&
1063 >                            (int)(h >>> EVENT_COUNT_SHIFT) != eventCount)
1064 >                            releaseEventWaiters();
1065 >                        else if ((workerCounts & RUNNING_COUNT_MASK) == 0 &&
1066 >                                 runState < TERMINATING)
1067 >                            helpMaintainParallelism();
1068 >                        else if (blocker.block())
1069 >                            break;
1070 >                    }
1071                  } finally {
1072                      int c;
1073                      do {} while (!UNSAFE.compareAndSwapInt
# Line 1069 | Line 1105 | public class ForkJoinPool extends Abstra
1105          return true;
1106      }
1107  
1108 +
1109      /**
1110       * Actions on transition to TERMINATING
1111       *
1112       * Runs up to four passes through workers: (0) shutting down each
1113 <     * quietly (without waking up if parked) to quickly spread
1114 <     * notifications without unnecessary bouncing around event queues
1115 <     * etc (1) wake up and help cancel tasks (2) interrupt (3) mop up
1116 <     * races with interrupted workers
1113 >     * (without waking up if parked) to quickly spread notifications
1114 >     * without unnecessary bouncing around event queues etc (1) wake
1115 >     * up and help cancel tasks (2) interrupt (3) mop up races with
1116 >     * interrupted workers
1117       */
1118      private void startTerminating() {
1119          cancelSubmissions();
1120          for (int passes = 0; passes < 4 && workerCounts != 0; ++passes) {
1121 <            advanceEventCount();
1121 >            int c; // advance event count
1122 >            UNSAFE.compareAndSwapInt(this, eventCountOffset,
1123 >                                     c = eventCount, c+1);
1124              eventWaiters = 0L; // clobber lists
1125              spareWaiters = 0;
1126 <            ForkJoinWorkerThread[] ws = workers;
1088 <            int n = ws.length;
1089 <            for (int i = 0; i < n; ++i) {
1090 <                ForkJoinWorkerThread w = ws[i];
1126 >            for (ForkJoinWorkerThread w : workers) {
1127                  if (w != null) {
1128 <                    w.shutdown(true);
1128 >                    w.shutdown();
1129                      if (passes > 0 && !w.isTerminated()) {
1130                          w.cancelTasks();
1131                          LockSupport.unpark(w);
1132 <                        if (passes > 1) {
1132 >                        if (passes > 1 && !w.isInterrupted()) {
1133                              try {
1134                                  w.interrupt();
1135                              } catch (SecurityException ignore) {
# Line 1106 | Line 1142 | public class ForkJoinPool extends Abstra
1142      }
1143  
1144      /**
1145 <     * Clear out and cancel submissions, ignoring exceptions
1145 >     * Clears out and cancels submissions, ignoring exceptions.
1146       */
1147      private void cancelSubmissions() {
1148          ForkJoinTask<?> task;
# Line 1121 | Line 1157 | public class ForkJoinPool extends Abstra
1157      // misc support for ForkJoinWorkerThread
1158  
1159      /**
1160 <     * Returns pool number
1160 >     * Returns pool number.
1161       */
1162      final int getPoolNumber() {
1163          return poolNumber;
1164      }
1165  
1166      /**
1167 <     * Tries to accumulates steal count from a worker, clearing
1168 <     * the worker's value.
1167 >     * Tries to accumulate steal count from a worker, clearing
1168 >     * the worker's value if successful.
1169       *
1170       * @return true if worker steal count now zero
1171       */
# Line 1151 | Line 1187 | public class ForkJoinPool extends Abstra
1187       */
1188      final int idlePerActive() {
1189          int pc = parallelism; // use parallelism, not rc
1190 <        int ac = runState;    // no mask -- artifically boosts during shutdown
1190 >        int ac = runState;    // no mask -- artificially boosts during shutdown
1191          // Use exact results for small values, saturate past 4
1192 <        return pc <= ac? 0 : pc >>> 1 <= ac? 1 : pc >>> 2 <= ac? 3 : pc >>> 3;
1192 >        return ((pc <= ac) ? 0 :
1193 >                (pc >>> 1 <= ac) ? 1 :
1194 >                (pc >>> 2 <= ac) ? 3 :
1195 >                pc >>> 3);
1196      }
1197  
1198      // Public and protected methods
# Line 1203 | Line 1242 | public class ForkJoinPool extends Abstra
1242       * use {@link #defaultForkJoinWorkerThreadFactory}.
1243       * @param handler the handler for internal worker threads that
1244       * terminate due to unrecoverable errors encountered while executing
1245 <     * tasks. For default value, use <code>null</code>.
1245 >     * tasks. For default value, use {@code null}.
1246       * @param asyncMode if true,
1247       * establishes local first-in-first-out scheduling mode for forked
1248       * tasks that are never joined. This mode may be more appropriate
1249       * than default locally stack-based mode in applications in which
1250       * worker threads only process event-style asynchronous tasks.
1251 <     * For default value, use <code>false</code>.
1251 >     * For default value, use {@code false}.
1252       * @throws IllegalArgumentException if parallelism less than or
1253       *         equal to zero, or greater than implementation limit
1254       * @throws NullPointerException if the factory is null
# Line 1237 | Line 1276 | public class ForkJoinPool extends Abstra
1276          this.workerLock = new ReentrantLock();
1277          this.termination = new Phaser(1);
1278          this.poolNumber = poolNumberGenerator.incrementAndGet();
1240        this.trimTime = System.nanoTime();
1279      }
1280  
1281      /**
# Line 1245 | Line 1283 | public class ForkJoinPool extends Abstra
1283       * @param pc the initial parallelism level
1284       */
1285      private static int initialArraySizeFor(int pc) {
1286 <        // See Hackers Delight, sec 3.2. We know MAX_WORKERS < (1 >>> 16)
1286 >        // If possible, initially allocate enough space for one spare
1287          int size = pc < MAX_WORKERS ? pc + 1 : MAX_WORKERS;
1288 +        // See Hackers Delight, sec 3.2. We know MAX_WORKERS < (1 >>> 16)
1289          size |= size >>> 1;
1290          size |= size >>> 2;
1291          size |= size >>> 4;
# Line 1265 | Line 1304 | public class ForkJoinPool extends Abstra
1304          if (runState >= SHUTDOWN)
1305              throw new RejectedExecutionException();
1306          submissionQueue.offer(task);
1307 <        advanceEventCount();
1308 <        helpMaintainParallelism();         // start or wake up workers
1307 >        int c; // try to increment event count -- CAS failure OK
1308 >        UNSAFE.compareAndSwapInt(this, eventCountOffset, c = eventCount, c+1);
1309 >        helpMaintainParallelism(); // create, start, or resume some workers
1310      }
1311  
1312      /**
1313       * Performs the given task, returning its result upon completion.
1274     * If the caller is already engaged in a fork/join computation in
1275     * the current pool, this method is equivalent in effect to
1276     * {@link ForkJoinTask#invoke}.
1314       *
1315       * @param task the task
1316       * @return the task's result
# Line 1288 | Line 1325 | public class ForkJoinPool extends Abstra
1325  
1326      /**
1327       * Arranges for (asynchronous) execution of the given task.
1291     * If the caller is already engaged in a fork/join computation in
1292     * the current pool, this method is equivalent in effect to
1293     * {@link ForkJoinTask#fork}.
1328       *
1329       * @param task the task
1330       * @throws NullPointerException if the task is null
# Line 1319 | Line 1353 | public class ForkJoinPool extends Abstra
1353  
1354      /**
1355       * Submits a ForkJoinTask for execution.
1322     * If the caller is already engaged in a fork/join computation in
1323     * the current pool, this method is equivalent in effect to
1324     * {@link ForkJoinTask#fork}.
1356       *
1357       * @param task the task to submit
1358       * @return the task
# Line 1427 | Line 1458 | public class ForkJoinPool extends Abstra
1458  
1459      /**
1460       * Returns the number of worker threads that have started but not
1461 <     * yet terminated.  This result returned by this method may differ
1461 >     * yet terminated.  The result returned by this method may differ
1462       * from {@link #getParallelism} when threads are created to
1463       * maintain parallelism when others are cooperatively blocked.
1464       *
# Line 1512 | Line 1543 | public class ForkJoinPool extends Abstra
1543       */
1544      public long getQueuedTaskCount() {
1545          long count = 0;
1546 <        ForkJoinWorkerThread[] ws = workers;
1516 <        int n = ws.length;
1517 <        for (int i = 0; i < n; ++i) {
1518 <            ForkJoinWorkerThread w = ws[i];
1546 >        for (ForkJoinWorkerThread w : workers)
1547              if (w != null)
1548                  count += w.getQueueSize();
1521        }
1549          return count;
1550      }
1551  
# Line 1573 | Line 1600 | public class ForkJoinPool extends Abstra
1600       */
1601      protected int drainTasksTo(Collection<? super ForkJoinTask<?>> c) {
1602          int count = submissionQueue.drainTo(c);
1603 <        ForkJoinWorkerThread[] ws = workers;
1577 <        int n = ws.length;
1578 <        for (int i = 0; i < n; ++i) {
1579 <            ForkJoinWorkerThread w = ws[i];
1603 >        for (ForkJoinWorkerThread w : workers)
1604              if (w != null)
1605                  count += w.drainTasksTo(c);
1582        }
1606          return count;
1607      }
1608  
# Line 1683 | Line 1706 | public class ForkJoinPool extends Abstra
1706      }
1707  
1708      /**
1709 +     * Returns true if terminating or terminated. Used by ForkJoinWorkerThread.
1710 +     */
1711 +    final boolean isAtLeastTerminating() {
1712 +        return runState >= TERMINATING;
1713 +    }
1714 +        
1715 +    /**
1716       * Returns {@code true} if this pool has been shut down.
1717       *
1718       * @return {@code true} if this pool has been shut down
# Line 1706 | Line 1736 | public class ForkJoinPool extends Abstra
1736          throws InterruptedException {
1737          try {
1738              return termination.awaitAdvanceInterruptibly(0, timeout, unit) > 0;
1739 <        } catch(TimeoutException ex) {
1739 >        } catch (TimeoutException ex) {
1740              return false;
1741          }
1742      }
# Line 1753 | Line 1783 | public class ForkJoinPool extends Abstra
1783       *   QueueTaker(BlockingQueue<E> q) { this.queue = q; }
1784       *   public boolean block() throws InterruptedException {
1785       *     if (item == null)
1786 <     *       item = queue.take
1786 >     *       item = queue.take();
1787       *     return true;
1788       *   }
1789       *   public boolean isReleasable() {
1790 <     *     return item != null || (item = queue.poll) != null;
1790 >     *     return item != null || (item = queue.poll()) != null;
1791       *   }
1792       *   public E getItem() { // call after pool.managedBlock completes
1793       *     return item;
# Line 1836 | Line 1866 | public class ForkJoinPool extends Abstra
1866      private static final long eventCountOffset =
1867          objectFieldOffset("eventCount", ForkJoinPool.class);
1868      private static final long eventWaitersOffset =
1869 <        objectFieldOffset("eventWaiters",ForkJoinPool.class);
1869 >        objectFieldOffset("eventWaiters", ForkJoinPool.class);
1870      private static final long stealCountOffset =
1871 <        objectFieldOffset("stealCount",ForkJoinPool.class);
1871 >        objectFieldOffset("stealCount", ForkJoinPool.class);
1872      private static final long spareWaitersOffset =
1873 <        objectFieldOffset("spareWaiters",ForkJoinPool.class);
1873 >        objectFieldOffset("spareWaiters", ForkJoinPool.class);
1874  
1875      private static long objectFieldOffset(String field, Class<?> klazz) {
1876          try {

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines