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.58 by dl, Fri Jul 23 13:07:43 2010 UTC vs.
Revision 1.64 by dl, Tue Aug 17 18:30:32 2010 UTC

# Line 52 | Line 52 | import java.util.concurrent.CountDownLat
52   * convenient form for informal monitoring.
53   *
54   * <p> As is the case with other ExecutorServices, there are three
55 < * main task execution methods summarized in the follwoing
55 > * main task execution methods summarized in the following
56   * table. These are designed to be used by clients not already engaged
57   * in fork/join computations in the current pool.  The main forms of
58   * these methods accept instances of {@code ForkJoinTask}, but
# Line 60 | Line 60 | import java.util.concurrent.CountDownLat
60   * Runnable}- or {@code Callable}- based activities as well.  However,
61   * tasks that are already executing in a pool should normally
62   * <em>NOT</em> use these pool execution methods, but instead use the
63 < * within-computation forms listed in the table.
63 > * within-computation forms listed in the table.
64   *
65   * <table BORDER CELLPADDING=3 CELLSPACING=1>
66   *  <tr>
# Line 84 | Line 84 | import java.util.concurrent.CountDownLat
84   *    <td> {@link ForkJoinTask#fork} (ForkJoinTasks <em>are</em> Futures)</td>
85   *  </tr>
86   * </table>
87 < *
87 > *
88   * <p><b>Sample Usage.</b> Normally a single {@code ForkJoinPool} is
89   * used for all parallel task execution in a program or subsystem.
90   * Otherwise, use would not usually outweigh the construction and
# 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 138 | Line 138 | public class ForkJoinPool extends Abstra
138       * cache pollution effects.)
139       *
140       * Beyond work-stealing support and essential bookkeeping, the
141 <     * main responsibility of this framework is to arrange tactics for
142 <     * when one worker is waiting to join a task stolen (or always
143 <     * held by) another.  Becauae we are multiplexing many tasks on to
144 <     * a pool of workers, we can't just let them block (as in
145 <     * Thread.join).  We also cannot just reassign the joiner's
146 <     * run-time stack with another and replace it later, which would
147 <     * be a form of "continuation", that even if possible is not
148 <     * necessarily a good idea. Given that the creation costs of most
149 <     * threads on most systems mainly surrounds setting up runtime
150 <     * stacks, thread creation and switching is usually not much more
151 <     * expensive than stack creation and switching, and is more
152 <     * flexible). Instead we combine two tactics:
141 >     * main responsibility of this framework is to take actions when
142 >     * one worker is waiting to join a task stolen (or always held by)
143 >     * another.  Becauae we are multiplexing many tasks on to a pool
144 >     * of workers, we can't just let them block (as in Thread.join).
145 >     * We also cannot just reassign the joiner's run-time stack with
146 >     * another and replace it later, which would be a form of
147 >     * "continuation", that even if possible is not necessarily a good
148 >     * idea. Given that the creation costs of most threads on most
149 >     * systems mainly surrounds setting up runtime stacks, thread
150 >     * creation and switching is usually not much more expensive than
151 >     * stack creation and switching, and is more flexible). Instead we
152 >     * combine two tactics:
153       *
154 <     *   1. Arranging for the joiner to execute some task that it
154 >     *   Helping: Arranging for the joiner to execute some task that it
155       *      would be running if the steal had not occurred.  Method
156       *      ForkJoinWorkerThread.helpJoinTask tracks joining->stealing
157       *      links to try to find such a task.
158       *
159 <     *   2. Unless there are already enough live threads, creating or
160 <     *      or re-activating a spare thread to compensate for the
161 <     *      (blocked) joiner until it unblocks.  Spares then suspend
162 <     *      at their next opportunity or eventually die if unused for
163 <     *      too long.  See below and the internal documentation
164 <     *      for tryAwaitJoin for more details about compensation
165 <     *      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 option (1) so uses a
175 <     * special version of (2) 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 497 | Line 535 | public class ForkJoinPool extends Abstra
535       * making decisions about creating and suspending spare
536       * threads. Updated only by CAS. Note that adding a new worker
537       * requires incrementing both counts, since workers start off in
538 <     * running state.  This field is also used for memory-fencing
501 <     * configuration parameters.
538 >     * running state.
539       */
540      private volatile int workerCounts;
541  
# Line 530 | 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;
579          do {} while (!UNSAFE.compareAndSwapInt(this, workerCountsOffset,
580 <                                               c = workerCounts,
580 >                                               c = workerCounts,
581                                                 c + ONE_RUNNING));
582      }
583  
# Line 555 | 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 572 | 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 582 | 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 611 | 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 650 | 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;
# Line 658 | Line 718 | public class ForkJoinPool extends Abstra
718              w = factory.newThread(this);
719          } finally { // Adjust on either null or exceptional factory return
720              if (w == null) {
721 <                onWorkerCreationFailure();
722 <                return null;
721 >                decrementWorkerCounts(ONE_RUNNING, ONE_TOTAL);
722 >                tryTerminate(false); // in case of failure during shutdown
723              }
724          }
725 <        w.start(recordWorker(w), ueh);
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 <            if ((wc >>> TOTAL_COUNT_SHIFT) == 0)
743 <                Thread.yield(); // wait for other counts to settle
744 <            else if (UNSAFE.compareAndSwapInt(this, workerCountsOffset, wc,
745 <                                              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 and/or resumes enough workers to establish target
774 <     * parallelism, giving up if terminating or addWorker fails
773 >     * Tries to advance eventCount and releases waiters. Called only
774 >     * from workers.
775 >     */
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 <     * TODO: recast this to support lazier creation and automated
689 <     * parallelism maintenance
788 >     * @param w the calling worker thread
789       */
790 <    private void ensureEnoughWorkers() {
791 <        for (;;) {
792 <            int pc = parallelism;
793 <            int wc = workerCounts;
794 <            int rc = wc & RUNNING_COUNT_MASK;
795 <            int tc = wc >>> TOTAL_COUNT_SHIFT;
796 <            if (tc < pc) {
797 <                if (runState == TERMINATING ||
798 <                    (UNSAFE.compareAndSwapInt
799 <                     (this, workerCountsOffset,
800 <                      wc, wc + (ONE_RUNNING|ONE_TOTAL)) &&
702 <                     addWorker() == null))
703 <                    break;
704 <            }
705 <            else if (tc > pc && rc < pc &&
706 <                     tc > (runState & ACTIVE_COUNT_MASK)) {
707 <                ForkJoinWorkerThread spare = null;
708 <                ForkJoinWorkerThread[] ws = workers;
709 <                int nws = ws.length;
710 <                for (int i = 0; i < nws; ++i) {
711 <                    ForkJoinWorkerThread w = ws[i];
712 <                    if (w != null && w.isSuspended()) {
713 <                        if ((workerCounts & RUNNING_COUNT_MASK) > pc ||
714 <                            runState == TERMINATING)
715 <                            return;
716 <                        if (w.tryResumeSpare())
717 <                            incrementRunningCount();
718 <                        break;
719 <                    }
720 <                }
721 <            }
722 <            else
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 <            if (rc - nr < 0 || (wc >>> TOTAL_COUNT_SHIFT) == 0)
849 <                Thread.yield(); // back off if waiting for other updates
850 <            else if (UNSAFE.compareAndSwapInt(this, workerCountsOffset,
851 <                                              wc, wc - unit))
852 <                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 <
859 <        accumulateStealCount(w); // collect final count
860 <        if (!tryTerminate(false))
861 <            ensureEnoughWorkers();
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 <    // Waiting for and signalling events
875 >    // Maintaining spares
876  
877      /**
878 <     * Releases workers blocked on a count not equal to current count.
765 <     * @return true if any released
878 >     * Pushes worker onto the spare stack
879       */
880 <    private void releaseWaiters() {
881 <        long top;
882 <        while ((top = eventWaiters) != 0L) {
883 <            ForkJoinWorkerThread[] ws = workers;
771 <            int n = ws.length;
772 <            for (;;) {
773 <                int i = ((int)(top & WAITER_ID_MASK)) - 1;
774 <                if (i < 0 || (int)(top >>> EVENT_COUNT_SHIFT) == eventCount)
775 <                    return;
776 <                ForkJoinWorkerThread w;
777 <                if (i < n && (w = ws[i]) != null &&
778 <                    UNSAFE.compareAndSwapLong(this, eventWaitersOffset,
779 <                                              top, w.nextWaiter)) {
780 <                    LockSupport.unpark(w);
781 <                    top = eventWaiters;
782 <                }
783 <                else
784 <                    break;      // possibly stale; reread
785 <            }
786 <        }
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      /**
887 <     * Ensures eventCount on exit is different (mod 2^32) than on
888 <     * entry and wakes up all waiters
887 >     * Callback from oldest spare occasionally waking up.  Tries
888 >     * (once) to shutdown a spare. Same idea as tryShutdownWaiter.
889       */
890 <    private void signalEvent() {
891 <        int c;
892 <        do {} while (!UNSAFE.compareAndSwapInt(this, eventCountOffset,
893 <                                               c = eventCount, c+1));
894 <        releaseWaiters();
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 <     * Advances eventCount and releases waiters until interference by
907 <     * other releasing threads is detected.
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 <    final void signalWork() {
912 <        int c;
913 <        UNSAFE.compareAndSwapInt(this, eventCountOffset, c=eventCount, c+1);
914 <        long top;
915 <        while ((top = eventWaiters) != 0L) {
916 <            int ec = eventCount;
917 <            ForkJoinWorkerThread[] ws = workers;
918 <            int n = ws.length;
919 <            for (;;) {
920 <                int i = ((int)(top & WAITER_ID_MASK)) - 1;
921 <                if (i < 0 || (int)(top >>> EVENT_COUNT_SHIFT) == ec)
922 <                    return;
923 <                ForkJoinWorkerThread w;
924 <                if (i < n && (w = ws[i]) != null &&
925 <                    UNSAFE.compareAndSwapLong(this, eventWaitersOffset,
926 <                                              top, 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 <                    if (top != eventWaiters) // let someone else take over
932 <                        return;
823 <                }
824 <                else
825 <                    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 <     * If worker is inactive, blocks until terminating or event count
941 <     * advances from last value held by worker; in any case helps
833 <     * release others.
834 <     *
835 <     * @param w the calling worker thread
836 <     * @param retries the number of scans by caller failing to find work
837 <     * @return false if now too many threads running
940 >     * Adds one or more workers if needed to establish target parallelism.
941 >     * Retries upon contention.
942       */
943 <    private boolean eventSync(ForkJoinWorkerThread w, int retries) {
944 <        int wec = w.lastEventCount;
945 <        if (retries > 1) { // can only block after 2nd miss
946 <            long nextTop = (((long)wec << EVENT_COUNT_SHIFT) |
947 <                            ((long)(w.poolIndex + 1)));
948 <            long top;
949 <            while ((runState < SHUTDOWN || !tryTerminate(false)) &&
950 <                   (((int)(top = eventWaiters) & WAITER_ID_MASK) == 0 ||
847 <                    (int)(top >>> EVENT_COUNT_SHIFT) == wec) &&
848 <                   eventCount == wec) {
849 <                if (UNSAFE.compareAndSwapLong(this, eventWaitersOffset,
850 <                                              w.nextWaiter = top, nextTop)) {
851 <                    accumulateStealCount(w); // transfer steals while idle
852 <                    Thread.interrupted();    // clear/ignore interrupt
853 <                    while (eventCount == wec)
854 <                        w.doPark();
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;
856                }
952              }
858            wec = eventCount;
953          }
954 <        releaseWaiters();
955 <        int wc = workerCounts;
956 <        if ((wc & RUNNING_COUNT_MASK) <= parallelism) {
957 <            w.lastEventCount = wec;
958 <            return true;
954 >    }
955 >
956 >    /**
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 >    private void tryAddWorkerIfBusy(int wc) {
964 >        int tc, rc, rs;
965 >        int pc = parallelism;
966 >        if ((tc = wc >>> TOTAL_COUNT_SHIFT) < MAX_WORKERS &&
967 >            ((rc = wc & RUNNING_COUNT_MASK) == 0 ||
968 >             rc < pc - ((tc - pc) << 1)) &&
969 >            (rs = runState) < TERMINATING &&
970 >            (rs & ACTIVE_COUNT_MASK) == tc) {
971 >            // Since all workers busy, heuristically back off to let settle
972 >            Thread.yield();
973 >            if (eventWaiters == 0L && spareWaiters == 0 && // recheck
974 >                runState == rs && workerCounts == wc &&
975 >                UNSAFE.compareAndSwapInt(this, workerCountsOffset, wc,
976 >                                         wc + (ONE_RUNNING|ONE_TOTAL)))
977 >                addWorker();
978 >        }
979 >    }
980 >
981 >    /**
982 >     * Does at most one of:
983 >     *
984 >     * 1. Help wake up existing workers waiting for work via
985 >     *    releaseEventWaiters. (If any exist, then it doesn't
986 >     *    matter right now if under target parallelism level.)
987 >     *
988 >     * 2. If a spare exists, try (once) to resume it via tryResumeSpare.
989 >     *
990 >     * 3. If there are not enough total workers, add some
991 >     *    via addWorkerIfBelowTarget;
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          }
866        if (wec != w.lastEventCount) // back up if may re-wait
867            w.lastEventCount = wec - (wc >>> TOTAL_COUNT_SHIFT);
868        return false;
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 (active || eventSync(w, retries))
1051 <                    break;
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 <            else if (!(inactivate |= active) &&  // must inactivate to suspend
1055 <                UNSAFE.compareAndSwapInt(this, workerCountsOffset,
1056 <                                         wc, wc - ONE_RUNNING) &&
1057 <                !w.suspendAsSpare())             // false if trimmed
1058 <                break;
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 >                        if (w.isRunning())
1070 >                            misses = 1;        // don't re-sync
1071 >                        else
1072 >                            break;             // was killed while waiting
1073 >                    }
1074 >                    continue;
1075 >                }
1076 >                w.lastEventCount = ec;
1077 >            }
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. Returns void because caller must check
1089 <     * task status on return anyway.
919 <     *
920 <     * We allow blocking if:
921 <     *
922 <     * 1. There would still be at least as many running threads as
923 <     *    parallelism level if this thread blocks.
924 <     *
925 <     * 2. A spare is resumed to replace this worker. We tolerate
926 <     *    slop in the decision to replace if a spare is found without
927 <     *    first decrementing run count.  This may release too many,
928 <     *    but if so, the superfluous ones will re-suspend via
929 <     *    preStep().
930 <     *
931 <     * 3. After #spares repeated checks, there are no fewer than #spare
932 <     *    threads not running. We allow this slack to avoid hysteresis
933 <     *    and as a hedge against lag/uncertainty of running count
934 <     *    estimates when signalling or unblocking stalls.
935 <     *
936 <     * 4. All existing workers are busy (as rechecked via repeated
937 <     *    retries by caller) and a new spare is created.
938 <     *
939 <     * If none of the above hold, we try to escape out by
940 <     * re-incrementing count and returning to caller, which can retry
941 <     * 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
944     * @param retries if negative, then serve only as a precheck
945     *   that the thread can be replaced by a spare. Otherwise,
946     *   the number of repeated calls to this method returning busy
947     * @return true if the call must be retried because there
948     *   none of the blocking checks hold
1092       */
1093 <    final boolean tryAwaitJoin(ForkJoinTask<?> joinMe, int retries) {
1094 <        if (joinMe.status < 0) // precheck to prime loop
1095 <            return false;
1096 <        int pc = parallelism;
1097 <        boolean running = true; // false when running count decremented
1098 <        outer:for (;;) {
1099 <            int wc = workerCounts;
1100 <            int rc = wc & RUNNING_COUNT_MASK;
1101 <            int tc = wc >>> TOTAL_COUNT_SHIFT;
1102 <            if (running) { // replace with spare or decrement count
1103 <                if (rc <= pc && tc > pc &&
1104 <                    (retries > 0 || tc > (runState & ACTIVE_COUNT_MASK))) {
1105 <                    ForkJoinWorkerThread[] ws = workers;
963 <                    int nws = ws.length;
964 <                    for (int i = 0; i < nws; ++i) { // search for spare
965 <                        ForkJoinWorkerThread w = ws[i];
966 <                        if (w != null) {
967 <                            if (joinMe.status < 0)
968 <                                return false;
969 <                            if (w.isSuspended()) {
970 <                                if ((workerCounts & RUNNING_COUNT_MASK)>=pc &&
971 <                                    w.tryResumeSpare()) {
972 <                                    running = false;
973 <                                    break outer;
974 <                                }
975 <                                continue outer; // rescan
976 <                            }
977 <                        }
978 <                    }
979 <                }
980 <                if (retries < 0 || // < 0 means replacement check only
981 <                    rc == 0 || joinMe.status < 0 || workerCounts != wc ||
982 <                    !UNSAFE.compareAndSwapInt(this, workerCountsOffset,
983 <                                              wc, wc - ONE_RUNNING))
984 <                    return false; // done or inconsistent or contended
985 <                running = false;
986 <                if (rc > pc)
987 <                    break;
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 <                if (rc >= pc || joinMe.status < 0)
1109 <                    break;
1110 <                int sc = tc - pc + 1; // = spare threads, plus the one to add
1111 <                if (retries > sc) {
1112 <                    if (rc > 0 && rc >= pc - sc) // allow slack
1113 <                        break;
1114 <                    if (tc < MAX_THREADS &&
1115 <                        tc == (runState & ACTIVE_COUNT_MASK) &&
1116 <                        workerCounts == wc &&
1117 <                        UNSAFE.compareAndSwapInt(this, workerCountsOffset, wc,
1000 <                                                 wc+(ONE_RUNNING|ONE_TOTAL))) {
1001 <                        addWorker();
1002 <                        break;
1003 <                    }
1004 <                }
1005 <                if (workerCounts == wc &&        // back out to allow rescan
1006 <                    UNSAFE.compareAndSwapInt (this, workerCountsOffset,
1007 <                                              wc, wc + ONE_RUNNING)) {
1008 <                    releaseWaiters();            // help others progress
1009 <                    return true;                 // let caller retry
1010 <                }
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          }
1013        // arrive here if can block
1014        joinMe.internalAwaitDone();
1015        int c;                      // to inline incrementRunningCount
1016        do {} while (!UNSAFE.compareAndSwapInt
1017                     (this, workerCountsOffset,
1018                      c = workerCounts, c + ONE_RUNNING));
1019        return false;
1120      }
1121  
1122      /**
1123 <     * Same idea as (and shares many code snippets with) tryAwaitJoin,
1024 <     * but self-contained because there are no caller retries.
1025 <     * 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 <        boolean done;
1128 <        if (done = blocker.isReleasable())
1129 <            return;
1130 <        int pc = parallelism;
1131 <        int retries = 0;
1132 <        boolean running = true; // false when running count decremented
1133 <        outer:for (;;) {
1134 <            int wc = workerCounts;
1135 <            int rc = wc & RUNNING_COUNT_MASK;
1038 <            int tc = wc >>> TOTAL_COUNT_SHIFT;
1039 <            if (running) {
1040 <                if (rc <= pc && tc > pc &&
1041 <                    (retries > 0 || tc > (runState & ACTIVE_COUNT_MASK))) {
1042 <                    ForkJoinWorkerThread[] ws = workers;
1043 <                    int nws = ws.length;
1044 <                    for (int i = 0; i < nws; ++i) {
1045 <                        ForkJoinWorkerThread w = ws[i];
1046 <                        if (w != null) {
1047 <                            if (done = blocker.isReleasable())
1048 <                                return;
1049 <                            if (w.isSuspended()) {
1050 <                                if ((workerCounts & RUNNING_COUNT_MASK)>=pc &&
1051 <                                    w.tryResumeSpare()) {
1052 <                                    running = false;
1053 <                                    break outer;
1054 <                                }
1055 <                                continue outer; // rescan
1056 <                            }
1057 <                        }
1058 <                    }
1059 <                }
1060 <                if (done = blocker.isReleasable())
1061 <                    return;
1062 <                if (rc == 0 || workerCounts != wc ||
1063 <                    !UNSAFE.compareAndSwapInt(this, workerCountsOffset,
1064 <                                              wc, wc - ONE_RUNNING))
1065 <                    continue;
1066 <                running = false;
1067 <                if (rc > pc)
1068 <                    break;
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 {
1138 <                if (rc >= pc || (done = blocker.isReleasable()))
1139 <                    break;
1140 <                int sc = tc - pc + 1;
1141 <                if (retries++ > sc) {
1142 <                    if (rc > 0 && rc >= pc - sc)
1143 <                        break;
1144 <                    if (tc < MAX_THREADS &&
1145 <                        tc == (runState & ACTIVE_COUNT_MASK) &&
1146 <                        workerCounts == wc &&
1147 <                        UNSAFE.compareAndSwapInt(this, workerCountsOffset, wc,
1148 <                                                 wc+(ONE_RUNNING|ONE_TOTAL))) {
1082 <                        addWorker();
1083 <                        break;
1084 <                    }
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 <                Thread.yield();
1087 <            }
1088 <        }
1089 <        
1090 <        try {
1091 <            if (!done)
1092 <                do {} while (!blocker.isReleasable() && !blocker.block());
1093 <        } finally {
1094 <            if (!running) {
1095 <                int c;
1096 <                do {} while (!UNSAFE.compareAndSwapInt
1097 <                             (this, workerCountsOffset,
1098 <                              c = workerCounts, c + ONE_RUNNING));
1150 >                break;
1151              }
1152          }
1153 <    }  
1153 >    }
1154  
1155      /**
1156       * Possibly initiates and/or completes termination.
# Line 1128 | 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 1152 | Line 1227 | public class ForkJoinPool extends Abstra
1227          }
1228      }
1229  
1155    /**
1156     * Sets all worker run states to at least shutdown,
1157     * also resuming suspended workers
1158     */
1159    private void shutdownWorkers() {
1160        ForkJoinWorkerThread[] ws = workers;
1161        int nws = ws.length;
1162        for (int i = 0; i < nws; ++i) {
1163            ForkJoinWorkerThread w = ws[i];
1164            if (w != null)
1165                w.shutdown();
1166        }
1167    }
1168
1169    /**
1170     * Clears out and cancels all locally queued tasks
1171     */
1172    private void cancelWorkerTasks() {
1173        ForkJoinWorkerThread[] ws = workers;
1174        int nws = ws.length;
1175        for (int i = 0; i < nws; ++i) {
1176            ForkJoinWorkerThread w = ws[i];
1177            if (w != null)
1178                w.cancelTasks();
1179        }
1180    }
1181
1182    /**
1183     * Unsticks all workers blocked on joins etc
1184     */
1185    private void interruptWorkers() {
1186        ForkJoinWorkerThread[] ws = workers;
1187        int nws = ws.length;
1188        for (int i = 0; i < nws; ++i) {
1189            ForkJoinWorkerThread w = ws[i];
1190            if (w != null && !w.isTerminated()) {
1191                try {
1192                    w.interrupt();
1193                } catch (SecurityException ignore) {
1194                }
1195            }
1196        }
1197    }
1198
1230      // misc support for ForkJoinWorkerThread
1231  
1232      /**
# Line 1206 | 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 1275 | Line 1310 | public class ForkJoinPool extends Abstra
1310       * use {@link java.lang.Runtime#availableProcessors}.
1311       * @param factory the factory for creating new threads. For default value,
1312       * use {@link #defaultForkJoinWorkerThreadFactory}.
1313 <     * @param handler the handler for internal worker threads that
1314 <     * terminate due to unrecoverable errors encountered while executing
1313 >     * @param handler the handler for internal worker threads that
1314 >     * terminate due to unrecoverable errors encountered while executing
1315       * tasks. For default value, use <code>null</code>.
1316 <     * @param asyncMode if true,
1316 >     * @param asyncMode if true,
1317       * establishes local first-in-first-out scheduling mode for forked
1318       * tasks that are never joined. This mode may be more appropriate
1319       * than default locally stack-based mode in applications in which
# Line 1292 | Line 1327 | public class ForkJoinPool extends Abstra
1327       *         because it does not hold {@link
1328       *         java.lang.RuntimePermission}{@code ("modifyThread")}
1329       */
1330 <    public ForkJoinPool(int parallelism,
1330 >    public ForkJoinPool(int parallelism,
1331                          ForkJoinWorkerThreadFactory factory,
1332                          Thread.UncaughtExceptionHandler handler,
1333                          boolean asyncMode) {
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 1318 | 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 1338 | Line 1373 | public class ForkJoinPool extends Abstra
1373          if (runState >= SHUTDOWN)
1374              throw new RejectedExecutionException();
1375          submissionQueue.offer(task);
1376 <        signalEvent();
1377 <        ensureEnoughWorkers();
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.
1347     * If the caller is already engaged in a fork/join computation in
1348     * the current pool, this method is equivalent in effect to
1349     * {@link ForkJoinTask#invoke}.
1385       *
1386       * @param task the task
1387       * @return the task's result
# Line 1361 | Line 1396 | public class ForkJoinPool extends Abstra
1396  
1397      /**
1398       * Arranges for (asynchronous) execution of the given task.
1364     * If the caller is already engaged in a fork/join computation in
1365     * the current pool, this method is equivalent in effect to
1366     * {@link ForkJoinTask#fork}.
1399       *
1400       * @param task the task
1401       * @throws NullPointerException if the task is null
# Line 1392 | Line 1424 | public class ForkJoinPool extends Abstra
1424  
1425      /**
1426       * Submits a ForkJoinTask for execution.
1395     * If the caller is already engaged in a fork/join computation in
1396     * the current pool, this method is equivalent in effect to
1397     * {@link ForkJoinTask#fork}.
1427       *
1428       * @param task the task to submit
1429       * @return the task
# Line 1586 | 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 1645 | 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);
1649 <        ForkJoinWorkerThread[] ws = workers;
1650 <        int nws = ws.length;
1651 <        for (int i = 0; i < nws; ++i) {
1652 <            ForkJoinWorkerThread w = ws[i];
1653 <            if (w != null)
1654 <                n += w.drainTasksTo(c);
1655 <        }
1656 <        return n;
1657 <    }
1658 <
1659 <    /**
1660 <     * Returns count of total parks by existing workers.
1661 <     * Used during development only since not meaningful to users.
1662 <     */
1663 <    private int collectParkCount() {
1664 <        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 1689 | Line 1702 | public class ForkJoinPool extends Abstra
1702          int pc = parallelism;
1703          int rs = runState;
1704          int ac = rs & ACTIVE_COUNT_MASK;
1692        //        int pk = collectParkCount();
1705          return super.toString() +
1706              "[" + runLevelToString(rs) +
1707              ", parallelism = " + pc +
# Line 1699 | Line 1711 | public class ForkJoinPool extends Abstra
1711              ", steals = " + st +
1712              ", tasks = " + qt +
1713              ", submissions = " + qs +
1702            //            ", parks = " + pk +
1714              "]";
1715      }
1716  
# Line 1806 | 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 1828 | 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 1870 | 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 1902 | 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