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.57 by dl, Wed Jul 7 19:52:31 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. To avoid inadvertant
64 < * cyclic task dependencies and to improve performance, task
65 < * submissions to the current pool by an ongoing fork/join
66 < * computations may be implicitly translated to the corresponding
67 < * ForkJoinTask forms.
63 > * within-computation forms listed in the table.
64   *
65   * <table BORDER CELLPADDING=3 CELLSPACING=1>
66   *  <tr>
# Line 88 | 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 113 | Line 109 | import java.util.concurrent.CountDownLat
109   * {@code IllegalArgumentException}.
110   *
111   * <p>This implementation rejects submitted tasks (that is, by throwing
112 < * {@link RejectedExecutionException}) only when the pool is shut down.
112 > * {@link RejectedExecutionException}) only when the pool is shut down
113 > * or internal resources have been exhausted.
114   *
115   * @since 1.7
116   * @author Doug Lea
# Line 140 | Line 137 | public class ForkJoinPool extends Abstra
137       * of tasks profit from cache affinities, but others are harmed by
138       * cache pollution effects.)
139       *
140 +     * Beyond work-stealing support and essential bookkeeping, the
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 +     *   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 +     *   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, 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 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
179       * other. We do not want to negate this by creating bottlenecks
180 <     * implementing the management responsibilities of this class. So
181 <     * we use a collection of techniques that avoid, reduce, or cope
182 <     * well with contention. These entail several instances of
183 <     * bit-packing into CASable fields to maintain only the minimally
184 <     * required atomicity. To enable such packing, we restrict maximum
185 <     * parallelism to (1<<15)-1 (enabling twice this to fit into a 16
186 <     * bit field), which is far in excess of normal operating range.
187 <     * Even though updates to some of these bookkeeping fields do
188 <     * sometimes contend with each other, they don't normally
189 <     * cache-contend with updates to others enough to warrant memory
190 <     * padding or isolation. So they are all held as fields of
191 <     * ForkJoinPool objects.  The main capabilities are as follows:
180 >     * implementing other management responsibilities. So we use a
181 >     * collection of techniques that avoid, reduce, or cope well with
182 >     * contention. These entail several instances of bit-packing into
183 >     * CASable fields to maintain only the minimally required
184 >     * atomicity. To enable such packing, we restrict maximum
185 >     * parallelism to (1<<15)-1 (enabling twice this (to accommodate
186 >     * unbalanced increments and decrements) to fit into a 16 bit
187 >     * field, which is far in excess of normal operating range.  Even
188 >     * though updates to some of these bookkeeping fields do sometimes
189 >     * contend with each other, they don't normally cache-contend with
190 >     * updates to others enough to warrant memory padding or
191 >     * isolation. So they are all held as fields of ForkJoinPool
192 >     * objects.  The main capabilities are as follows:
193       *
194       * 1. Creating and removing workers. Workers are recorded in the
195       * "workers" array. This is an array as opposed to some other data
# Line 170 | 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 179 | Line 227 | public class ForkJoinPool extends Abstra
227       * that are neither blocked nor artifically suspended) as well as
228       * the total number.  These two values are packed into one field,
229       * "workerCounts" because we need accurate snapshots when deciding
230 <     * to create, resume or suspend.  To support these decisions,
231 <     * updates to spare counts must be prospective (not
232 <     * retrospective).  For example, the running count is decremented
233 <     * before blocking by a thread about to block as a spare, but
186 <     * incremented by the thread about to unblock it. Updates upon
187 <     * resumption ofr threads blocking in awaitJoin or awaitBlocker
188 <     * cannot usually be prospective, so the running count is in
189 <     * general an upper bound of the number of productively running
190 <     * threads Updates to the workerCounts field sometimes transiently
191 <     * encounter a fair amount of contention when join dependencies
192 <     * are such that many threads block or unblock at about the same
193 <     * time. We alleviate this by sometimes performing an alternative
194 <     * action on contention like releasing waiters or locating spares.
230 >     * to create, resume or suspend.  Note however that the
231 >     * correspondance of these counts to reality is not guaranteed. In
232 >     * particular updates for unblocked threads may lag until they
233 >     * actually wake up.
234       *
235       * 3. Maintaining global run state. The run state of the pool
236       * consists of a runLevel (SHUTDOWN, TERMINATING, etc) similar to
# Line 220 | 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 231 | 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
241 <     * by other threads trying to release, and lets them take
242 <     * over. The net effect is a tree-like diffusion of signals, where
243 <     * released threads (and possibly others) help with unparks.  To
244 <     * further reduce contention effects a bit, failed CASes to
245 <     * 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       *
283       * 5. Managing suspension of extra workers. When a worker is about
284       * to block waiting for a join (or via ManagedBlockers), we may
285       * create a new thread to maintain parallelism level, or at least
286 <     * avoid starvation (see below). Usually, extra threads are needed
287 <     * for only very short periods, yet join dependencies are such
288 <     * that we sometimes need them in bursts. Rather than create new
289 <     * threads each time this happens, we suspend no-longer-needed
290 <     * extra ones as "spares". For most purposes, we don't distinguish
291 <     * "extra" spare threads from normal "core" threads: On each call
292 <     * to preStep (the only point at which we can do this) a worker
286 >     * avoid starvation. Usually, extra threads are needed for only
287 >     * very short periods, yet join dependencies are such that we
288 >     * sometimes need them in bursts. Rather than create new threads
289 >     * each time this happens, we suspend no-longer-needed extra ones
290 >     * as "spares". For most purposes, we don't distinguish "extra"
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 awaitJoin and awaitBlocker look
295 <     * for suspended threads to resume before considering creating a
296 <     * new replacement. We don't need a special data structure to
297 <     * maintain spares; simply scanning the workers array looking for
298 <     * worker.isSuspended() is fine because the calling thread is
265 <     * otherwise not doing anything useful anyway; we are at least as
266 <     * happy if after locating a spare, the caller doesn't actually
267 <     * block because the join is ready before we try to adjust and
268 <     * compensate.  Note that this is intrinsically racy.  One thread
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. The only
303 <     * effective difference between "extra" and "core" threads is that
304 <     * we allow the "extra" ones to time out and die if they are not
305 <     * resumed within a keep-alive interval of a few seconds. This is
306 <     * implemented mainly within ForkJoinWorkerThread, but requires
307 <     * some coordination (isTrimmed() -- meaning killed while
308 <     * suspended) to correctly maintain pool counts.
309 <     *
310 <     * 6. Deciding when to create new workers. The main dynamic
311 <     * control in this class is deciding when to create extra threads,
312 <     * in methods awaitJoin and awaitBlocker. We always need to create
313 <     * one when the number of running threads becomes zero. But
314 <     * because blocked joins are typically dependent, we don't
315 <     * necessarily need or want one-to-one replacement. Instead, we
316 <     * use a combination of heuristics that adds threads only when the
317 <     * pool appears to be approaching starvation.  These effectively
318 <     * reduce churn at the price of systematically undershooting
319 <     * target parallelism when many threads are blocked.  However,
320 <     * biasing toward undeshooting partially compensates for the above
321 <     * mechanics to suspend extra threads, that normally lead to
322 <     * overshoot because we can only suspend workers in-between
323 <     * top-level actions. It also better copes with the fact that some
324 <     * of the methods in this class tend to never become compiled (but
325 <     * are interpreted), so some components of the entire set of
326 <     * controls might execute many times faster than others. And
327 <     * similarly for cases where the apparent lack of work is just due
328 <     * to GC stalls and other transient system activity.
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 308 | 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 a few
352 <     * other coding oddities that help some methods perform reasonably
353 <     * even when interpreted (not compiled).
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 380 | 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 425 | 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_INDEX_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 452 | 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 461 | 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;
464    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 470 | 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
474 <     * configuration parameters.
538 >     * running state.
539       */
540      private volatile int workerCounts;
541  
# Line 503 | Line 567 | public class ForkJoinPool extends Abstra
567       */
568      private final int poolNumber;
569  
570 <    // utilities for updating fields
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 <    
583 >
584      /**
585       * Tries to decrement running count unless already zero
586       */
# Line 527 | Line 593 | public class ForkJoinPool extends Abstra
593      }
594  
595      /**
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 +    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 +    /**
627       * Tries incrementing active count; fails on contention.
628       * Called by workers before executing tasks.
629       *
# Line 535 | 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 545 | 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 574 | 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 613 | 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 621 | 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 <                UNSAFE.compareAndSwapInt(this, workerCountsOffset,
744 <                                         wc, 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          }
643        tryTerminate(false); // in case of failure during shutdown
770      }
771  
772      /**
773 <     * Create 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 <            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 <            ensureEnoughTotalWorkers();
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.
878 >     * Pushes worker onto the spare stack
879       */
880 <    private void releaseWaiters() {
881 <        long top;
882 <        int id;
883 <        while ((id = (int)((top = eventWaiters) & WAITER_INDEX_MASK)) > 0 &&
704 <               (int)(top >>> EVENT_COUNT_SHIFT) != eventCount) {
705 <            ForkJoinWorkerThread[] ws = workers;
706 <            ForkJoinWorkerThread w;
707 <            if (ws.length >= id && (w = ws[id - 1]) != null &&
708 <                UNSAFE.compareAndSwapLong(this, eventWaitersOffset,
709 <                                          top, w.nextWaiter))
710 <                LockSupport.unpark(w);
711 <        }
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 <        // EventCount CAS failures are OK -- any change in count suffices.
913 <        int ec;
914 <        UNSAFE.compareAndSwapInt(this, eventCountOffset, ec=eventCount, ec+1);
915 <        outer:for (;;) {
916 <            long top = eventWaiters;
917 <            ec = eventCount;
918 <            for (;;) {
919 <                ForkJoinWorkerThread[] ws; ForkJoinWorkerThread w;
920 <                int id = (int)(top & WAITER_INDEX_MASK);
921 <                if (id <= 0 || (int)(top >>> EVENT_COUNT_SHIFT) == ec)
922 <                    return;
923 <                if ((ws = workers).length < id || (w = ws[id - 1]) == null ||
924 <                    !UNSAFE.compareAndSwapLong(this, eventWaitersOffset,
925 <                                               top, top = w.nextWaiter))
926 <                    continue outer;      // possibly stale; reread
927 <                LockSupport.unpark(w);
928 <                if (top != eventWaiters) // let someone else take over
929 <                    return;
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 >                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
755 <     * release others.
756 <     *
757 <     * @param w the calling worker thread
940 >     * Adds one or more workers if needed to establish target parallelism.
941 >     * Retries upon contention.
942       */
943 <    private void eventSync(ForkJoinWorkerThread w) {
944 <        if (!w.active) {
945 <            int prev = w.lastEventCount;
946 <            long nextTop = (((long)prev << EVENT_COUNT_SHIFT) |
947 <                            ((long)(w.poolIndex + 1)));
948 <            long top;
949 <            while ((runState < SHUTDOWN || !tryTerminate(false)) &&
950 <                   (((int)(top = eventWaiters) & WAITER_INDEX_MASK) == 0 ||
767 <                    (int)(top >>> EVENT_COUNT_SHIFT) == prev) &&
768 <                   eventCount == prev) {
769 <                if (UNSAFE.compareAndSwapLong(this, eventWaitersOffset,
770 <                                              w.nextWaiter = top, nextTop)) {
771 <                    accumulateStealCount(w); // transfer steals while idle
772 <                    Thread.interrupted();    // clear/ignore interrupt
773 <                    while (eventCount == prev)
774 <                        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;
776                }
952              }
778            w.lastEventCount = eventCount;
953          }
954 <        releaseWaiters();
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 >        }
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 >     * 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 <     * * If the worker cannot find work, updates its active status to
789 <     * inactive and updates activeCount unless there is contention, in
790 <     * which case it may try again (either in this or a subsequent
791 <     * call).  Additionally, awaits the next task event and/or helps
792 <     * wake up other releasable waiters.
793 <     *
794 <     * * If there are too many running threads, suspends this worker
795 <     * (first forcing inactivation if necessary).  If it is not
796 <     * resumed before a keepAlive elapses, the worker may be "trimmed"
797 <     * -- killed while suspended within suspendAsSpare. Otherwise,
798 <     * upon resume it rechecks to make sure that it is still needed.
1034 >     * 5. Help reactivate other workers via helpMaintainParallelism
1035       *
1036       * @param w the worker
1037 <     * @param worked false if the worker scanned for work but didn't
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, boolean worked) {
1040 >    final void preStep(ForkJoinWorkerThread w, int misses) {
1041          boolean active = w.active;
1042 <        boolean inactivate = !worked & active;
1042 >        int pc = parallelism;
1043          for (;;) {
1044 <            if (inactivate) {
1045 <                int rs = runState;
1046 <                if (UNSAFE.compareAndSwapInt(this, runStateOffset,
1047 <                                             rs, rs - ONE_ACTIVE))
1048 <                    inactivate = active = w.active = false;
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 <            int wc = workerCounts;
1055 <            if ((wc & RUNNING_COUNT_MASK) <= parallelism) {
1056 <                if (!worked)
1057 <                    eventSync(w);
1058 <                return;
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 (!(inactivate |= active) &&  // must inactivate to suspend
1066 <                UNSAFE.compareAndSwapInt(this, workerCountsOffset,
1067 <                                         wc, wc - ONE_RUNNING) &&
1068 <                !w.suspendAsSpare())        // false if trimmed
1069 <                return;
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 <     * Tries to decrement running count, and if so, possibly creates
1086 <     * or resumes compensating threads before blocking on task joinMe.
1087 <     * This code is sprawled out with manual inlining to evade some
1088 <     * JIT oddities.
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
835     * @return task status on exit
1092       */
1093 <    final int tryAwaitJoin(ForkJoinTask<?> joinMe) {
1094 <        int cw = workerCounts; // read now to spoil CAS if counts change as ...
1095 <        releaseWaiters();      // ... a byproduct of releaseWaiters
1096 <        int stat = joinMe.status;
1097 <        if (stat >= 0 && // inline variant of tryDecrementRunningCount
1098 <            (cw & RUNNING_COUNT_MASK) > 0 &&
1099 <            UNSAFE.compareAndSwapInt(this, workerCountsOffset,
1100 <                                     cw, cw - ONE_RUNNING)) {
1101 <            int pc = parallelism;
1102 <            int scans = 0;  // to require confirming passes to add threads
1103 <            outer: while ((workerCounts & RUNNING_COUNT_MASK) < pc) {
1104 <                if ((stat = joinMe.status) < 0)
1105 <                    break;
1106 <                ForkJoinWorkerThread spare = null;
1107 <                ForkJoinWorkerThread[] ws = workers;
1108 <                int nws = ws.length;
1109 <                for (int i = 0; i < nws; ++i) {
1110 <                    ForkJoinWorkerThread w = ws[i];
1111 <                    if (w != null && w.isSuspended()) {
1112 <                        spare = w;
1113 <                        break;
1114 <                    }
1115 <                }
1116 <                if ((stat = joinMe.status) < 0) // recheck to narrow race
1117 <                    break;
862 <                int wc = workerCounts;
863 <                int rc = wc & RUNNING_COUNT_MASK;
864 <                if (rc >= pc)
865 <                    break;
866 <                if (spare != null) {
867 <                    if (spare.tryUnsuspend()) {
868 <                        int c; // inline incrementRunningCount
869 <                        do {} while (!UNSAFE.compareAndSwapInt
870 <                                     (this, workerCountsOffset,
871 <                                      c = workerCounts, c + ONE_RUNNING));
872 <                        LockSupport.unpark(spare);
873 <                        break;
874 <                    }
875 <                    continue;
876 <                }
877 <                int tc = wc >>> TOTAL_COUNT_SHIFT;
878 <                int sc = tc - pc;
879 <                if (rc > 0) {
880 <                    int p = pc;
881 <                    int s = sc;
882 <                    while (s-- >= 0) { // try keeping 3/4 live
883 <                        if (rc > (p -= (p >>> 2) + 1))
884 <                            break outer;
885 <                    }
886 <                }
887 <                if (scans++ > sc && tc < MAX_THREADS &&
888 <                    UNSAFE.compareAndSwapInt(this, workerCountsOffset, wc,
889 <                                             wc + (ONE_RUNNING|ONE_TOTAL))) {
890 <                    addWorker();
891 <                    break;
892 <                }
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
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              }
894            if (stat >= 0)
895                stat = joinMe.internalAwaitDone();
896            int c; // inline incrementRunningCount
897            do {} while (!UNSAFE.compareAndSwapInt
898                         (this, workerCountsOffset,
899                          c = workerCounts, c + ONE_RUNNING));
1119          }
901        return stat;
1120      }
1121  
1122      /**
1123 <     * Same idea as (and mostly pasted from) tryAwaitJoin, but
906 <     * self-contained
1123 >     * Same idea as awaitJoin, but no helping
1124       */
1125      final void awaitBlocker(ManagedBlocker blocker)
1126          throws InterruptedException {
1127 <        for (;;) {
1128 <            if (blocker.isReleasable())
1129 <                return;
1130 <            int cw = workerCounts;
1131 <            releaseWaiters();
1132 <            if ((cw & RUNNING_COUNT_MASK) > 0 &&
1133 <                UNSAFE.compareAndSwapInt(this, workerCountsOffset,
1134 <                                         cw, cw - ONE_RUNNING))
1135 <                break;
919 <        }
920 <        boolean done = false;
921 <        int pc = parallelism;
922 <        int scans = 0;
923 <        outer: while ((workerCounts & RUNNING_COUNT_MASK) < pc) {
924 <            if (done = blocker.isReleasable())
925 <                break;
926 <            ForkJoinWorkerThread spare = null;
927 <            ForkJoinWorkerThread[] ws = workers;
928 <            int nws = ws.length;
929 <            for (int i = 0; i < nws; ++i) {
930 <                ForkJoinWorkerThread w = ws[i];
931 <                if (w != null && w.isSuspended()) {
932 <                    spare = w;
933 <                    break;
934 <                }
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 <            if (done = blocker.isReleasable())
1138 <                break;
1139 <            int wc = workerCounts;
1140 <            int rc = wc & RUNNING_COUNT_MASK;
1141 <            if (rc >= pc)
1142 <                break;
1143 <            if (spare != null) {
1144 <                if (spare.tryUnsuspend()) {
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));
948                    LockSupport.unpark(spare);
949                    break;
950                }
951                continue;
952            }
953            int tc = wc >>> TOTAL_COUNT_SHIFT;
954            int sc = tc - pc;
955            if (rc > 0) {
956                int p = pc;
957                int s = sc;
958                while (s-- >= 0) {
959                    if (rc > (p -= (p >>> 2) + 1))
960                        break outer;
1149                  }
962            }
963            if (scans++ > sc && tc < MAX_THREADS &&
964                UNSAFE.compareAndSwapInt(this, workerCountsOffset, wc,
965                                         wc + (ONE_RUNNING|ONE_TOTAL))) {
966                addWorker();
1150                  break;
1151              }
1152          }
1153 <        try {
971 <            if (!done)
972 <                do {} while (!blocker.isReleasable() &&
973 <                             !blocker.block());
974 <        } finally {
975 <            int c;
976 <            do {} while (!UNSAFE.compareAndSwapInt
977 <                         (this, workerCountsOffset,
978 <                          c = workerCounts, c + ONE_RUNNING));
979 <        }
980 <    }  
1153 >    }
1154  
1155      /**
1156       * Possibly initiates and/or completes termination.
# Line 1007 | 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 1031 | Line 1227 | public class ForkJoinPool extends Abstra
1227          }
1228      }
1229  
1034    /**
1035     * Sets all worker run states to at least shutdown,
1036     * also resuming suspended workers
1037     */
1038    private void shutdownWorkers() {
1039        ForkJoinWorkerThread[] ws = workers;
1040        int nws = ws.length;
1041        for (int i = 0; i < nws; ++i) {
1042            ForkJoinWorkerThread w = ws[i];
1043            if (w != null)
1044                w.shutdown();
1045        }
1046    }
1047
1048    /**
1049     * Clears out and cancels all locally queued tasks
1050     */
1051    private void cancelWorkerTasks() {
1052        ForkJoinWorkerThread[] ws = workers;
1053        int nws = ws.length;
1054        for (int i = 0; i < nws; ++i) {
1055            ForkJoinWorkerThread w = ws[i];
1056            if (w != null)
1057                w.cancelTasks();
1058        }
1059    }
1060
1061    /**
1062     * Unsticks all workers blocked on joins etc
1063     */
1064    private void interruptWorkers() {
1065        ForkJoinWorkerThread[] ws = workers;
1066        int nws = ws.length;
1067        for (int i = 0; i < nws; ++i) {
1068            ForkJoinWorkerThread w = ws[i];
1069            if (w != null && !w.isTerminated()) {
1070                try {
1071                    w.interrupt();
1072                } catch (SecurityException ignore) {
1073                }
1074            }
1075        }
1076    }
1077
1230      // misc support for ForkJoinWorkerThread
1231  
1232      /**
# Line 1085 | 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 1103 | Line 1259 | public class ForkJoinPool extends Abstra
1259       * active thread.
1260       */
1261      final int idlePerActive() {
1262 <        int pc = parallelism; // use targeted parallelism, not rc
1262 >        int pc = parallelism; // use parallelism, not rc
1263          int ac = runState;    // no mask -- artifically boosts during shutdown
1264          // Use exact results for small values, saturate past 4
1265          return pc <= ac? 0 : pc >>> 1 <= ac? 1 : pc >>> 2 <= ac? 3 : pc >>> 3;
# Line 1154 | 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 1171 | 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 1197 | 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 1216 | Line 1372 | public class ForkJoinPool extends Abstra
1372              throw new NullPointerException();
1373          if (runState >= SHUTDOWN)
1374              throw new RejectedExecutionException();
1375 <        // Convert submissions to current pool into forks
1376 <        Thread t = Thread.currentThread();
1377 <        ForkJoinWorkerThread w;
1378 <        if ((t instanceof ForkJoinWorkerThread) &&
1379 <            (w = (ForkJoinWorkerThread) t).pool == this)
1380 <            w.pushTask(task);
1225 <        else {
1226 <            submissionQueue.offer(task);
1227 <            signalEvent();
1228 <            ensureEnoughTotalWorkers();
1229 <        }
1375 >        submissionQueue.offer(task);
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.
1234     * If the caller is already engaged in a fork/join computation in
1235     * the current pool, this method is equivalent in effect to
1236     * {@link ForkJoinTask#invoke}.
1385       *
1386       * @param task the task
1387       * @return the task's result
# Line 1248 | Line 1396 | public class ForkJoinPool extends Abstra
1396  
1397      /**
1398       * Arranges for (asynchronous) execution of the given task.
1251     * If the caller is already engaged in a fork/join computation in
1252     * the current pool, this method is equivalent in effect to
1253     * {@link ForkJoinTask#fork}.
1399       *
1400       * @param task the task
1401       * @throws NullPointerException if the task is null
# Line 1279 | Line 1424 | public class ForkJoinPool extends Abstra
1424  
1425      /**
1426       * Submits a ForkJoinTask for execution.
1282     * If the caller is already engaged in a fork/join computation in
1283     * the current pool, this method is equivalent in effect to
1284     * {@link ForkJoinTask#fork}.
1427       *
1428       * @param task the task to submit
1429       * @return the task
# Line 1473 | 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 1532 | 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);
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 <                n += w.drainTasksTo(c);
1542 <        }
1543 <        return n;
1544 <    }
1545 <
1546 <    /**
1547 <     * Returns count of total parks by existing workers.
1548 <     * Used during development only since not meaningful to users.
1549 <     */
1550 <    private int collectParkCount() {
1551 <        int count = 0;
1552 <        ForkJoinWorkerThread[] ws = workers;
1553 <        int nws = ws.length;
1554 <        for (int i = 0; i < nws; ++i) {
1555 <            ForkJoinWorkerThread w = ws[i];
1556 <            if (w != null)
1557 <                count += w.parkCount;
1683 >                count += w.drainTasksTo(c);
1684          }
1685          return count;
1686      }
# Line 1576 | Line 1702 | public class ForkJoinPool extends Abstra
1702          int pc = parallelism;
1703          int rs = runState;
1704          int ac = rs & ACTIVE_COUNT_MASK;
1579        //        int pk = collectParkCount();
1705          return super.toString() +
1706              "[" + runLevelToString(rs) +
1707              ", parallelism = " + pc +
# Line 1586 | Line 1711 | public class ForkJoinPool extends Abstra
1711              ", steals = " + st +
1712              ", tasks = " + qt +
1713              ", submissions = " + qs +
1589            //            ", parks = " + pk +
1714              "]";
1715      }
1716  
# Line 1693 | 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 1715 | 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 1757 | 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 1789 | 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