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.60 by dl, Sat Jul 24 20:28:18 2010 UTC vs.
Revision 1.65 by dl, Wed Aug 18 14:05:27 2010 UTC

# Line 110 | Line 110 | import java.util.concurrent.CountDownLat
110   *
111   * <p>This implementation rejects submitted tasks (that is, by throwing
112   * {@link RejectedExecutionException}) only when the pool is shut down
113 < * or internal resources have been exhuasted.
113 > * or internal resources have been exhausted.
114   *
115   * @since 1.7
116   * @author Doug Lea
# Line 156 | Line 156 | public class ForkJoinPool extends Abstra
156       *      ForkJoinWorkerThread.helpJoinTask tracks joining->stealing
157       *      links to try to find such a task.
158       *
159 <     *   Compensating: Unless there are already enough live threads,
160 <     *      creating or or re-activating a spare thread to compensate
161 <     *      for the (blocked) joiner until it unblocks.  Spares then
162 <     *      suspend at their next opportunity or eventually die if
163 <     *      unused for too long.  See below and the internal
164 <     *      documentation for tryAwaitJoin for more details about
165 <     *      compensation rules.
159 >     *   Compensating: Unless there are already enough live threads,
160 >     *      method helpMaintainParallelism() may create or or
161 >     *      re-activate a spare thread to compensate for blocked
162 >     *      joiners until they unblock.
163       *
164       * Because the determining existence of conservatively safe
165       * helping targets, the availability of already-created spares,
166       * and the apparent need to create new spares are all racy and
167 <     * require heuristic guidance, joins (in
168 <     * ForkJoinWorkerThread.joinTask) interleave these options until
169 <     * successful.  Creating a new spare always succeeds, but also
170 <     * increases application footprint, so we try to avoid it, within
171 <     * reason.
167 >     * require heuristic guidance, we rely on multiple retries of
168 >     * each. Further, because it is impossible to keep exactly the
169 >     * target (parallelism) number of threads running at any given
170 >     * time, we allow compensation during joins to fail, and enlist
171 >     * all other threads to help out whenever they are not otherwise
172 >     * occupied (i.e., mainly in method preStep).
173       *
174 <     * The ManagedBlocker extension API can't use helping so uses a
175 <     * special version of compensation in method awaitBlocker.
174 >     * The ManagedBlocker extension API can't use helping so relies
175 >     * only on compensation in method awaitBlocker.
176       *
177       * The main throughput advantages of work-stealing stem from
178       * decentralized control -- workers mostly steal tasks from each
# Line 207 | Line 205 | public class ForkJoinPool extends Abstra
205       * blocked workers. However, all other support code is set up to
206       * work with other policies.
207       *
208 +     * To ensure that we do not hold on to worker references that
209 +     * would prevent GC, ALL accesses to workers are via indices into
210 +     * the workers array (which is one source of some of the unusual
211 +     * code constructions here). In essence, the workers array serves
212 +     * as a WeakReference mechanism. Thus for example the event queue
213 +     * stores worker indices, not worker references. Access to the
214 +     * workers in associated methods (for example releaseEventWaiters)
215 +     * must both index-check and null-check the IDs. All such accesses
216 +     * ignore bad IDs by returning out early from what they are doing,
217 +     * since this can only be associated with shutdown, in which case
218 +     * it is OK to give up. On termination, we just clobber these
219 +     * data structures without trying to use them.
220 +     *
221       * 2. Bookkeeping for dynamically adding and removing workers. We
222       * aim to approximately maintain the given level of parallelism.
223       * When some workers are known to be blocked (on joins or via
# Line 248 | Line 259 | public class ForkJoinPool extends Abstra
259       * workers that previously could not find a task to now find one:
260       * Submission of a new task to the pool, or another worker pushing
261       * a task onto a previously empty queue.  (We also use this
262 <     * mechanism for termination and reconfiguration actions that
262 >     * mechanism for configuration and termination actions that
263       * require wakeups of idle workers).  Each worker maintains its
264       * last known event count, and blocks when a scan for work did not
265       * find a task AND its lastEventCount matches the current
# Line 259 | Line 270 | public class ForkJoinPool extends Abstra
270       * a record (field nextEventWaiter) for the next waiting worker.
271       * In addition to allowing simpler decisions about need for
272       * wakeup, the event count bits in eventWaiters serve the role of
273 <     * tags to avoid ABA errors in Treiber stacks.  To reduce delays
274 <     * in task diffusion, workers not otherwise occupied may invoke
275 <     * method releaseWaiters, that removes and signals (unparks)
276 <     * workers not waiting on current count. To minimize task
277 <     * production stalls associate with signalling, any worker pushing
278 <     * a task on an empty queue invokes the weaker method signalWork,
279 <     * that only releases idle workers until it detects interference
269 <     * by other threads trying to release, and lets them take
270 <     * over. The net effect is a tree-like diffusion of signals, where
271 <     * released threads (and possibly others) help with unparks.  To
272 <     * further reduce contention effects a bit, failed CASes to
273 <     * increment field eventCount are tolerated without retries.
273 >     * tags to avoid ABA errors in Treiber stacks. Upon any wakeup,
274 >     * released threads also try to release others (but give up upon
275 >     * contention to reduce useless flailing).  The net effect is a
276 >     * tree-like diffusion of signals, where released threads (and
277 >     * possibly others) help with unparks.  To further reduce
278 >     * contention effects a bit, failed CASes to increment field
279 >     * eventCount are tolerated without retries in signalWork.
280       * Conceptually they are merged into the same event, which is OK
281       * when their only purpose is to enable workers to scan for work.
282       *
# Line 285 | Line 291 | public class ForkJoinPool extends Abstra
291       * spare threads from normal "core" threads: On each call to
292       * preStep (the only point at which we can do this) a worker
293       * checks to see if there are now too many running workers, and if
294 <     * so, suspends itself.  Methods tryAwaitJoin and awaitBlocker
295 <     * look for suspended threads to resume before considering
296 <     * creating a new replacement. We don't need a special data
297 <     * structure to maintain spares; simply scanning the workers array
298 <     * looking for worker.isSuspended() is fine because the calling
299 <     * thread is otherwise not doing anything useful anyway; we are at
300 <     * least as happy if after locating a spare, the caller doesn't
301 <     * actually block because the join is ready before we try to
302 <     * adjust and compensate.  Note that this is intrinsically racy.
303 <     * One thread may become a spare at about the same time as another
304 <     * is needlessly being created. We counteract this and related
305 <     * slop in part by requiring resumed spares to immediately recheck
306 <     * (in preStep) to see whether they they should re-suspend. The
307 <     * only effective difference between "extra" and "core" threads is
308 <     * that we allow the "extra" ones to time out and die if they are
309 <     * not resumed within a keep-alive interval of a few seconds. This
310 <     * is implemented mainly within ForkJoinWorkerThread, but requires
311 <     * some coordination (isTrimmed() -- meaning killed while
312 <     * suspended) to correctly maintain pool counts.
313 <     *
314 <     * 6. Deciding when to create new workers. The main dynamic
315 <     * control in this class is deciding when to create extra threads,
316 <     * in methods awaitJoin and awaitBlocker. We always need to create
317 <     * one when the number of running threads would become zero and
318 <     * all workers are busy. However, this is not easy to detect
319 <     * reliably in the presence of transients so we use retries and
320 <     * allow slack (in tryAwaitJoin) to reduce false alarms.  These
321 <     * effectively reduce churn at the price of systematically
322 <     * undershooting target parallelism when many threads are blocked.
323 <     * However, biasing toward undeshooting partially compensates for
324 <     * the above mechanics to suspend extra threads, that normally
325 <     * lead to overshoot because we can only suspend workers
326 <     * in-between top-level actions. It also better copes with the
327 <     * fact that some of the methods in this class tend to never
328 <     * become compiled (but are interpreted), so some components of
329 <     * the entire set of controls might execute many times faster than
330 <     * others. And similarly for cases where the apparent lack of work
331 <     * is just due to GC stalls and other transient system activity.
294 >     * so, suspends itself.  Method helpMaintainParallelism looks for
295 >     * suspended threads to resume before considering creating a new
296 >     * replacement. The spares themselves are encoded on another
297 >     * variant of a Treiber Stack, headed at field "spareWaiters".
298 >     * Note that the use of spares is intrinsically racy.  One thread
299 >     * may become a spare at about the same time as another is
300 >     * needlessly being created. We counteract this and related slop
301 >     * in part by requiring resumed spares to immediately recheck (in
302 >     * preStep) to see whether they they should re-suspend.
303 >     *
304 >     * 6. Killing off unneeded workers. The Spare and Event queues use
305 >     * similar mechanisms to shed unused workers: The oldest (first)
306 >     * waiter uses a timed rather than hard wait. When this wait times
307 >     * out without a normal wakeup, it tries to shutdown any one (for
308 >     * convenience the newest) other waiter via tryShutdownSpare or
309 >     * tryShutdownWaiter, respectively. The wakeup rates for spares
310 >     * are much shorter than for waiters. Together, they will
311 >     * eventually reduce the number of worker threads to a minimum of
312 >     * one after a long enough period without use.
313 >     *
314 >     * 7. Deciding when to create new workers. The main dynamic
315 >     * control in this class is deciding when to create extra threads
316 >     * in method helpMaintainParallelism. We would like to keep
317 >     * exactly #parallelism threads running, which is an impossble
318 >     * task. We always need to create one when the number of running
319 >     * threads would become zero and all workers are busy. Beyond
320 >     * this, we must rely on heuristics that work well in the the
321 >     * presence of transients phenomena such as GC stalls, dynamic
322 >     * compilation, and wake-up lags. These transients are extremely
323 >     * common -- we are normally trying to fully saturate the CPUs on
324 >     * a machine, so almost any activity other than running tasks
325 >     * impedes accuracy. Our main defense is to allow some slack in
326 >     * creation thresholds, using rules that reflect the fact that the
327 >     * more threads we have running, the more likely that we are
328 >     * underestimating the number running threads. (We also include
329 >     * some heuristic use of Thread.yield when all workers appear to
330 >     * be busy, to improve likelihood of counts settling.) The rules
331 >     * also better cope with the fact that some of the methods in this
332 >     * class tend to never become compiled (but are interpreted), so
333 >     * 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.
337       *
338       * Beware that there is a lot of representation-level coupling
339       * among classes ForkJoinPool, ForkJoinWorkerThread, and
# Line 335 | Line 346 | public class ForkJoinPool extends Abstra
346       *
347       * Style notes: There are lots of inline assignments (of form
348       * "while ((local = field) != 0)") which are usually the simplest
349 <     * way to ensure read orderings. Also several occurrences of the
350 <     * unusual "do {} while(!cas...)" which is the simplest way to
351 <     * force an update of a CAS'ed variable. There are also other
352 <     * coding oddities that help some methods perform reasonably even
353 <     * when interpreted (not compiled), at the expense of messiness.
349 >     * way to ensure the required read orderings (which are sometimes
350 >     * critical). Also several occurrences of the unusual "do {}
351 >     * while(!cas...)" which is the simplest way to force an update of
352 >     * a CAS'ed variable. There are also other coding oddities that
353 >     * help some methods perform reasonably even when interpreted (not
354 >     * compiled), at the expense of some messy constructions that
355 >     * reduce byte code counts.
356       *
357       * The order of declarations in this file is: (1) statics (2)
358       * fields (along with constants used when unpacking some of them)
# Line 407 | Line 420 | public class ForkJoinPool extends Abstra
420          new AtomicInteger();
421  
422      /**
423 <     * Absolute bound for parallelism level. Twice this number must
424 <     * fit into a 16bit field to enable word-packing for some counts.
423 >     * The wakeup interval (in nanoseconds) for the oldest worker
424 >     * worker waiting for an event invokes tryShutdownWaiter to shrink
425 >     * the number of workers.  The exact value does not matter too
426 >     * much, but should be long enough to slowly release resources
427 >     * during long periods without use without disrupting normal use.
428 >     */
429 >    private static final long SHRINK_RATE_NANOS =
430 >        60L * 1000L * 1000L * 1000L; // one minute
431 >
432 >    /**
433 >     * Absolute bound for parallelism level. Twice this number plus
434 >     * one (i.e., 0xfff) must fit into a 16bit field to enable
435 >     * word-packing for some counts and indices.
436       */
437 <    private static final int MAX_THREADS = 0x7fff;
437 >    private static final int MAX_WORKERS   = 0x7fff;
438  
439      /**
440       * Array holding all worker threads in the pool.  Array size must
# Line 452 | Line 476 | public class ForkJoinPool extends Abstra
476      /**
477       * Encoded record of top of treiber stack of threads waiting for
478       * events. The top 32 bits contain the count being waited for. The
479 <     * bottom word contains one plus the pool index of waiting worker
480 <     * thread.
479 >     * bottom 16 bits contains one plus the pool index of waiting
480 >     * worker thread. (Bits 16-31 are unused.)
481       */
482      private volatile long eventWaiters;
483  
484      private static final int  EVENT_COUNT_SHIFT = 32;
485 <    private static final long WAITER_ID_MASK = (1L << EVENT_COUNT_SHIFT)-1L;
485 >    private static final long WAITER_ID_MASK    = (1L << 16) - 1L;
486  
487      /**
488       * A counter for events that may wake up worker threads:
489       *   - Submission of a new task to the pool
490       *   - A worker pushing a task on an empty queue
491 <     *   - termination and reconfiguration
491 >     *   - termination
492       */
493      private volatile int eventCount;
494  
495      /**
496 +     * Encoded record of top of treiber stack of spare threads waiting
497 +     * for resumption. The top 16 bits contain an arbitrary count to
498 +     * avoid ABA effects. The bottom 16bits contains one plus the pool
499 +     * index of waiting worker thread.
500 +     */
501 +    private volatile int spareWaiters;
502 +
503 +    private static final int SPARE_COUNT_SHIFT = 16;
504 +    private static final int SPARE_ID_MASK     = (1 << 16) - 1;
505 +
506 +    /**
507       * Lifecycle control. The low word contains the number of workers
508       * that are (probably) executing tasks. This value is atomically
509       * incremented before a worker gets a task to run, and decremented
# Line 479 | Line 514 | public class ForkJoinPool extends Abstra
514       * These are bundled together to ensure consistent read for
515       * termination checks (i.e., that runLevel is at least SHUTDOWN
516       * and active threads is zero).
517 +     *
518 +     * Notes: Most direct CASes are dependent on these bitfield
519 +     * positions.  Also, this field is non-private to enable direct
520 +     * performance-sensitive CASes in ForkJoinWorkerThread.
521       */
522 <    private volatile int runState;
522 >    volatile int runState;
523  
524      // Note: The order among run level values matters.
525      private static final int RUNLEVEL_SHIFT     = 16;
# Line 488 | Line 527 | public class ForkJoinPool extends Abstra
527      private static final int TERMINATING        = 1 << (RUNLEVEL_SHIFT + 1);
528      private static final int TERMINATED         = 1 << (RUNLEVEL_SHIFT + 2);
529      private static final int ACTIVE_COUNT_MASK  = (1 << RUNLEVEL_SHIFT) - 1;
491    private static final int ONE_ACTIVE         = 1; // active update delta
530  
531      /**
532       * Holds number of total (i.e., created and not yet terminated)
# Line 529 | Line 567 | public class ForkJoinPool extends Abstra
567       */
568      private final int poolNumber;
569  
570 <    // Utilities for CASing fields. Note that several of these
571 <    // are manually inlined by callers
570 >
571 >    // Utilities for CASing fields. Note that most of these
572 >    // are usually manually inlined by callers
573  
574      /**
575 <     * Increments running count.  Also used by ForkJoinTask.
575 >     * Increments running count part of workerCounts
576       */
577      final void incrementRunningCount() {
578          int c;
# Line 554 | Line 593 | public class ForkJoinPool extends Abstra
593      }
594  
595      /**
596 <     * Tries to increment running count
596 >     * Forces decrement of encoded workerCounts, awaiting nonzero if
597 >     * (rarely) necessary when other count updates lag.
598 >     *
599 >     * @param dr -- either zero or ONE_RUNNING
600 >     * @param dt == either zero or ONE_TOTAL
601       */
602 <    final boolean tryIncrementRunningCount() {
603 <        int wc;
604 <        return UNSAFE.compareAndSwapInt(this, workerCountsOffset,
605 <                                        wc = workerCounts, wc + ONE_RUNNING);
602 >    private void decrementWorkerCounts(int dr, int dt) {
603 >        for (;;) {
604 >            int wc = workerCounts;
605 >            if ((wc & RUNNING_COUNT_MASK)  - dr < 0 ||
606 >                (wc >>> TOTAL_COUNT_SHIFT) - dt < 0) {
607 >                if ((runState & TERMINATED) != 0)
608 >                    return; // lagging termination on a backout
609 >                Thread.yield();
610 >            }
611 >            if (UNSAFE.compareAndSwapInt(this, workerCountsOffset,
612 >                                         wc, wc - (dr + dt)))
613 >                return;
614 >        }
615 >    }
616 >
617 >    /**
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      /**
# Line 571 | Line 632 | public class ForkJoinPool extends Abstra
632      final boolean tryIncrementActiveCount() {
633          int c;
634          return UNSAFE.compareAndSwapInt(this, runStateOffset,
635 <                                        c = runState, c + ONE_ACTIVE);
635 >                                        c = runState, c + 1);
636      }
637  
638      /**
# Line 581 | Line 642 | public class ForkJoinPool extends Abstra
642      final boolean tryDecrementActiveCount() {
643          int c;
644          return UNSAFE.compareAndSwapInt(this, runStateOffset,
645 <                                        c = runState, c - ONE_ACTIVE);
645 >                                        c = runState, c - 1);
646      }
647  
648      /**
# Line 610 | Line 671 | public class ForkJoinPool extends Abstra
671          lock.lock();
672          try {
673              ForkJoinWorkerThread[] ws = workers;
674 <            int nws = ws.length;
675 <            if (k < 0 || k >= nws || ws[k] != null) {
676 <                for (k = 0; k < nws && ws[k] != null; ++k)
674 >            int n = ws.length;
675 >            if (k < 0 || k >= n || ws[k] != null) {
676 >                for (k = 0; k < n && ws[k] != null; ++k)
677                      ;
678 <                if (k == nws)
679 <                    ws = Arrays.copyOf(ws, nws << 1);
678 >                if (k == n)
679 >                    ws = Arrays.copyOf(ws, n << 1);
680              }
681              ws[k] = w;
682              workers = ws; // volatile array write ensures slot visibility
# Line 649 | Line 710 | public class ForkJoinPool extends Abstra
710       * are already updated to accommodate the worker, so adjusts on
711       * failure.
712       *
713 <     * @return new worker or null if creation failed
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 <                onWorkerCreationFailure();
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)
725 >        if (w != null) {
726              w.start(recordWorker(w), ueh);
727 +            advanceEventCount();
728 +        }
729          return w;
730      }
731  
732      /**
733 <     * Adjusts counts upon failure to create worker
733 >     * Final callback from terminating worker.  Removes record of
734 >     * worker from array, and adjusts counts. If pool is shutting
735 >     * down, tries to complete terminatation.
736 >     *
737 >     * @param w the worker
738       */
739 <    private void onWorkerCreationFailure() {
740 <        for (;;) {
741 <            int wc = workerCounts;
742 <            int rc = wc & RUNNING_COUNT_MASK;
743 <            int tc = wc >>> TOTAL_COUNT_SHIFT;
744 <            if (rc == 0 || wc == 0)
745 <                Thread.yield(); // must wait for other counts to settle
746 <            else if (UNSAFE.compareAndSwapInt(this, workerCountsOffset, wc,
747 <                                              wc - (ONE_RUNNING|ONE_TOTAL)))
739 >    final void workerTerminated(ForkJoinWorkerThread w) {
740 >        forgetWorker(w);
741 >        decrementWorkerCounts(w.isTrimmed()? 0 : ONE_RUNNING, ONE_TOTAL);
742 >        while (w.stealCount != 0) // collect final count
743 >            tryAccumulateStealCount(w);
744 >        tryTerminate(false);
745 >    }
746 >
747 >    // Waiting for and signalling events
748 >
749 >    /**
750 >     * Releases workers blocked on a count not equal to current count.
751 >     * Normally called after precheck that eventWaiters isn't zero to
752 >     * avoid wasted array checks. Gives up upon a change in count or
753 >     * contention, letting other workers take over.
754 >     */
755 >    private void releaseEventWaiters() {
756 >        ForkJoinWorkerThread[] ws = workers;
757 >        int n = ws.length;
758 >        long h = eventWaiters;
759 >        int ec = eventCount;
760 >        ForkJoinWorkerThread w; int id;
761 >        while ((int)(h >>> EVENT_COUNT_SHIFT) != ec &&
762 >               (id = ((int)(h & WAITER_ID_MASK)) - 1) >= 0 &&
763 >               id < n && (w = ws[id]) != null &&
764 >               UNSAFE.compareAndSwapLong(this, eventWaitersOffset,
765 >                                         h,  h = w.nextWaiter)) {
766 >            LockSupport.unpark(w);
767 >            if (eventWaiters != h || eventCount != ec)
768                  break;
769          }
681        tryTerminate(false); // in case of failure during shutdown
770      }
771  
772      /**
773 <     * Creates enough total workers to establish target parallelism,
774 <     * giving up if terminating or addWorker fails
773 >     * Tries to advance eventCount and releases waiters. Called only
774 >     * from workers.
775       */
776 <    private void ensureEnoughTotalWorkers() {
777 <        int wc;
778 <        while (((wc = workerCounts) >>> TOTAL_COUNT_SHIFT) < parallelism &&
779 <               runState < TERMINATING) {
780 <            if ((UNSAFE.compareAndSwapInt(this, workerCountsOffset,
781 <                                          wc, wc + (ONE_RUNNING|ONE_TOTAL)) &&
782 <                 addWorker() == null))
776 >    final void signalWork() {
777 >        int c; // try to increment event count -- CAS failure OK
778 >        UNSAFE.compareAndSwapInt(this, eventCountOffset, c = eventCount, c+1);
779 >        if (eventWaiters != 0L)
780 >            releaseEventWaiters();
781 >    }
782 >
783 >    /**
784 >     * Adds the given worker to event queue and blocks until
785 >     * terminating or event count advances from the workers
786 >     * lastEventCount value
787 >     *
788 >     * @param w the calling worker thread
789 >     */
790 >    private void eventSync(ForkJoinWorkerThread w) {
791 >        int ec = w.lastEventCount;
792 >        long nh = (((long)ec) << EVENT_COUNT_SHIFT) | ((long)(w.poolIndex+1));
793 >        long h;
794 >        while ((runState < SHUTDOWN || !tryTerminate(false)) &&
795 >               (((int)((h = eventWaiters) & WAITER_ID_MASK)) == 0 ||
796 >                (int)(h >>> EVENT_COUNT_SHIFT) == ec) &&
797 >               eventCount == ec) {
798 >            if (UNSAFE.compareAndSwapLong(this, eventWaitersOffset,
799 >                                          w.nextWaiter = h, nh)) {
800 >                awaitEvent(w, ec);
801                  break;
802 +            }
803          }
804      }
805  
806      /**
807 <     * Final callback from terminating worker.  Removes record of
808 <     * worker from array, and adjusts counts. If pool is shutting
809 <     * down, tries to complete terminatation, else possibly replaces
810 <     * the worker.
807 >     * Blocks the given worker (that has already been entered as an
808 >     * event waiter) until terminating or event count advances from
809 >     * the given value. The oldest (first) waiter uses a timed wait to
810 >     * occasionally one-by-one shrink the number of workers (to a
811 >     * minumum of one) if the pool has not been used for extended
812 >     * periods.
813       *
814 <     * @param w the worker
814 >     * @param w the calling worker thread
815 >     * @param ec the count
816       */
817 <    final void workerTerminated(ForkJoinWorkerThread w) {
818 <        if (w.active) { // force inactive
819 <            w.active = false;
820 <            do {} while (!tryDecrementActiveCount());
817 >    private void awaitEvent(ForkJoinWorkerThread w, int ec) {
818 >        while (eventCount == ec) {
819 >            if (tryAccumulateStealCount(w)) { // transfer while idle
820 >                boolean untimed = (w.nextWaiter != 0L ||
821 >                                   (workerCounts & RUNNING_COUNT_MASK) <= 1);
822 >                long startTime = untimed? 0 : System.nanoTime();
823 >                Thread.interrupted();         // clear/ignore interrupt
824 >                if (eventCount != ec || !w.isRunning() ||
825 >                    runState >= TERMINATING)  // recheck after clear
826 >                    break;
827 >                if (untimed)
828 >                    LockSupport.park(w);
829 >                else {
830 >                    LockSupport.parkNanos(w, SHRINK_RATE_NANOS);
831 >                    if (eventCount != ec || !w.isRunning() ||
832 >                        runState >= TERMINATING)
833 >                        break;
834 >                    if (System.nanoTime() - startTime >= SHRINK_RATE_NANOS)
835 >                        tryShutdownWaiter(ec);
836 >                }
837 >            }
838          }
839 <        forgetWorker(w);
839 >    }
840  
841 <        // Decrement total count, and if was running, running count
842 <        // Spin (waiting for other updates) if either would be negative
843 <        int nr = w.isTrimmed() ? 0 : ONE_RUNNING;
844 <        int unit = ONE_TOTAL + nr;
845 <        for (;;) {
846 <            int wc = workerCounts;
847 <            int rc = wc & RUNNING_COUNT_MASK;
848 <            int tc = wc >>> TOTAL_COUNT_SHIFT;
849 <            if (rc - nr < 0 || tc == 0)
850 <                Thread.yield(); // back off if waiting for other updates
851 <            else if (UNSAFE.compareAndSwapInt(this, workerCountsOffset,
852 <                                              wc, wc - unit))
853 <                break;
841 >    /**
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
876  
877 <        accumulateStealCount(w); // collect final count
878 <        if (!tryTerminate(false))
879 <            ensureEnoughTotalWorkers();
877 >    /**
878 >     * Pushes worker onto the spare stack
879 >     */
880 >    final void pushSpare(ForkJoinWorkerThread w) {
881 >        int ns = (++w.spareCount << SPARE_COUNT_SHIFT) | (w.poolIndex + 1);
882 >        do {} while (!UNSAFE.compareAndSwapInt(this, spareWaitersOffset,
883 >                                               w.nextSpare = spareWaiters,ns));
884      }
885  
886 <    // Waiting for and signalling events
886 >    /**
887 >     * Callback from oldest spare occasionally waking up.  Tries
888 >     * (once) to shutdown a spare. Same idea as tryShutdownWaiter.
889 >     */
890 >    final void tryShutdownSpare() {
891 >        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 <     * Releases workers blocked on a count not equal to current count.
907 <     * @return true if any released
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 releaseWaiters() {
912 <        long top;
913 <        while ((top = eventWaiters) != 0L) {
914 <            ForkJoinWorkerThread[] ws = workers;
915 <            int n = ws.length;
916 <            for (;;) {
917 <                int i = ((int)(top & WAITER_ID_MASK)) - 1;
918 <                int e = (int)(top >>> EVENT_COUNT_SHIFT);
919 <                if (i < 0 || e == eventCount)
920 <                    return;
921 <                ForkJoinWorkerThread w;
922 <                if (i < n && (w = ws[i]) != null &&
923 <                    UNSAFE.compareAndSwapLong(this, eventWaitersOffset,
924 <                                              top, w.nextWaiter)) {
911 >    private void tryResumeSpare(int wc) {
912 >        ForkJoinWorkerThread[] ws = workers;
913 >        int n = ws.length;
914 >        int sw, id, rs;  ForkJoinWorkerThread w;
915 >        if ((id = ((sw = spareWaiters) & SPARE_ID_MASK) - 1) >= 0 &&
916 >            id < n && (w = ws[id]) != null &&
917 >            (rs = runState) < TERMINATING &&
918 >            eventWaiters == 0L && workerCounts == wc) {
919 >            // In case all workers busy, heuristically back off to let settle
920 >            Thread.yield();
921 >            if (eventWaiters == 0L && runState == rs && // recheck
922 >                workerCounts == wc && spareWaiters == sw &&
923 >                UNSAFE.compareAndSwapInt(this, spareWaitersOffset,
924 >                                         sw, w.nextSpare)) {
925 >                int c;              // increment running count before resume
926 >                do {} while(!UNSAFE.compareAndSwapInt
927 >                            (this, workerCountsOffset,
928 >                             c = workerCounts, c + ONE_RUNNING));
929 >                if (w.tryUnsuspend())
930                      LockSupport.unpark(w);
931 <                    top = eventWaiters;
932 <                }
757 <                else
758 <                    break;      // possibly stale; reread
931 >                else               // back out if w was shutdown
932 >                    decrementWorkerCounts(ONE_RUNNING, 0);
933              }
934          }
935      }
936  
937 +    // adding workers on demand
938 +
939      /**
940 <     * Ensures eventCount on exit is different (mod 2^32) than on
941 <     * entry and wakes up all waiters
940 >     * Adds one or more workers if needed to establish target parallelism.
941 >     * Retries upon contention.
942       */
943 <    private void signalEvent() {
944 <        int c;
945 <        do {} while (!UNSAFE.compareAndSwapInt(this, eventCountOffset,
946 <                                               c = eventCount, c+1));
947 <        releaseWaiters();
943 >    private void addWorkerIfBelowTarget() {
944 >        int pc = parallelism;
945 >        int wc;
946 >        while (((wc = workerCounts) >>> TOTAL_COUNT_SHIFT) < pc &&
947 >               runState < TERMINATING) {
948 >            if (UNSAFE.compareAndSwapInt(this, workerCountsOffset, wc,
949 >                                         wc + (ONE_RUNNING|ONE_TOTAL))) {
950 >                if (addWorker() == null)
951 >                    break;
952 >            }
953 >        }
954      }
955  
956      /**
957 <     * Advances eventCount and releases waiters until interference by
958 <     * other releasing threads is detected.
957 >     * Tries (once) to add a new worker if all existing workers are
958 >     * busy, and there are either no running workers or the deficit is
959 >     * at least twice the surplus.
960 >     *
961 >     * @param wc workerCounts value on invocation of this method
962       */
963 <    final void signalWork() {
964 <        int c;
965 <        UNSAFE.compareAndSwapInt(this, eventCountOffset, c=eventCount, c+1);
966 <        long top;
967 <        while ((top = eventWaiters) != 0L) {
968 <            int ec = eventCount;
969 <            ForkJoinWorkerThread[] ws = workers;
970 <            int n = ws.length;
971 <            for (;;) {
972 <                int i = ((int)(top & WAITER_ID_MASK)) - 1;
973 <                int e = (int)(top >>> EVENT_COUNT_SHIFT);
974 <                if (i < 0 || e == ec)
975 <                    return;
976 <                ForkJoinWorkerThread w;
977 <                if (i < n && (w = ws[i]) != null &&
793 <                    UNSAFE.compareAndSwapLong(this, eventWaitersOffset,
794 <                                              top, top = w.nextWaiter)) {
795 <                    LockSupport.unpark(w);
796 <                    if (top != eventWaiters) // let someone else take over
797 <                        return;
798 <                }
799 <                else
800 <                    break;      // possibly stale; reread
801 <            }
963 >    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 <     * Blockss worker until terminating or event count
807 <     * advances from last value held by worker
982 >     * Does at most one of:
983       *
984 <     * @param w the calling worker thread
985 <     */
986 <    private void eventSync(ForkJoinWorkerThread w) {
987 <        int wec = w.lastEventCount;
988 <        long nextTop = (((long)wec << EVENT_COUNT_SHIFT) |
989 <                        ((long)(w.poolIndex + 1)));
990 <        long top;
991 <        while ((runState < SHUTDOWN || !tryTerminate(false)) &&
992 <               (((int)(top = eventWaiters) & WAITER_ID_MASK) == 0 ||
993 <                (int)(top >>> EVENT_COUNT_SHIFT) == wec) &&
994 <               eventCount == wec) {
995 <            if (UNSAFE.compareAndSwapLong(this, eventWaitersOffset,
996 <                                          w.nextWaiter = top, nextTop)) {
997 <                accumulateStealCount(w); // transfer steals while idle
998 <                Thread.interrupted();    // clear/ignore interrupt
999 <                while (eventCount == wec)
1000 <                    w.doPark();
1001 <                break;
1002 <            }
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;
992 >     *
993 >     * 4. Try (once) to add a new worker if all existing workers
994 >     *     are busy, via tryAddWorkerIfBusy
995 >     */
996 >    private void helpMaintainParallelism() {
997 >        long h; int pc, wc;
998 >        if (((int)((h = eventWaiters) & WAITER_ID_MASK)) != 0) {
999 >            if ((int)(h >>> EVENT_COUNT_SHIFT) != eventCount)
1000 >                releaseEventWaiters(); // avoid useless call
1001 >        }
1002 >        else if ((pc = parallelism) >
1003 >                 ((wc = workerCounts) & RUNNING_COUNT_MASK)) {
1004 >            if (spareWaiters != 0)
1005 >                tryResumeSpare(wc);
1006 >            else if ((wc >>> TOTAL_COUNT_SHIFT) < pc)
1007 >                addWorkerIfBelowTarget();
1008 >            else
1009 >                tryAddWorkerIfBusy(wc);
1010          }
829        w.lastEventCount = eventCount;
1011      }
1012  
1013      /**
1014       * Callback from workers invoked upon each top-level action (i.e.,
1015 <     * stealing a task or taking a submission and running
1016 <     * it). Performs one or both of the following:
1015 >     * stealing a task or taking a submission and running it).
1016 >     * Performs one or more of the following:
1017       *
1018 <     * * If the worker cannot find work, updates its active status to
1019 <     * inactive and updates activeCount unless there is contention, in
1020 <     * which case it may try again (either in this or a subsequent
1021 <     * call).  Additionally, awaits the next task event and/or helps
1022 <     * wake up other releasable waiters.
1023 <     *
1024 <     * * If there are too many running threads, suspends this worker
1025 <     * (first forcing inactivation if necessary).  If it is not
1026 <     * resumed before a keepAlive elapses, the worker may be "trimmed"
1027 <     * -- killed while suspended within suspendAsSpare. Otherwise,
1028 <     * upon resume it rechecks to make sure that it is still needed.
1018 >     * 1. If the worker is active, try to set its active status to
1019 >     *    inactive and update activeCount. On contention, we may try
1020 >     *    again on this or subsequent call.
1021 >     *
1022 >     * 2. Release any existing event waiters that are now relesable
1023 >     *
1024 >     * 3. If there are too many running threads, suspend this worker
1025 >     *    (first forcing inactive if necessary).  If it is not
1026 >     *    needed, it may be killed while suspended via
1027 >     *    tryShutdownSpare. Otherwise, upon resume it rechecks to make
1028 >     *    sure that it is still needed.
1029 >     *
1030 >     * 4. If more than 1 miss, await the next task event via
1031 >     *    eventSync (first forcing inactivation if necessary), upon
1032 >     *    which worker may also be killed, via tryShutdownWaiter.
1033 >     *
1034 >     * 5. Help reactivate other workers via helpMaintainParallelism
1035       *
1036       * @param w the worker
1037 <     * @param retries the number of scans by caller failing to find work
1038 <     * find any (in which case it may block waiting for work).
1037 >     * @param misses the number of scans by caller failing to find work
1038 >     * (saturating at 2 to avoid wraparound)
1039       */
1040 <    final void preStep(ForkJoinWorkerThread w, int retries) {
1040 >    final void preStep(ForkJoinWorkerThread w, int misses) {
1041          boolean active = w.active;
1042 <        boolean inactivate = active && retries > 0;
1042 >        int pc = parallelism;
1043          for (;;) {
1044 <            int rs, wc;
1045 <            if (inactivate &&
1046 <                UNSAFE.compareAndSwapInt(this, runStateOffset,
1047 <                                         rs = runState, rs - ONE_ACTIVE))
1048 <                inactivate = active = w.active = false;
1049 <            if (((wc = workerCounts) & RUNNING_COUNT_MASK) <= parallelism) {
1050 <                if (retries > 0) {
1051 <                    if (retries > 1 && !active)
1044 >            int rs, wc, rc, ec; long h;
1045 >            if (active && UNSAFE.compareAndSwapInt(this, runStateOffset,
1046 >                                                   rs = runState, rs - 1))
1047 >                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
1053 >            }
1054 >            if ((rc = ((wc = workerCounts) & RUNNING_COUNT_MASK)) > pc) {
1055 >                if (!active &&                 // must inactivate to suspend
1056 >                    workerCounts == wc &&      // try to suspend as spare
1057 >                    UNSAFE.compareAndSwapInt(this, workerCountsOffset,
1058 >                                             wc, wc - ONE_RUNNING)) {
1059 >                    w.suspendAsSpare();
1060 >                    if (!w.isRunning())
1061 >                        break;                 // was killed while spare
1062 >                }
1063 >                continue;
1064 >            }
1065 >            if (misses > 0) {
1066 >                if ((ec = eventCount) == w.lastEventCount && misses > 1) {
1067 >                    if (!active) {             // must inactivate to sync
1068                          eventSync(w);
1069 <                    releaseWaiters();
1069 >                        if (w.isRunning())
1070 >                            misses = 1;        // don't re-sync
1071 >                        else
1072 >                            break;             // was killed while waiting
1073 >                    }
1074 >                    continue;
1075                  }
1076 <                break;
1076 >                w.lastEventCount = ec;
1077              }
1078 <            if (!(inactivate |= active) &&  // must inactivate to suspend
1079 <                UNSAFE.compareAndSwapInt(this, workerCountsOffset,
1080 <                                         wc, wc - ONE_RUNNING) &&
873 <                !w.suspendAsSpare())             // false if trimmed
874 <                break;
1078 >            if (rc < pc)
1079 >                helpMaintainParallelism();
1080 >            break;
1081          }
1082      }
1083  
1084      /**
1085 <     * Awaits join of the given task if enough threads, or can resume
1086 <     * or create a spare. Fails (in which case the given task might
1087 <     * not be done) upon contention or lack of decision about
1088 <     * blocking.
1089 <     *
884 <     * We allow blocking if:
885 <     *
886 <     * 1. There would still be at least as many running threads as
887 <     *    parallelism level if this thread blocks.
888 <     *
889 <     * 2. A spare is resumed to replace this worker. We tolerate
890 <     *    races in the decision to replace when a spare is found.
891 <     *    This may release too many, but if so, the superfluous ones
892 <     *    will re-suspend via preStep().
893 <     *
894 <     * 3. After #spares repeated retries, there are fewer than #spare
895 <     *    threads not running. We allow this slack to avoid hysteresis
896 <     *    and as a hedge against lag/uncertainty of running count
897 <     *    estimates when signalling or unblocking stalls.
898 <     *
899 <     * 4. All existing workers are busy (as rechecked via #spares
900 <     *    repeated retries by caller) and a new spare is created.
901 <     *
902 <     * If none of the above hold, we escape out by re-incrementing
903 <     * count and returning to caller, which can retry later.
1085 >     * Helps and/or blocks awaiting join of the given task.
1086 >     * 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.
1090       *
1091       * @param joinMe the task to join
906     * @param retries the number of calls to this method for this join
1092       */
1093 <    final void tryAwaitJoin(ForkJoinTask<?> joinMe, int retries) {
1094 <        int pc = parallelism;
1095 <        boolean running = true; // false when running count decremented
1096 <        outer:while (joinMe.status >= 0) {
1097 <            int wc = workerCounts;
1098 <            int rc = wc & RUNNING_COUNT_MASK;
1099 <            int tc = wc >>> TOTAL_COUNT_SHIFT;
1100 <            if (running) { // replace with spare or decrement count
1101 <                if (rc <= pc && tc > pc &&
1102 <                    (retries > 0 || tc > (runState & ACTIVE_COUNT_MASK))) {
1103 <                    ForkJoinWorkerThread[] ws = workers; // search for spare
1104 <                    int nws = ws.length;
1105 <                    for (int i = 0; i < nws; ++i) {
921 <                        ForkJoinWorkerThread w = ws[i];
922 <                        if (w != null && w.isSuspended()) {
923 <                            if ((workerCounts & RUNNING_COUNT_MASK) > pc)
924 <                                continue outer;
925 <                            if (joinMe.status < 0)
926 <                                break outer;
927 <                            if (w.tryResumeSpare()) {
928 <                                running = false;
929 <                                break outer;
930 <                            }
931 <                            continue outer; // rescan on failure to resume
932 <                        }
933 <                    }
934 <                }
935 <                if ((rc <= pc && (rc == 0 || --retries < 0)) || // no retry
936 <                    joinMe.status < 0)
937 <                    break;
938 <                if (workerCounts == wc &&
939 <                    UNSAFE.compareAndSwapInt(this, workerCountsOffset,
940 <                                             wc, wc - ONE_RUNNING))
941 <                    running = false;
1093 >    final void awaitJoin(ForkJoinTask<?> joinMe, ForkJoinWorkerThread worker) {
1094 >        int threshold = parallelism;         // descend blocking thresholds
1095 >        while (joinMe.status >= 0) {
1096 >            boolean block; int wc;
1097 >            worker.helpJoinTask(joinMe);
1098 >            if (joinMe.status < 0)
1099 >                break;
1100 >            if (((wc = workerCounts) & RUNNING_COUNT_MASK) <= threshold) {
1101 >                if (threshold > 0)
1102 >                    --threshold;
1103 >                else
1104 >                    advanceEventCount(); // force release
1105 >                block = false;
1106              }
1107 <            else { // allow blocking if enough threads
1108 <                int sc = tc - pc + 1;          // = spares, plus the one to add
1109 <                if (sc > 0 && rc > 0 && rc >= pc - sc && rc > pc - retries)
1110 <                    break;  
1111 <                if (--retries > sc && tc < MAX_THREADS &&
1112 <                    tc == (runState & ACTIVE_COUNT_MASK) &&
1113 <                    workerCounts == wc &&
1114 <                    UNSAFE.compareAndSwapInt(this, workerCountsOffset, wc,
1115 <                                             wc + (ONE_RUNNING|ONE_TOTAL))) {
1116 <                    addWorker();
1117 <                    break;
954 <                }
955 <                if (workerCounts == wc &&
956 <                    UNSAFE.compareAndSwapInt (this, workerCountsOffset,
957 <                                              wc, wc + ONE_RUNNING)) {
958 <                    running = true;            // back out; allow retry
959 <                    break;
960 <                }
1107 >            else
1108 >                block = UNSAFE.compareAndSwapInt(this, workerCountsOffset,
1109 >                                                 wc, wc - ONE_RUNNING);
1110 >            helpMaintainParallelism();
1111 >            if (block) {
1112 >                int c;
1113 >                joinMe.internalAwaitDone();
1114 >                do {} while (!UNSAFE.compareAndSwapInt
1115 >                             (this, workerCountsOffset,
1116 >                              c = workerCounts, c + ONE_RUNNING));
1117 >                break;
1118              }
1119          }
963        if (!running) { // can block
964            int c;                      // to inline incrementRunningCount
965            joinMe.internalAwaitDone();
966            do {} while (!UNSAFE.compareAndSwapInt
967                         (this, workerCountsOffset,
968                          c = workerCounts, c + ONE_RUNNING));
969        }
1120      }
1121  
1122      /**
1123 <     * Same idea as (and shares many code snippets with) tryAwaitJoin,
974 <     * but self-contained because there are no caller retries.
975 <     * TODO: Rework to use simpler API.
1123 >     * Same idea as awaitJoin, but no helping
1124       */
1125      final void awaitBlocker(ManagedBlocker blocker)
1126          throws InterruptedException {
1127 <        int pc = parallelism;
1128 <        boolean running = true;
1129 <        int retries = 0;
1130 <        boolean done;
1131 <        outer:while (!(done = blocker.isReleasable())) {
1132 <            int wc = workerCounts;
1133 <            int rc = wc & RUNNING_COUNT_MASK;
1134 <            int tc = wc >>> TOTAL_COUNT_SHIFT;
1135 <            if (running) {
988 <                if (rc <= pc && tc > pc &&
989 <                    (retries > 0 || tc > (runState & ACTIVE_COUNT_MASK))) {
990 <                    ForkJoinWorkerThread[] ws = workers;
991 <                    int nws = ws.length;
992 <                    for (int i = 0; i < nws; ++i) {
993 <                        ForkJoinWorkerThread w = ws[i];
994 <                        if (w != null && w.isSuspended()) {
995 <                            if ((workerCounts & RUNNING_COUNT_MASK) > pc)
996 <                                continue outer;
997 <                            if (done = blocker.isReleasable())
998 <                                break outer;
999 <                            if (w.tryResumeSpare()) {
1000 <                                running = false;
1001 <                                break outer;
1002 <                            }
1003 <                            continue outer;
1004 <                        }
1005 <                    }
1006 <                    if (done = blocker.isReleasable())
1007 <                        break;
1008 <                }
1009 <                if (rc > 0 && workerCounts == wc &&
1010 <                    UNSAFE.compareAndSwapInt(this, workerCountsOffset,
1011 <                                             wc, wc - ONE_RUNNING)) {
1012 <                    running = false;
1013 <                    if (rc > pc)
1014 <                        break;
1015 <                }
1127 >        int threshold = parallelism;
1128 >        while (!blocker.isReleasable()) {
1129 >            boolean block; int wc;
1130 >            if (((wc = workerCounts) & RUNNING_COUNT_MASK) <= threshold) {
1131 >                if (threshold > 0)
1132 >                    --threshold;
1133 >                else
1134 >                    advanceEventCount();
1135 >                block = false;
1136              }
1137 <            else if (rc >= pc)
1138 <                break;
1139 <            else if (tc < MAX_THREADS &&
1140 <                     tc == (runState & ACTIVE_COUNT_MASK) &&
1141 <                     workerCounts == wc &&
1142 <                     UNSAFE.compareAndSwapInt(this, workerCountsOffset, wc,
1143 <                                              wc + (ONE_RUNNING|ONE_TOTAL))) {
1144 <                addWorker();
1137 >            else
1138 >                block = UNSAFE.compareAndSwapInt(this, workerCountsOffset,
1139 >                                                 wc, wc - ONE_RUNNING);
1140 >            helpMaintainParallelism();
1141 >            if (block) {
1142 >                try {
1143 >                    do {} while (!blocker.isReleasable() && !blocker.block());
1144 >                } finally {
1145 >                    int c;
1146 >                    do {} while (!UNSAFE.compareAndSwapInt
1147 >                                 (this, workerCountsOffset,
1148 >                                  c = workerCounts, c + ONE_RUNNING));
1149 >                }
1150                  break;
1151              }
1027            else if (workerCounts == wc &&
1028                     UNSAFE.compareAndSwapInt (this, workerCountsOffset,
1029                                              wc, wc + ONE_RUNNING)) {
1030                Thread.yield();
1031                ++retries;
1032                running = true;            // allow rescan
1033            }
1034        }
1035
1036        try {
1037            if (!done)
1038                do {} while (!blocker.isReleasable() && !blocker.block());
1039        } finally {
1040            if (!running) {
1041                int c;
1042                do {} while (!UNSAFE.compareAndSwapInt
1043                             (this, workerCountsOffset,
1044                              c = workerCounts, c + ONE_RUNNING));
1045            }
1152          }
1153      }
1154  
# Line 1074 | Line 1180 | public class ForkJoinPool extends Abstra
1180  
1181      /**
1182       * Actions on transition to TERMINATING
1183 +     *
1184 +     * Runs up to four passes through workers: (0) shutting down each
1185 +     * (without waking up if parked) to quickly spread notifications
1186 +     * without unnecessary bouncing around event queues etc (1) wake
1187 +     * up and help cancel tasks (2) interrupt (3) mop up races with
1188 +     * interrupted workers
1189       */
1190      private void startTerminating() {
1191 <        for (int i = 0; i < 2; ++i) { // twice to mop up newly created workers
1192 <            cancelSubmissions();
1193 <            shutdownWorkers();
1194 <            cancelWorkerTasks();
1195 <            signalEvent();
1196 <            interruptWorkers();
1191 >        cancelSubmissions();
1192 >        for (int passes = 0; passes < 4 && workerCounts != 0; ++passes) {
1193 >            advanceEventCount();
1194 >            eventWaiters = 0L; // clobber lists
1195 >            spareWaiters = 0;
1196 >            ForkJoinWorkerThread[] ws = workers;
1197 >            int n = ws.length;
1198 >            for (int i = 0; i < n; ++i) {
1199 >                ForkJoinWorkerThread w = ws[i];
1200 >                if (w != null) {
1201 >                    w.shutdown();
1202 >                    if (passes > 0 && !w.isTerminated()) {
1203 >                        w.cancelTasks();
1204 >                        LockSupport.unpark(w);
1205 >                        if (passes > 1) {
1206 >                            try {
1207 >                                w.interrupt();
1208 >                            } catch (SecurityException ignore) {
1209 >                            }
1210 >                        }
1211 >                    }
1212 >                }
1213 >            }
1214          }
1215      }
1216  
# Line 1098 | Line 1227 | public class ForkJoinPool extends Abstra
1227          }
1228      }
1229  
1101    /**
1102     * Sets all worker run states to at least shutdown,
1103     * also resuming suspended workers
1104     */
1105    private void shutdownWorkers() {
1106        ForkJoinWorkerThread[] ws = workers;
1107        int nws = ws.length;
1108        for (int i = 0; i < nws; ++i) {
1109            ForkJoinWorkerThread w = ws[i];
1110            if (w != null)
1111                w.shutdown();
1112        }
1113    }
1114
1115    /**
1116     * Clears out and cancels all locally queued tasks
1117     */
1118    private void cancelWorkerTasks() {
1119        ForkJoinWorkerThread[] ws = workers;
1120        int nws = ws.length;
1121        for (int i = 0; i < nws; ++i) {
1122            ForkJoinWorkerThread w = ws[i];
1123            if (w != null)
1124                w.cancelTasks();
1125        }
1126    }
1127
1128    /**
1129     * Unsticks all workers blocked on joins etc
1130     */
1131    private void interruptWorkers() {
1132        ForkJoinWorkerThread[] ws = workers;
1133        int nws = ws.length;
1134        for (int i = 0; i < nws; ++i) {
1135            ForkJoinWorkerThread w = ws[i];
1136            if (w != null && !w.isTerminated()) {
1137                try {
1138                    w.interrupt();
1139                } catch (SecurityException ignore) {
1140                }
1141            }
1142        }
1143    }
1144
1230      // misc support for ForkJoinWorkerThread
1231  
1232      /**
# Line 1152 | Line 1237 | public class ForkJoinPool extends Abstra
1237      }
1238  
1239      /**
1240 <     * Accumulates steal count from a worker, clearing
1241 <     * the worker's value
1240 >     * Tries to accumulates steal count from a worker, clearing
1241 >     * the worker's value.
1242 >     *
1243 >     * @return true if worker steal count now zero
1244       */
1245 <    final void accumulateStealCount(ForkJoinWorkerThread w) {
1245 >    final boolean tryAccumulateStealCount(ForkJoinWorkerThread w) {
1246          int sc = w.stealCount;
1247 <        if (sc != 0) {
1248 <            long c;
1249 <            w.stealCount = 0;
1250 <            do {} while (!UNSAFE.compareAndSwapLong(this, stealCountOffset,
1251 <                                                    c = stealCount, c + sc));
1247 >        long c = stealCount;
1248 >        // CAS even if zero, for fence effects
1249 >        if (UNSAFE.compareAndSwapLong(this, stealCountOffset, c, c + sc)) {
1250 >            if (sc != 0)
1251 >                w.stealCount = 0;
1252 >            return true;
1253          }
1254 +        return sc == 0;
1255      }
1256  
1257      /**
# Line 1245 | Line 1334 | public class ForkJoinPool extends Abstra
1334          checkPermission();
1335          if (factory == null)
1336              throw new NullPointerException();
1337 <        if (parallelism <= 0 || parallelism > MAX_THREADS)
1337 >        if (parallelism <= 0 || parallelism > MAX_WORKERS)
1338              throw new IllegalArgumentException();
1339          this.parallelism = parallelism;
1340          this.factory = factory;
# Line 1264 | Line 1353 | public class ForkJoinPool extends Abstra
1353       * @param pc the initial parallelism level
1354       */
1355      private static int initialArraySizeFor(int pc) {
1356 <        // See Hackers Delight, sec 3.2. We know MAX_THREADS < (1 >>> 16)
1357 <        int size = pc < MAX_THREADS ? pc + 1 : MAX_THREADS;
1356 >        // See Hackers Delight, sec 3.2. We know MAX_WORKERS < (1 >>> 16)
1357 >        int size = pc < MAX_WORKERS ? pc + 1 : MAX_WORKERS;
1358          size |= size >>> 1;
1359          size |= size >>> 2;
1360          size |= size >>> 4;
# Line 1284 | Line 1373 | public class ForkJoinPool extends Abstra
1373          if (runState >= SHUTDOWN)
1374              throw new RejectedExecutionException();
1375          submissionQueue.offer(task);
1376 <        signalEvent();
1377 <        ensureEnoughTotalWorkers();
1376 >        advanceEventCount();
1377 >        if (eventWaiters != 0L)
1378 >            releaseEventWaiters();
1379 >        if ((workerCounts >>> TOTAL_COUNT_SHIFT) < parallelism)
1380 >            addWorkerIfBelowTarget();
1381      }
1382  
1383      /**
1384       * Performs the given task, returning its result upon completion.
1293     * If the caller is already engaged in a fork/join computation in
1294     * the current pool, this method is equivalent in effect to
1295     * {@link ForkJoinTask#invoke}.
1385       *
1386       * @param task the task
1387       * @return the task's result
# Line 1307 | Line 1396 | public class ForkJoinPool extends Abstra
1396  
1397      /**
1398       * Arranges for (asynchronous) execution of the given task.
1310     * If the caller is already engaged in a fork/join computation in
1311     * the current pool, this method is equivalent in effect to
1312     * {@link ForkJoinTask#fork}.
1399       *
1400       * @param task the task
1401       * @throws NullPointerException if the task is null
# Line 1338 | Line 1424 | public class ForkJoinPool extends Abstra
1424  
1425      /**
1426       * Submits a ForkJoinTask for execution.
1341     * If the caller is already engaged in a fork/join computation in
1342     * the current pool, this method is equivalent in effect to
1343     * {@link ForkJoinTask#fork}.
1427       *
1428       * @param task the task to submit
1429       * @return the task
# Line 1532 | Line 1615 | public class ForkJoinPool extends Abstra
1615      public long getQueuedTaskCount() {
1616          long count = 0;
1617          ForkJoinWorkerThread[] ws = workers;
1618 <        int nws = ws.length;
1619 <        for (int i = 0; i < nws; ++i) {
1618 >        int n = ws.length;
1619 >        for (int i = 0; i < n; ++i) {
1620              ForkJoinWorkerThread w = ws[i];
1621              if (w != null)
1622                  count += w.getQueueSize();
# Line 1591 | Line 1674 | public class ForkJoinPool extends Abstra
1674       * @return the number of elements transferred
1675       */
1676      protected int drainTasksTo(Collection<? super ForkJoinTask<?>> c) {
1677 <        int n = submissionQueue.drainTo(c);
1595 <        ForkJoinWorkerThread[] ws = workers;
1596 <        int nws = ws.length;
1597 <        for (int i = 0; i < nws; ++i) {
1598 <            ForkJoinWorkerThread w = ws[i];
1599 <            if (w != null)
1600 <                n += w.drainTasksTo(c);
1601 <        }
1602 <        return n;
1603 <    }
1604 <
1605 <    /**
1606 <     * Returns count of total parks by existing workers.
1607 <     * Used during development only since not meaningful to users.
1608 <     */
1609 <    private int collectParkCount() {
1610 <        int count = 0;
1677 >        int count = submissionQueue.drainTo(c);
1678          ForkJoinWorkerThread[] ws = workers;
1679 <        int nws = ws.length;
1680 <        for (int i = 0; i < nws; ++i) {
1679 >        int n = ws.length;
1680 >        for (int i = 0; i < n; ++i) {
1681              ForkJoinWorkerThread w = ws[i];
1682              if (w != null)
1683 <                count += w.parkCount;
1683 >                count += w.drainTasksTo(c);
1684          }
1685          return count;
1686      }
# Line 1635 | Line 1702 | public class ForkJoinPool extends Abstra
1702          int pc = parallelism;
1703          int rs = runState;
1704          int ac = rs & ACTIVE_COUNT_MASK;
1638        //        int pk = collectParkCount();
1705          return super.toString() +
1706              "[" + runLevelToString(rs) +
1707              ", parallelism = " + pc +
# Line 1645 | Line 1711 | public class ForkJoinPool extends Abstra
1711              ", steals = " + st +
1712              ", tasks = " + qt +
1713              ", submissions = " + qs +
1648            //            ", parks = " + pk +
1714              "]";
1715      }
1716  
# Line 1752 | Line 1817 | public class ForkJoinPool extends Abstra
1817       * Interface for extending managed parallelism for tasks running
1818       * in {@link ForkJoinPool}s.
1819       *
1820 <     * <p>A {@code ManagedBlocker} provides two methods.
1821 <     * Method {@code isReleasable} must return {@code true} if
1822 <     * blocking is not necessary. Method {@code block} blocks the
1823 <     * current thread if necessary (perhaps internally invoking
1824 <     * {@code isReleasable} before actually blocking).
1820 >     * <p>A {@code ManagedBlocker} provides two methods.  Method
1821 >     * {@code isReleasable} must return {@code true} if blocking is
1822 >     * not necessary. Method {@code block} blocks the current thread
1823 >     * if necessary (perhaps internally invoking {@code isReleasable}
1824 >     * before actually blocking). The unusual methods in this API
1825 >     * accommodate synchronizers that may, but don't usually, block
1826 >     * for long periods. Similarly, they allow more efficient internal
1827 >     * handling of cases in which additional workers may be, but
1828 >     * usually are not, needed to ensure sufficient parallelism.
1829 >     * Toward this end, implementations of method {@code isReleasable}
1830 >     * must be amenable to repeated invocation.
1831       *
1832       * <p>For example, here is a ManagedBlocker based on a
1833       * ReentrantLock:
# Line 1774 | Line 1845 | public class ForkJoinPool extends Abstra
1845       *     return hasLock || (hasLock = lock.tryLock());
1846       *   }
1847       * }}</pre>
1848 +     *
1849 +     * <p>Here is a class that possibly blocks waiting for an
1850 +     * item on a given queue:
1851 +     *  <pre> {@code
1852 +     * class QueueTaker<E> implements ManagedBlocker {
1853 +     *   final BlockingQueue<E> queue;
1854 +     *   volatile E item = null;
1855 +     *   QueueTaker(BlockingQueue<E> q) { this.queue = q; }
1856 +     *   public boolean block() throws InterruptedException {
1857 +     *     if (item == null)
1858 +     *       item = queue.take();
1859 +     *     return true;
1860 +     *   }
1861 +     *   public boolean isReleasable() {
1862 +     *     return item != null || (item = queue.poll()) != null;
1863 +     *   }
1864 +     *   public E getItem() { // call after pool.managedBlock completes
1865 +     *     return item;
1866 +     *   }
1867 +     * }}</pre>
1868       */
1869      public static interface ManagedBlocker {
1870          /**
# Line 1816 | Line 1907 | public class ForkJoinPool extends Abstra
1907      public static void managedBlock(ManagedBlocker blocker)
1908          throws InterruptedException {
1909          Thread t = Thread.currentThread();
1910 <        if (t instanceof ForkJoinWorkerThread)
1911 <            ((ForkJoinWorkerThread) t).pool.awaitBlocker(blocker);
1910 >        if (t instanceof ForkJoinWorkerThread) {
1911 >            ForkJoinWorkerThread w = (ForkJoinWorkerThread) t;
1912 >            w.pool.awaitBlocker(blocker);
1913 >        }
1914          else {
1915              do {} while (!blocker.isReleasable() && !blocker.block());
1916          }
# Line 1848 | Line 1941 | public class ForkJoinPool extends Abstra
1941          objectFieldOffset("eventWaiters",ForkJoinPool.class);
1942      private static final long stealCountOffset =
1943          objectFieldOffset("stealCount",ForkJoinPool.class);
1944 +    private static final long spareWaitersOffset =
1945 +        objectFieldOffset("spareWaiters",ForkJoinPool.class);
1946  
1947      private static long objectFieldOffset(String field, Class<?> klazz) {
1948          try {

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines