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.2 by dl, Wed Jan 7 16:07:37 2009 UTC vs.
Revision 1.54 by dl, Sun Apr 18 12:51:18 2010 UTC

# Line 5 | Line 5
5   */
6  
7   package jsr166y;
8 < import java.util.*;
8 >
9   import java.util.concurrent.*;
10 < import java.util.concurrent.locks.*;
11 < import java.util.concurrent.atomic.*;
12 < import sun.misc.Unsafe;
13 < import java.lang.reflect.*;
10 >
11 > import java.util.ArrayList;
12 > import java.util.Arrays;
13 > import java.util.Collection;
14 > import java.util.Collections;
15 > import java.util.List;
16 > import java.util.concurrent.locks.LockSupport;
17 > import java.util.concurrent.locks.ReentrantLock;
18 > import java.util.concurrent.atomic.AtomicInteger;
19 > import java.util.concurrent.CountDownLatch;
20  
21   /**
22 < * An {@link ExecutorService} for running {@link ForkJoinTask}s.  A
23 < * ForkJoinPool provides the entry point for submissions from
24 < * non-ForkJoinTasks, as well as management and monitoring operations.
25 < * Normally a single ForkJoinPool is used for a large number of
20 < * submitted tasks. Otherwise, use would not usually outweigh the
21 < * construction and bookkeeping overhead of creating a large set of
22 < * threads.
22 > * An {@link ExecutorService} for running {@link ForkJoinTask}s.
23 > * A {@code ForkJoinPool} provides the entry point for submissions
24 > * from non-{@code ForkJoinTask}s, as well as management and
25 > * monitoring operations.
26   *
27 < * <p>ForkJoinPools differ from other kinds of Executors mainly in
28 < * that they provide <em>work-stealing</em>: all threads in the pool
29 < * attempt to find and execute subtasks created by other active tasks
30 < * (eventually blocking if none exist). This makes them efficient when
31 < * most tasks spawn other subtasks (as do most ForkJoinTasks), as well
32 < * as the mixed execution of some plain Runnable- or Callable- based
33 < * activities along with ForkJoinTasks. Otherwise, other
34 < * ExecutorService implementations are typically more appropriate
35 < * choices.
27 > * <p>A {@code ForkJoinPool} differs from other kinds of {@link
28 > * ExecutorService} mainly by virtue of employing
29 > * <em>work-stealing</em>: all threads in the pool attempt to find and
30 > * execute subtasks created by other active tasks (eventually blocking
31 > * waiting for work if none exist). This enables efficient processing
32 > * when most tasks spawn other subtasks (as do most {@code
33 > * ForkJoinTask}s). A {@code ForkJoinPool} may also be used for mixed
34 > * execution of some plain {@code Runnable}- or {@code Callable}-
35 > * based activities along with {@code ForkJoinTask}s. When setting
36 > * {@linkplain #setAsyncMode async mode}, a {@code ForkJoinPool} may
37 > * also be appropriate for use with fine-grained tasks of any form
38 > * that are never joined. Otherwise, other {@code ExecutorService}
39 > * implementations are typically more appropriate choices.
40   *
41 < * <p>A ForkJoinPool may be constructed with a given parallelism level
42 < * (target pool size), which it attempts to maintain by dynamically
43 < * adding, suspending, or resuming threads, even if some tasks are
44 < * waiting to join others. However, no such adjustments are performed
45 < * in the face of blocked IO or other unmanaged synchronization. The
46 < * nested <code>ManagedBlocker</code> interface enables extension of
47 < * the kinds of synchronization accommodated.  The target parallelism
48 < * level may also be changed dynamically (<code>setParallelism</code>)
49 < * and dynamically thread construction can be limited using methods
50 < * <code>setMaximumPoolSize</code> and/or
51 < * <code>setMaintainsParallelism</code>.
41 > * <p>A {@code ForkJoinPool} is constructed with a given target
42 > * parallelism level; by default, equal to the number of available
43 > * processors. Unless configured otherwise via {@link
44 > * #setMaintainsParallelism}, the pool attempts to maintain this
45 > * number of active (or available) threads by dynamically adding,
46 > * suspending, or resuming internal worker threads, even if some tasks
47 > * are stalled waiting to join others. However, no such adjustments
48 > * are performed in the face of blocked IO or other unmanaged
49 > * synchronization. The nested {@link ManagedBlocker} interface
50 > * enables extension of the kinds of synchronization accommodated.
51 > * The target parallelism level may also be changed dynamically
52 > * ({@link #setParallelism}). The total number of threads may be
53 > * limited using method {@link #setMaximumPoolSize}, in which case it
54 > * may become possible for the activities of a pool to stall due to
55 > * the lack of available threads to process new tasks. When the pool
56 > * is executing tasks, these and other configuration setting methods
57 > * may only gradually affect actual pool sizes. It is normally best
58 > * practice to invoke these methods only when the pool is known to be
59 > * quiescent.
60   *
61   * <p>In addition to execution and lifecycle control methods, this
62   * class provides status check methods (for example
63 < * <code>getStealCount</code>) that are intended to aid in developing,
63 > * {@link #getStealCount}) that are intended to aid in developing,
64   * tuning, and monitoring fork/join applications. Also, method
65 < * <code>toString</code> returns indications of pool state in a
65 > * {@link #toString} returns indications of pool state in a
66   * convenient form for informal monitoring.
67   *
68 + * <p><b>Sample Usage.</b> Normally a single {@code ForkJoinPool} is
69 + * used for all parallel task execution in a program or subsystem.
70 + * Otherwise, use would not usually outweigh the construction and
71 + * bookkeeping overhead of creating a large set of threads. For
72 + * example, a common pool could be used for the {@code SortTasks}
73 + * illustrated in {@link RecursiveAction}. Because {@code
74 + * ForkJoinPool} uses threads in {@linkplain java.lang.Thread#isDaemon
75 + * daemon} mode, there is typically no need to explicitly {@link
76 + * #shutdown} such a pool upon program exit.
77 + *
78 + * <pre>
79 + * static final ForkJoinPool mainPool = new ForkJoinPool();
80 + * ...
81 + * public void sort(long[] array) {
82 + *   mainPool.invoke(new SortTask(array, 0, array.length));
83 + * }
84 + * </pre>
85 + *
86   * <p><b>Implementation notes</b>: This implementation restricts the
87   * maximum number of running threads to 32767. Attempts to create
88 < * pools with greater than the maximum result in
89 < * IllegalArgumentExceptions.
88 > * pools with greater than the maximum number result in
89 > * {@code IllegalArgumentException}.
90 > *
91 > * <p>This implementation rejects submitted tasks (that is, by throwing
92 > * {@link RejectedExecutionException}) only when the pool is shut down.
93 > *
94 > * @since 1.7
95 > * @author Doug Lea
96   */
97   public class ForkJoinPool extends AbstractExecutorService {
98  
99      /*
100 <     * See the extended comments interspersed below for design,
101 <     * rationale, and walkthroughs.
100 >     * Implementation Overview
101 >     *
102 >     * This class provides the central bookkeeping and control for a
103 >     * set of worker threads: Submissions from non-FJ threads enter
104 >     * into a submission queue. Workers take these tasks and typically
105 >     * split them into subtasks that may be stolen by other workers.
106 >     * The main work-stealing mechanics implemented in class
107 >     * ForkJoinWorkerThread give first priority to processing tasks
108 >     * from their own queues (LIFO or FIFO, depending on mode), then
109 >     * to randomized FIFO steals of tasks in other worker queues, and
110 >     * lastly to new submissions. These mechanics do not consider
111 >     * affinities, loads, cache localities, etc, so rarely provide the
112 >     * best possible performance on a given machine, but portably
113 >     * provide good throughput by averaging over these factors.
114 >     * (Further, even if we did try to use such information, we do not
115 >     * usually have a basis for exploiting it. For example, some sets
116 >     * of tasks profit from cache affinities, but others are harmed by
117 >     * cache pollution effects.)
118 >     *
119 >     * The main throughput advantages of work-stealing stem from
120 >     * decentralized control -- workers mostly steal tasks from each
121 >     * other. We do not want to negate this by creating bottlenecks
122 >     * implementing the management responsibilities of this class. So
123 >     * we use a collection of techniques that avoid, reduce, or cope
124 >     * well with contention. These entail several instances of
125 >     * bit-packing into CASable fields to maintain only the minimally
126 >     * required atomicity. To enable such packing, we restrict maximum
127 >     * parallelism to (1<<15)-1 (enabling twice this to fit into a 16
128 >     * bit field), which is far in excess of normal operating range.
129 >     * Even though updates to some of these bookkeeping fields do
130 >     * sometimes contend with each other, they don't normally
131 >     * cache-contend with updates to others enough to warrant memory
132 >     * padding or isolation. So they are all held as fields of
133 >     * ForkJoinPool objects.  The main capabilities are as follows:
134 >     *
135 >     * 1. Creating and removing workers. Workers are recorded in the
136 >     * "workers" array. This is an array as opposed to some other data
137 >     * structure to support index-based random steals by workers.
138 >     * Updates to the array recording new workers and unrecording
139 >     * terminated ones are protected from each other by a lock
140 >     * (workerLock) but the array is otherwise concurrently readable,
141 >     * and accessed directly by workers. To simplify index-based
142 >     * operations, the array size is always a power of two, and all
143 >     * readers must tolerate null slots. Currently, all but the first
144 >     * worker thread creation is on-demand, triggered by task
145 >     * submissions, replacement of terminated workers, and/or
146 >     * compensation for blocked workers. However, all other support
147 >     * code is set up to work with other policies.
148 >     *
149 >     * 2. Bookkeeping for dynamically adding and removing workers. We
150 >     * maintain a given level of parallelism (or, if
151 >     * maintainsParallelism is false, at least avoid starvation). When
152 >     * some workers are known to be blocked (on joins or via
153 >     * ManagedBlocker), we may create or resume others to take their
154 >     * place until they unblock (see below). Implementing this
155 >     * requires counts of the number of "running" threads (i.e., those
156 >     * that are neither blocked nor artifically suspended) as well as
157 >     * the total number.  These two values are packed into one field,
158 >     * "workerCounts" because we need accurate snapshots when deciding
159 >     * to create, resume or suspend.  To support these decisions,
160 >     * updates must be prospective (not retrospective).  For example,
161 >     * the running count is decremented before blocking by a thread
162 >     * about to block, but incremented by the thread about to unblock
163 >     * it. (In a few cases, these prospective updates may need to be
164 >     * rolled back, for example when deciding to create a new worker
165 >     * but the thread factory fails or returns null. In these cases,
166 >     * we are no worse off wrt other decisions than we would be
167 >     * otherwise.)  Updates to the workerCounts field sometimes
168 >     * transiently encounter a fair amount of contention when join
169 >     * dependencies are such that many threads block or unblock at
170 >     * about the same time. We alleviate this by sometimes bundling
171 >     * updates (for example blocking one thread on join and resuming a
172 >     * spare cancel each other out), and in most other cases
173 >     * performing an alternative action (like releasing waiters and
174 >     * finding spares; see below) as a more productive form of
175 >     * backoff.
176 >     *
177 >     * 3. Maintaining global run state. The run state of the pool
178 >     * consists of a runLevel (SHUTDOWN, TERMINATING, etc) similar to
179 >     * those in other Executor implementations, as well as a count of
180 >     * "active" workers -- those that are, or soon will be, or
181 >     * recently were executing tasks. The runLevel and active count
182 >     * are packed together in order to correctly trigger shutdown and
183 >     * termination. Without care, active counts can be subject to very
184 >     * high contention.  We substantially reduce this contention by
185 >     * relaxing update rules.  A worker must claim active status
186 >     * prospectively, by activating if it sees that a submitted or
187 >     * stealable task exists (it may find after activating that the
188 >     * task no longer exists). It stays active while processing this
189 >     * task (if it exists) and any other local subtasks it produces,
190 >     * until it cannot find any other tasks. It then tries
191 >     * inactivating (see method preStep), but upon update contention
192 >     * instead scans for more tasks, later retrying inactivation if it
193 >     * doesn't find any.
194 >     *
195 >     * 4. Managing idle workers waiting for tasks. We cannot let
196 >     * workers spin indefinitely scanning for tasks when none are
197 >     * available. On the other hand, we must quickly prod them into
198 >     * action when new tasks are submitted or generated.  We
199 >     * park/unpark these idle workers using an event-count scheme.
200 >     * Field eventCount is incremented upon events that may enable
201 >     * workers that previously could not find a task to now find one:
202 >     * Submission of a new task to the pool, or another worker pushing
203 >     * a task onto a previously empty queue.  (We also use this
204 >     * mechanism for termination and reconfiguration actions that
205 >     * require wakeups of idle workers).  Each worker maintains its
206 >     * last known event count, and blocks when a scan for work did not
207 >     * find a task AND its lastEventCount matches the current
208 >     * eventCount. Waiting idle workers are recorded in a variant of
209 >     * Treiber stack headed by field eventWaiters which, when nonzero,
210 >     * encodes the thread index and count awaited for by the worker
211 >     * thread most recently calling eventSync. This thread in turn has
212 >     * a record (field nextEventWaiter) for the next waiting worker.
213 >     * In addition to allowing simpler decisions about need for
214 >     * wakeup, the event count bits in eventWaiters serve the role of
215 >     * tags to avoid ABA errors in Treiber stacks.  To reduce delays
216 >     * in task diffusion, workers not otherwise occupied may invoke
217 >     * method releaseWaiters, that removes and signals (unparks)
218 >     * workers not waiting on current count. To minimize task
219 >     * production stalls associate with signalling, any worker pushing
220 >     * a task on an empty queue invokes the weaker method signalWork,
221 >     * that only releases idle workers until it detects interference
222 >     * by other threads trying to release, and lets them take
223 >     * over. The net effect is a tree-like diffusion of signals, where
224 >     * released threads and possibly others) help with unparks.  To
225 >     * further reduce contention effects a bit, failed CASes to
226 >     * increment field eventCount are tolerated without retries.
227 >     * Conceptually they are merged into the same event, which is OK
228 >     * when their only purpose is to enable workers to scan for work.
229 >     *
230 >     * 5. Managing suspension of extra workers. When a worker is about
231 >     * to block waiting for a join (or via ManagedBlockers), we may
232 >     * create a new thread to maintain parallelism level, or at least
233 >     * avoid starvation (see below). Usually, extra threads are needed
234 >     * for only very short periods, yet join dependencies are such
235 >     * that we sometimes need them in bursts. Rather than create new
236 >     * threads each time this happens, we suspend no-longer-needed
237 >     * extra ones as "spares". For most purposes, we don't distinguish
238 >     * "extra" spare threads from normal "core" threads: On each call
239 >     * to preStep (the only point at which we can do this) a worker
240 >     * checks to see if there are now too many running workers, and if
241 >     * so, suspends itself.  Methods preJoin and doBlock look for
242 >     * suspended threads to resume before considering creating a new
243 >     * replacement. We don't need a special data structure to maintain
244 >     * spares; simply scanning the workers array looking for
245 >     * worker.isSuspended() is fine because the calling thread is
246 >     * otherwise not doing anything useful anyway; we are at least as
247 >     * happy if after locating a spare, the caller doesn't actually
248 >     * block because the join is ready before we try to adjust and
249 >     * compensate.  Note that this is intrinsically racy.  One thread
250 >     * may become a spare at about the same time as another is
251 >     * needlessly being created. We counteract this and related slop
252 >     * in part by requiring resumed spares to immediately recheck (in
253 >     * preStep) to see whether they they should re-suspend. The only
254 >     * effective difference between "extra" and "core" threads is that
255 >     * we allow the "extra" ones to time out and die if they are not
256 >     * resumed within a keep-alive interval of a few seconds. This is
257 >     * implemented mainly within ForkJoinWorkerThread, but requires
258 >     * some coordination (isTrimmed() -- meaning killed while
259 >     * suspended) to correctly maintain pool counts.
260 >     *
261 >     * 6. Deciding when to create new workers. The main dynamic
262 >     * control in this class is deciding when to create extra threads,
263 >     * in methods preJoin and doBlock. We always need to create one
264 >     * when the number of running threads becomes zero. But because
265 >     * blocked joins are typically dependent, we don't necessarily
266 >     * need or want one-to-one replacement. Using a one-to-one
267 >     * compensation rule often leads to enough useless overhead
268 >     * creating, suspending, resuming, and/or killing threads to
269 >     * signficantly degrade throughput.  We use a rule reflecting the
270 >     * idea that, the more spare threads you already have, the more
271 >     * evidence you need to create another one; where "evidence" is
272 >     * expressed as the current deficit -- target minus running
273 >     * threads. To reduce flickering and drift around target values,
274 >     * the relation is quadratic: adding a spare if (dc*dc)>=(sc*pc)
275 >     * (where dc is deficit, sc is number of spare threads and pc is
276 >     * target parallelism.)  This effectively reduces churn at the
277 >     * price of systematically undershooting target parallelism when
278 >     * many threads are blocked.  However, biasing toward undeshooting
279 >     * partially compensates for the above mechanics to suspend extra
280 >     * threads, that normally lead to overshoot because we can only
281 >     * suspend workers in-between top-level actions. It also better
282 >     * copes with the fact that some of the methods in this class tend
283 >     * to never become compiled (but are interpreted), so some
284 >     * components of the entire set of controls might execute many
285 >     * times faster than others. And similarly for cases where the
286 >     * apparent lack of work is just due to GC stalls and other
287 >     * transient system activity.
288 >     *
289 >     * 7. Maintaining other configuration parameters and monitoring
290 >     * statistics. Updates to fields controlling parallelism level,
291 >     * max size, etc can only meaningfully take effect for individual
292 >     * threads upon their next top-level actions; i.e., between
293 >     * stealing/running tasks/submission, which are separated by calls
294 >     * to preStep.  Memory ordering for these (assumed infrequent)
295 >     * reconfiguration calls is ensured by using reads and writes to
296 >     * volatile field workerCounts (that must be read in preStep anyway)
297 >     * as "fences" -- user-level reads are preceded by reads of
298 >     * workCounts, and writes are followed by no-op CAS to
299 >     * workerCounts. The values reported by other management and
300 >     * monitoring methods are either computed on demand, or are kept
301 >     * in fields that are only updated when threads are otherwise
302 >     * idle.
303 >     *
304 >     * Beware that there is a lot of representation-level coupling
305 >     * among classes ForkJoinPool, ForkJoinWorkerThread, and
306 >     * ForkJoinTask.  For example, direct access to "workers" array by
307 >     * workers, and direct access to ForkJoinTask.status by both
308 >     * ForkJoinPool and ForkJoinWorkerThread.  There is little point
309 >     * trying to reduce this, since any associated future changes in
310 >     * representations will need to be accompanied by algorithmic
311 >     * changes anyway.
312 >     *
313 >     * Style notes: There are lots of inline assignments (of form
314 >     * "while ((local = field) != 0)") which are usually the simplest
315 >     * way to ensure read orderings. Also several occurrences of the
316 >     * unusual "do {} while(!cas...)" which is the simplest way to
317 >     * force an update of a CAS'ed variable. There are also a few
318 >     * other coding oddities that help some methods perform reasonably
319 >     * even when interpreted (not compiled).
320 >     *
321 >     * The order of declarations in this file is: (1) statics (2)
322 >     * fields (along with constants used when unpacking some of them)
323 >     * (3) internal control methods (4) callbacks and other support
324 >     * for ForkJoinTask and ForkJoinWorkerThread classes, (5) exported
325 >     * methods (plus a few little helpers).
326       */
327  
65    /** Mask for packing and unpacking shorts */
66    private static final int  shortMask = 0xffff;
67
68    /** Max pool size -- must be a power of two minus 1 */
69    private static final int MAX_THREADS =  0x7FFF;
70
328      /**
329 <     * Factory for creating new ForkJoinWorkerThreads.  A
330 <     * ForkJoinWorkerThreadFactory must be defined and used for
331 <     * ForkJoinWorkerThread subclasses that extend base functionality
332 <     * or initialize threads with different contexts.
329 >     * Factory for creating new {@link ForkJoinWorkerThread}s.
330 >     * A {@code ForkJoinWorkerThreadFactory} must be defined and used
331 >     * for {@code ForkJoinWorkerThread} subclasses that extend base
332 >     * functionality or initialize threads with different contexts.
333       */
334      public static interface ForkJoinWorkerThreadFactory {
335          /**
336           * Returns a new worker thread operating in the given pool.
337           *
338           * @param pool the pool this thread works in
339 <         * @throws NullPointerException if pool is null;
339 >         * @throws NullPointerException if the pool is null
340           */
341          public ForkJoinWorkerThread newThread(ForkJoinPool pool);
342      }
343  
344      /**
345 <     * Default ForkJoinWorkerThreadFactory implementation, creates a
345 >     * Default ForkJoinWorkerThreadFactory implementation; creates a
346       * new ForkJoinWorkerThread.
347       */
348      static class  DefaultForkJoinWorkerThreadFactory
349          implements ForkJoinWorkerThreadFactory {
350          public ForkJoinWorkerThread newThread(ForkJoinPool pool) {
351 <            try {
95 <                return new ForkJoinWorkerThread(pool);
96 <            } catch (OutOfMemoryError oom)  {
97 <                return null;
98 <            }
351 >            return new ForkJoinWorkerThread(pool);
352          }
353      }
354  
# Line 131 | Line 384 | public class ForkJoinPool extends Abstra
384          new AtomicInteger();
385  
386      /**
387 <     * Array holding all worker threads in the pool. Array size must
387 >     * Absolute bound for parallelism level. Twice this number must
388 >     * fit into a 16bit field to enable word-packing for some counts.
389 >     */
390 >    private static final int MAX_THREADS = 0x7fff;
391 >
392 >    /**
393 >     * Array holding all worker threads in the pool.  Array size must
394       * be a power of two.  Updates and replacements are protected by
395 <     * workerLock, but it is always kept in a consistent enough state
396 <     * to be randomly accessed without locking by workers performing
397 <     * work-stealing.
395 >     * workerLock, but the array is always kept in a consistent enough
396 >     * state to be randomly accessed without locking by workers
397 >     * performing work-stealing, as well as other traversal-based
398 >     * methods in this class. All readers must tolerate that some
399 >     * array slots may be null.
400       */
401      volatile ForkJoinWorkerThread[] workers;
402  
403      /**
404 <     * Lock protecting access to workers.
404 >     * Queue for external submissions.
405       */
406 <    private final ReentrantLock workerLock;
406 >    private final LinkedTransferQueue<ForkJoinTask<?>> submissionQueue;
407  
408      /**
409 <     * Condition for awaitTermination.
409 >     * Lock protecting updates to workers array.
410       */
411 <    private final Condition termination;
411 >    private final ReentrantLock workerLock;
412  
413      /**
414 <     * The uncaught exception handler used when any worker
154 <     * abrupty terminates
414 >     * Latch released upon termination.
415       */
416 <    private Thread.UncaughtExceptionHandler ueh;
416 >    private final CountDownLatch terminationLatch;
417  
418      /**
419       * Creation factory for worker threads.
# Line 161 | Line 421 | public class ForkJoinPool extends Abstra
421      private final ForkJoinWorkerThreadFactory factory;
422  
423      /**
424 <     * Head of stack of threads that were created to maintain
425 <     * parallelism when other threads blocked, but have since
166 <     * suspended when the parallelism level rose.
424 >     * Sum of per-thread steal counts, updated only when threads are
425 >     * idle or terminating.
426       */
427 <    private volatile WaitQueueNode spareStack;
427 >    private volatile long stealCount;
428  
429      /**
430 <     * Sum of per-thread steal counts, updated only when threads are
431 <     * idle or terminating.
430 >     * Encoded record of top of treiber stack of threads waiting for
431 >     * events. The top 32 bits contain the count being waited for. The
432 >     * bottom word contains one plus the pool index of waiting worker
433 >     * thread.
434       */
435 <    private final AtomicLong stealCount;
435 >    private volatile long eventWaiters;
436 >
437 >    private static final int  EVENT_COUNT_SHIFT = 32;
438 >    private static final long WAITER_INDEX_MASK = (1L << EVENT_COUNT_SHIFT)-1L;
439  
440      /**
441 <     * Queue for external submissions.
441 >     * A counter for events that may wake up worker threads:
442 >     *   - Submission of a new task to the pool
443 >     *   - A worker pushing a task on an empty queue
444 >     *   - termination and reconfiguration
445       */
446 <    private final LinkedTransferQueue<ForkJoinTask<?>> submissionQueue;
446 >    private volatile int eventCount;
447 >
448 >    /**
449 >     * Lifecycle control. The low word contains the number of workers
450 >     * that are (probably) executing tasks. This value is atomically
451 >     * incremented before a worker gets a task to run, and decremented
452 >     * when worker has no tasks and cannot find any.  Bits 16-18
453 >     * contain runLevel value. When all are zero, the pool is
454 >     * running. Level transitions are monotonic (running -> shutdown
455 >     * -> terminating -> terminated) so each transition adds a bit.
456 >     * These are bundled together to ensure consistent read for
457 >     * termination checks (i.e., that runLevel is at least SHUTDOWN
458 >     * and active threads is zero).
459 >     */
460 >    private volatile int runState;
461 >
462 >    // Note: The order among run level values matters.
463 >    private static final int RUNLEVEL_SHIFT     = 16;
464 >    private static final int SHUTDOWN           = 1 << RUNLEVEL_SHIFT;
465 >    private static final int TERMINATING        = 1 << (RUNLEVEL_SHIFT + 1);
466 >    private static final int TERMINATED         = 1 << (RUNLEVEL_SHIFT + 2);
467 >    private static final int ACTIVE_COUNT_MASK  = (1 << RUNLEVEL_SHIFT) - 1;
468 >    private static final int ONE_ACTIVE         = 1; // active update delta
469  
470      /**
471 <     * Head of Treiber stack for barrier sync. See below for explanation
471 >     * Holds number of total (i.e., created and not yet terminated)
472 >     * and running (i.e., not blocked on joins or other managed sync)
473 >     * threads, packed together to ensure consistent snapshot when
474 >     * making decisions about creating and suspending spare
475 >     * threads. Updated only by CAS. Note that adding a new worker
476 >     * requires incrementing both counts, since workers start off in
477 >     * running state.  This field is also used for memory-fencing
478 >     * configuration parameters.
479 >     */
480 >    private volatile int workerCounts;
481 >
482 >    private static final int TOTAL_COUNT_SHIFT  = 16;
483 >    private static final int RUNNING_COUNT_MASK = (1 << TOTAL_COUNT_SHIFT) - 1;
484 >    private static final int ONE_RUNNING        = 1;
485 >    private static final int ONE_TOTAL          = 1 << TOTAL_COUNT_SHIFT;
486 >
487 >    /*
488 >     * Fields parallelism. maxPoolSize, locallyFifo,
489 >     * maintainsParallelism, and ueh are non-volatile, but external
490 >     * reads/writes use workerCount fences to ensure visability.
491       */
184    private volatile WaitQueueNode barrierStack;
492  
493      /**
494 <     * The count for event barrier
494 >     * The target parallelism level.
495       */
496 <    private volatile long eventCount;
496 >    private int parallelism;
497  
498      /**
499 <     * Pool number, just for assigning useful names to worker threads
499 >     * The maximum allowed pool size.
500       */
501 <    private final int poolNumber;
501 >    private int maxPoolSize;
502  
503      /**
504 <     * The maximum allowed pool size
504 >     * True if use local fifo, not default lifo, for local polling
505 >     * Replicated by ForkJoinWorkerThreads
506       */
507 <    private volatile int maxPoolSize;
507 >    private boolean locallyFifo;
508  
509      /**
510 <     * The desired parallelism level, updated only under workerLock.
510 >     * Controls whether to add spares to maintain parallelism
511       */
512 <    private volatile int parallelism;
512 >    private boolean maintainsParallelism;
513  
514      /**
515 <     * Holds number of total (i.e., created and not yet terminated)
516 <     * and running (i.e., not blocked on joins or other managed sync)
209 <     * threads, packed into one int to ensure consistent snapshot when
210 <     * making decisions about creating and suspending spare
211 <     * threads. Updated only by CAS.  Note: CASes in
212 <     * updateRunningCount and preJoin running active count is in low
213 <     * word, so need to be modified if this changes
515 >     * The uncaught exception handler used when any worker
516 >     * abruptly terminates
517       */
518 <    private volatile int workerCounts;
518 >    private Thread.UncaughtExceptionHandler ueh;
519  
520 <    private static int totalCountOf(int s)           { return s >>> 16;  }
521 <    private static int runningCountOf(int s)         { return s & shortMask; }
522 <    private static int workerCountsFor(int t, int r) { return (t << 16) + r; }
520 >    /**
521 >     * Pool number, just for assigning useful names to worker threads
522 >     */
523 >    private final int poolNumber;
524 >
525 >    // utilities for updating fields
526  
527      /**
528 <     * Add delta (which may be negative) to running count.  This must
529 <     * be called before (with negative arg) and after (with positive)
224 <     * any managed synchronization (i.e., mainly, joins)
528 >     * Adds delta to running count.  Used mainly by ForkJoinTask.
529 >     *
530       * @param delta the number to add
531       */
532      final void updateRunningCount(int delta) {
533 <        int s;
534 <        do;while (!casWorkerCounts(s = workerCounts, s + delta));
533 >        int wc;
534 >        do {} while (!UNSAFE.compareAndSwapInt(this, workerCountsOffset,
535 >                                               wc = workerCounts,
536 >                                               wc + delta));
537      }
538  
539      /**
540 <     * Add delta (which may be negative) to both total and running
541 <     * count.  This must be called upon creation and termination of
542 <     * worker threads.
543 <     * @param delta the number to add
540 >     * Write fence for user modifications of pool parameters
541 >     * (parallelism. etc).  Note that it doesn't matter if CAS fails.
542 >     */
543 >    private void workerCountWriteFence() {
544 >        int wc;
545 >        UNSAFE.compareAndSwapInt(this, workerCountsOffset,
546 >                                 wc = workerCounts, wc);
547 >    }
548 >
549 >    /**
550 >     * Read fence for external reads of pool parameters
551 >     * (parallelism. maxPoolSize, etc).
552 >     */
553 >    private void workerCountReadFence() {
554 >        int ignore = workerCounts;
555 >    }
556 >
557 >    /**
558 >     * Tries incrementing active count; fails on contention.
559 >     * Called by workers before executing tasks.
560 >     *
561 >     * @return true on success
562 >     */
563 >    final boolean tryIncrementActiveCount() {
564 >        int c;
565 >        return UNSAFE.compareAndSwapInt(this, runStateOffset,
566 >                                        c = runState, c + ONE_ACTIVE);
567 >    }
568 >
569 >    /**
570 >     * Tries decrementing active count; fails on contention.
571 >     * Called when workers cannot find tasks to run.
572 >     */
573 >    final boolean tryDecrementActiveCount() {
574 >        int c;
575 >        return UNSAFE.compareAndSwapInt(this, runStateOffset,
576 >                                        c = runState, c - ONE_ACTIVE);
577 >    }
578 >
579 >    /**
580 >     * Advances to at least the given level. Returns true if not
581 >     * already in at least the given level.
582       */
583 <    private void updateWorkerCount(int delta) {
584 <        int d = delta + (delta << 16); // add to both lo and hi parts
585 <        int s;
586 <        do;while (!casWorkerCounts(s = workerCounts, s + d));
583 >    private boolean advanceRunLevel(int level) {
584 >        for (;;) {
585 >            int s = runState;
586 >            if ((s & level) != 0)
587 >                return false;
588 >            if (UNSAFE.compareAndSwapInt(this, runStateOffset, s, s | level))
589 >                return true;
590 >        }
591      }
592  
593 +    // workers array maintenance
594 +
595      /**
596 <     * Lifecycle control. High word contains runState, low word
246 <     * contains the number of workers that are (probably) executing
247 <     * tasks. This value is atomically incremented before a worker
248 <     * gets a task to run, and decremented when worker has no tasks
249 <     * and cannot find any. These two fields are bundled together to
250 <     * support correct termination triggering.  Note: activeCount
251 <     * CAS'es cheat by assuming active count is in low word, so need
252 <     * to be modified if this changes
596 >     * Records and returns a workers array index for new worker.
597       */
598 <    private volatile int runControl;
598 >    private int recordWorker(ForkJoinWorkerThread w) {
599 >        // Try using slot totalCount-1. If not available, scan and/or resize
600 >        int k = (workerCounts >>> TOTAL_COUNT_SHIFT) - 1;
601 >        final ReentrantLock lock = this.workerLock;
602 >        lock.lock();
603 >        try {
604 >            ForkJoinWorkerThread[] ws = workers;
605 >            int len = ws.length;
606 >            if (k < 0 || k >= len || ws[k] != null) {
607 >                for (k = 0; k < len && ws[k] != null; ++k)
608 >                    ;
609 >                if (k == len)
610 >                    ws = Arrays.copyOf(ws, len << 1);
611 >            }
612 >            ws[k] = w;
613 >            workers = ws; // volatile array write ensures slot visibility
614 >        } finally {
615 >            lock.unlock();
616 >        }
617 >        return k;
618 >    }
619  
620 <    // RunState values. Order among values matters
621 <    private static final int RUNNING     = 0;
622 <    private static final int SHUTDOWN    = 1;
623 <    private static final int TERMINATING = 2;
624 <    private static final int TERMINATED  = 3;
620 >    /**
621 >     * Nulls out record of worker in workers array
622 >     */
623 >    private void forgetWorker(ForkJoinWorkerThread w) {
624 >        int idx = w.poolIndex;
625 >        // Locking helps method recordWorker avoid unecessary expansion
626 >        final ReentrantLock lock = this.workerLock;
627 >        lock.lock();
628 >        try {
629 >            ForkJoinWorkerThread[] ws = workers;
630 >            if (idx >= 0 && idx < ws.length && ws[idx] == w) // verify
631 >                ws[idx] = null;
632 >        } finally {
633 >            lock.unlock();
634 >        }
635 >    }
636  
637 <    private static int runStateOf(int c)             { return c >>> 16; }
263 <    private static int activeCountOf(int c)          { return c & shortMask; }
264 <    private static int runControlFor(int r, int a)   { return (r << 16) + a; }
637 >    // adding and removing workers
638  
639      /**
640 <     * Increment active count. Called by workers before/during
641 <     * executing tasks.
640 >     * Tries to create and add new worker. Assumes that worker counts
641 >     * are already updated to accommodate the worker, so adjusts on
642 >     * failure.
643 >     *
644 >     * @return new worker or null if creation failed
645       */
646 <    final void incrementActiveCount() {
646 >    private ForkJoinWorkerThread addWorker() {
647 >        ForkJoinWorkerThread w = null;
648 >        try {
649 >            w = factory.newThread(this);
650 >        } finally { // Adjust on either null or exceptional factory return
651 >            if (w == null) {
652 >                onWorkerCreationFailure();
653 >                return null;
654 >            }
655 >        }
656 >        w.start(recordWorker(w), locallyFifo, ueh);
657 >        return w;
658 >    }
659 >
660 >    /**
661 >     * Adjusts counts upon failure to create worker
662 >     */
663 >    private void onWorkerCreationFailure() {
664          int c;
665 <        do;while (!casRunControl(c = runControl, c+1));
665 >        do {} while (!UNSAFE.compareAndSwapInt(this, workerCountsOffset,
666 >                                               c = workerCounts,
667 >                                               c - (ONE_RUNNING|ONE_TOTAL)));
668 >        tryTerminate(false); // in case of failure during shutdown
669 >    }
670 >
671 >    /**
672 >     * Create enough total workers to establish target parallelism,
673 >     * giving up if terminating or addWorker fails
674 >     */
675 >    private void ensureEnoughTotalWorkers() {
676 >        int wc;
677 >        while (runState < TERMINATING &&
678 >               ((wc = workerCounts) >>> TOTAL_COUNT_SHIFT) < parallelism) {
679 >            if ((UNSAFE.compareAndSwapInt(this, workerCountsOffset,
680 >                                          wc, wc + (ONE_RUNNING|ONE_TOTAL)) &&
681 >                 addWorker() == null))
682 >                break;
683 >        }
684 >    }
685 >
686 >    /**
687 >     * Final callback from terminating worker.  Removes record of
688 >     * worker from array, and adjusts counts. If pool is shutting
689 >     * down, tries to complete terminatation, else possibly replaces
690 >     * the worker.
691 >     *
692 >     * @param w the worker
693 >     */
694 >    final void workerTerminated(ForkJoinWorkerThread w) {
695 >        if (w.active) { // force inactive
696 >            w.active = false;
697 >            do {} while (!tryDecrementActiveCount());
698 >        }
699 >        forgetWorker(w);
700 >
701 >        // decrement total count, and if was running, running count
702 >        int unit = w.isTrimmed()? ONE_TOTAL : (ONE_RUNNING|ONE_TOTAL);
703 >        int wc;
704 >        do {} while (!UNSAFE.compareAndSwapInt(this, workerCountsOffset,
705 >                                               wc = workerCounts, wc - unit));
706 >
707 >        accumulateStealCount(w); // collect final count
708 >        if (!tryTerminate(false))
709 >            ensureEnoughTotalWorkers();
710 >    }
711 >
712 >    // Waiting for and signalling events
713 >
714 >    /**
715 >     * Ensures eventCount on exit is different (mod 2^32) than on
716 >     * entry.  CAS failures are OK -- any change in count suffices.
717 >     */
718 >    private void advanceEventCount() {
719 >        int c;
720 >        UNSAFE.compareAndSwapInt(this, eventCountOffset, c = eventCount, c+1);
721 >    }
722 >
723 >    /**
724 >     * Releases workers blocked on a count not equal to current count.
725 >     */
726 >    final void releaseWaiters() {
727 >        long top;
728 >        int id;
729 >        while ((id = (int)((top = eventWaiters) & WAITER_INDEX_MASK)) > 0 &&
730 >               (int)(top >>> EVENT_COUNT_SHIFT) != eventCount) {
731 >            ForkJoinWorkerThread[] ws = workers;
732 >            ForkJoinWorkerThread w;
733 >            if (ws.length >= id && (w = ws[id - 1]) != null &&
734 >                UNSAFE.compareAndSwapLong(this, eventWaitersOffset,
735 >                                          top, w.nextWaiter))
736 >                LockSupport.unpark(w);
737 >        }
738 >    }
739 >
740 >    /**
741 >     * Advances eventCount and releases waiters until interference by
742 >     * other releasing threads is detected.
743 >     */
744 >    final void signalWork() {
745 >        int ec;
746 >        UNSAFE.compareAndSwapInt(this, eventCountOffset, ec=eventCount, ec+1);
747 >        outer:for (;;) {
748 >            long top = eventWaiters;
749 >            ec = eventCount;
750 >            for (;;) {
751 >                ForkJoinWorkerThread[] ws; ForkJoinWorkerThread w;
752 >                int id = (int)(top & WAITER_INDEX_MASK);
753 >                if (id <= 0 || (int)(top >>> EVENT_COUNT_SHIFT) == ec)
754 >                    return;
755 >                if ((ws = workers).length < id || (w = ws[id - 1]) == null ||
756 >                    !UNSAFE.compareAndSwapLong(this, eventWaitersOffset,
757 >                                               top, top = w.nextWaiter))
758 >                    continue outer;      // possibly stale; reread
759 >                LockSupport.unpark(w);
760 >                if (top != eventWaiters) // let someone else take over
761 >                    return;
762 >            }
763 >        }
764 >    }
765 >
766 >    /**
767 >     * If worker is inactive, blocks until terminating or event count
768 >     * advances from last value held by worker; in any case helps
769 >     * release others.
770 >     *
771 >     * @param w the calling worker thread
772 >     */
773 >    private void eventSync(ForkJoinWorkerThread w) {
774 >        if (!w.active) {
775 >            int prev = w.lastEventCount;
776 >            long nextTop = (((long)prev << EVENT_COUNT_SHIFT) |
777 >                            ((long)(w.poolIndex + 1)));
778 >            long top;
779 >            while ((runState < SHUTDOWN || !tryTerminate(false)) &&
780 >                   (((int)(top = eventWaiters) & WAITER_INDEX_MASK) == 0 ||
781 >                    (int)(top >>> EVENT_COUNT_SHIFT) == prev) &&
782 >                   eventCount == prev) {
783 >                if (UNSAFE.compareAndSwapLong(this, eventWaitersOffset,
784 >                                              w.nextWaiter = top, nextTop)) {
785 >                    accumulateStealCount(w); // transfer steals while idle
786 >                    Thread.interrupted();    // clear/ignore interrupt
787 >                    while (eventCount == prev)
788 >                        w.doPark();
789 >                    break;
790 >                }
791 >            }
792 >            w.lastEventCount = eventCount;
793 >        }
794 >        releaseWaiters();
795      }
796  
797      /**
798 <     * Decrement active count; possibly trigger termination.
799 <     * Called by workers when they can't find tasks.
798 >     * Callback from workers invoked upon each top-level action (i.e.,
799 >     * stealing a task or taking a submission and running
800 >     * it). Performs one or both of the following:
801 >     *
802 >     * * If the worker cannot find work, updates its active status to
803 >     * inactive and updates activeCount unless there is contention, in
804 >     * which case it may try again (either in this or a subsequent
805 >     * call).  Additionally, awaits the next task event and/or helps
806 >     * wake up other releasable waiters.
807 >     *
808 >     * * If there are too many running threads, suspends this worker
809 >     * (first forcing inactivation if necessary).  If it is not
810 >     * resumed before a keepAlive elapses, the worker may be "trimmed"
811 >     * -- killed while suspended within suspendAsSpare. Otherwise,
812 >     * upon resume it rechecks to make sure that it is still needed.
813 >     *
814 >     * @param w the worker
815 >     * @param worked false if the worker scanned for work but didn't
816 >     * find any (in which case it may block waiting for work).
817       */
818 <    final void decrementActiveCount() {
819 <        int c, nextc;
820 <        do;while (!casRunControl(c = runControl, nextc = c-1));
821 <        if (canTerminateOnShutdown(nextc))
822 <            terminateOnShutdown();
818 >    final void preStep(ForkJoinWorkerThread w, boolean worked) {
819 >        boolean active = w.active;
820 >        boolean inactivate = !worked & active;
821 >        for (;;) {
822 >            if (inactivate) {
823 >                int c = runState;
824 >                if (UNSAFE.compareAndSwapInt(this, runStateOffset,
825 >                                             c, c - ONE_ACTIVE))
826 >                    inactivate = active = w.active = false;
827 >            }
828 >            int wc = workerCounts;
829 >            if ((wc & RUNNING_COUNT_MASK) <= parallelism) {
830 >                if (!worked)
831 >                    eventSync(w);
832 >                return;
833 >            }
834 >            if (!(inactivate |= active) &&  // must inactivate to suspend
835 >                UNSAFE.compareAndSwapInt(this, workerCountsOffset,
836 >                                         wc, wc - ONE_RUNNING) &&
837 >                !w.suspendAsSpare())        // false if trimmed
838 >                return;
839 >        }
840      }
841  
842      /**
843 <     * Return true if argument represents zero active count and
844 <     * nonzero runstate, which is the triggering condition for
845 <     * terminating on shutdown.
843 >     * Adjusts counts and creates or resumes compensating threads for
844 >     * a worker about to block on task joinMe, returning early if
845 >     * joinMe becomes ready. First tries resuming an existing spare
846 >     * (which usually also avoids any count adjustment), but must then
847 >     * decrement running count to determine whether a new thread is
848 >     * needed. See above for fuller explanation.
849       */
850 <    private static boolean canTerminateOnShutdown(int c) {
851 <        return ((c & -c) >>> 16) != 0; // i.e. least bit is nonzero runState bit
850 >    final void preJoin(ForkJoinTask<?> joinMe) {
851 >        boolean dec = false;       // true when running count decremented
852 >        for (;;) {
853 >            releaseWaiters();      // help other threads progress
854 >
855 >            if (joinMe.status < 0) // surround spare search with done checks
856 >                return;
857 >            ForkJoinWorkerThread spare = null;
858 >            for (ForkJoinWorkerThread w : workers) {
859 >                if (w != null && w.isSuspended()) {
860 >                    spare = w;
861 >                    break;
862 >                }
863 >            }
864 >            if (joinMe.status < 0)
865 >                return;
866 >
867 >            if (spare != null && spare.tryUnsuspend()) {
868 >                if (dec || joinMe.requestSignal() < 0) {
869 >                    int c;
870 >                    do {} while (!UNSAFE.compareAndSwapInt(this,
871 >                                                           workerCountsOffset,
872 >                                                           c = workerCounts,
873 >                                                           c + ONE_RUNNING));
874 >                } // else no net count change
875 >                LockSupport.unpark(spare);
876 >                return;
877 >            }
878 >
879 >            int wc = workerCounts; // decrement running count
880 >            if (!dec && (wc & RUNNING_COUNT_MASK) != 0 &&
881 >                (dec = UNSAFE.compareAndSwapInt(this, workerCountsOffset,
882 >                                                wc, wc -= ONE_RUNNING)) &&
883 >                joinMe.requestSignal() < 0) { // cannot block
884 >                int c;                        // back out
885 >                do {} while (!UNSAFE.compareAndSwapInt(this,
886 >                                                       workerCountsOffset,
887 >                                                       c = workerCounts,
888 >                                                       c + ONE_RUNNING));
889 >                return;
890 >            }
891 >
892 >            if (dec) {
893 >                int tc = wc >>> TOTAL_COUNT_SHIFT;
894 >                int pc = parallelism;
895 >                int dc = pc - (wc & RUNNING_COUNT_MASK); // deficit count
896 >                if ((dc < pc && (dc <= 0 || (dc * dc < (tc - pc) * pc) ||
897 >                                 !maintainsParallelism)) ||
898 >                    tc >= maxPoolSize) // cannot add
899 >                    return;
900 >                if (spare == null &&
901 >                    UNSAFE.compareAndSwapInt(this, workerCountsOffset, wc,
902 >                                             wc + (ONE_RUNNING|ONE_TOTAL))) {
903 >                    addWorker();
904 >                    return;
905 >                }
906 >            }
907 >        }
908      }
909  
910      /**
911 <     * Transition run state to at least the given state. Return true
912 <     * if not already at least given state.
911 >     * Same idea as preJoin but with too many differing details to
912 >     * integrate: There are no task-based signal counts, and only one
913 >     * way to do the actual blocking. So for simplicity it is directly
914 >     * incorporated into this method.
915       */
916 <    private boolean transitionRunStateTo(int state) {
916 >    final void doBlock(ManagedBlocker blocker, boolean maintainPar)
917 >        throws InterruptedException {
918 >        maintainPar &= maintainsParallelism; // override
919 >        boolean dec = false;
920 >        boolean done = false;
921          for (;;) {
922 <            int c = runControl;
923 <            if (runStateOf(c) >= state)
924 <                return false;
925 <            if (casRunControl(c, runControlFor(state, activeCountOf(c))))
926 <                return true;
922 >            releaseWaiters();
923 >            if (done = blocker.isReleasable())
924 >                break;
925 >            ForkJoinWorkerThread spare = null;
926 >            for (ForkJoinWorkerThread w : workers) {
927 >                if (w != null && w.isSuspended()) {
928 >                    spare = w;
929 >                    break;
930 >                }
931 >            }
932 >            if (done = blocker.isReleasable())
933 >                break;
934 >            if (spare != null && spare.tryUnsuspend()) {
935 >                if (dec) {
936 >                    int c;
937 >                    do {} while (!UNSAFE.compareAndSwapInt(this,
938 >                                                           workerCountsOffset,
939 >                                                           c = workerCounts,
940 >                                                           c + ONE_RUNNING));
941 >                }
942 >                LockSupport.unpark(spare);
943 >                break;
944 >            }
945 >            int wc = workerCounts;
946 >            if (!dec && (wc & RUNNING_COUNT_MASK) != 0)
947 >                dec = UNSAFE.compareAndSwapInt(this, workerCountsOffset,
948 >                                               wc, wc -= ONE_RUNNING);
949 >            if (dec) {
950 >                int tc = wc >>> TOTAL_COUNT_SHIFT;
951 >                int pc = parallelism;
952 >                int dc = pc - (wc & RUNNING_COUNT_MASK);
953 >                if ((dc < pc && (dc <= 0 || (dc * dc < (tc - pc) * pc) ||
954 >                                 !maintainPar)) ||
955 >                    tc >= maxPoolSize)
956 >                    break;
957 >                if (spare == null &&
958 >                    UNSAFE.compareAndSwapInt(this, workerCountsOffset, wc,
959 >                                             wc + (ONE_RUNNING|ONE_TOTAL))){
960 >                    addWorker();
961 >                    break;
962 >                }
963 >            }
964 >        }
965 >
966 >        try {
967 >            if (!done)
968 >                do {} while (!blocker.isReleasable() && !blocker.block());
969 >        } finally {
970 >            if (dec) {
971 >                int c;
972 >                do {} while (!UNSAFE.compareAndSwapInt(this,
973 >                                                       workerCountsOffset,
974 >                                                       c = workerCounts,
975 >                                                       c + ONE_RUNNING));
976 >            }
977          }
978      }
979  
980      /**
981 <     * Controls whether to add spares to maintain parallelism
981 >     * Unless there are not enough other running threads, adjusts
982 >     * counts for a a worker in performing helpJoin that cannot find
983 >     * any work, so that this worker can now block.
984 >     *
985 >     * @return true if worker may block
986 >     */
987 >    final boolean preBlockHelpingJoin(ForkJoinTask<?> joinMe) {
988 >        while (joinMe.status >= 0) {
989 >            releaseWaiters(); // help other threads progress
990 >
991 >            // if a spare exists, resume it to maintain parallelism level
992 >            if ((workerCounts & RUNNING_COUNT_MASK) <= parallelism) {
993 >                ForkJoinWorkerThread spare = null;
994 >                for (ForkJoinWorkerThread w : workers) {
995 >                    if (w != null && w.isSuspended()) {
996 >                        spare = w;
997 >                        break;
998 >                    }
999 >                }
1000 >                if (joinMe.status < 0)
1001 >                    break;
1002 >                if (spare != null) {
1003 >                    if (spare.tryUnsuspend()) {
1004 >                        boolean canBlock = true;
1005 >                        if (joinMe.requestSignal() < 0) {
1006 >                            canBlock = false; // already done
1007 >                            int c;
1008 >                            do {} while (!UNSAFE.compareAndSwapInt
1009 >                                         (this, workerCountsOffset,
1010 >                                          c = workerCounts, c + ONE_RUNNING));
1011 >                        }
1012 >                        LockSupport.unpark(spare);
1013 >                        return canBlock;
1014 >                    }
1015 >                    continue; // recheck -- another spare may exist
1016 >                }
1017 >            }
1018 >
1019 >            int wc = workerCounts; // reread to shorten CAS window
1020 >            int rc = wc & RUNNING_COUNT_MASK;
1021 >            if (rc <= 2) // keep this and at most one other thread alive
1022 >                break;
1023 >
1024 >            if (UNSAFE.compareAndSwapInt(this, workerCountsOffset,
1025 >                                         wc, wc - ONE_RUNNING)) {
1026 >                if (joinMe.requestSignal() >= 0)
1027 >                    return true;
1028 >                int c;                        // back out
1029 >                do {} while (!UNSAFE.compareAndSwapInt
1030 >                             (this, workerCountsOffset,
1031 >                              c = workerCounts, c + ONE_RUNNING));
1032 >                break;
1033 >            }
1034 >        }
1035 >        return false;
1036 >    }
1037 >
1038 >    /**
1039 >     * Possibly initiates and/or completes termination.
1040 >     *
1041 >     * @param now if true, unconditionally terminate, else only
1042 >     * if shutdown and empty queue and no active workers
1043 >     * @return true if now terminating or terminated
1044 >     */
1045 >    private boolean tryTerminate(boolean now) {
1046 >        if (now)
1047 >            advanceRunLevel(SHUTDOWN); // ensure at least SHUTDOWN
1048 >        else if (runState < SHUTDOWN ||
1049 >                 !submissionQueue.isEmpty() ||
1050 >                 (runState & ACTIVE_COUNT_MASK) != 0)
1051 >            return false;
1052 >
1053 >        if (advanceRunLevel(TERMINATING))
1054 >            startTerminating();
1055 >
1056 >        // Finish now if all threads terminated; else in some subsequent call
1057 >        if ((workerCounts >>> TOTAL_COUNT_SHIFT) == 0) {
1058 >            advanceRunLevel(TERMINATED);
1059 >            terminationLatch.countDown();
1060 >        }
1061 >        return true;
1062 >    }
1063 >
1064 >    /**
1065 >     * Actions on transition to TERMINATING
1066 >     */
1067 >    private void startTerminating() {
1068 >        // Clear out and cancel submissions, ignoring exceptions
1069 >        ForkJoinTask<?> task;
1070 >        while ((task = submissionQueue.poll()) != null) {
1071 >            try {
1072 >                task.cancel(false);
1073 >            } catch (Throwable ignore) {
1074 >            }
1075 >        }
1076 >        // Propagate run level
1077 >        for (ForkJoinWorkerThread w : workers) {
1078 >            if (w != null)
1079 >                w.shutdown();    // also resumes suspended workers
1080 >        }
1081 >        // Ensure no straggling local tasks
1082 >        for (ForkJoinWorkerThread w : workers) {
1083 >            if (w != null)
1084 >                w.cancelTasks();
1085 >        }
1086 >        // Wake up idle workers
1087 >        advanceEventCount();
1088 >        releaseWaiters();
1089 >        // Unstick pending joins
1090 >        for (ForkJoinWorkerThread w : workers) {
1091 >            if (w != null && !w.isTerminated()) {
1092 >                try {
1093 >                    w.interrupt();
1094 >                } catch (SecurityException ignore) {
1095 >                }
1096 >            }
1097 >        }
1098 >    }
1099 >
1100 >    // misc support for ForkJoinWorkerThread
1101 >
1102 >    /**
1103 >     * Returns pool number
1104 >     */
1105 >    final int getPoolNumber() {
1106 >        return poolNumber;
1107 >    }
1108 >
1109 >    /**
1110 >     * Accumulates steal count from a worker, clearing
1111 >     * the worker's value
1112 >     */
1113 >    final void accumulateStealCount(ForkJoinWorkerThread w) {
1114 >        int sc = w.stealCount;
1115 >        if (sc != 0) {
1116 >            long c;
1117 >            w.stealCount = 0;
1118 >            do {} while (!UNSAFE.compareAndSwapLong(this, stealCountOffset,
1119 >                                                    c = stealCount, c + sc));
1120 >        }
1121 >    }
1122 >
1123 >    /**
1124 >     * Returns the approximate (non-atomic) number of idle threads per
1125 >     * active thread.
1126       */
1127 <    private volatile boolean maintainsParallelism;
1127 >    final int idlePerActive() {
1128 >        int ac = runState;    // no mask -- artifically boosts during shutdown
1129 >        int pc = parallelism; // use targeted parallelism, not rc
1130 >        // Use exact results for small values, saturate past 4
1131 >        return pc <= ac? 0 : pc >>> 1 <= ac? 1 : pc >>> 2 <= ac? 3 : pc >>> 3;
1132 >    }
1133 >
1134 >    // Public and protected methods
1135  
1136      // Constructors
1137  
1138      /**
1139 <     * Creates a ForkJoinPool with a pool size equal to the number of
1140 <     * processors available on the system and using the default
1141 <     * ForkJoinWorkerThreadFactory,
1139 >     * Creates a {@code ForkJoinPool} with parallelism equal to {@link
1140 >     * java.lang.Runtime#availableProcessors}, and using the {@linkplain
1141 >     * #defaultForkJoinWorkerThreadFactory default thread factory}.
1142 >     *
1143       * @throws SecurityException if a security manager exists and
1144       *         the caller is not permitted to modify threads
1145       *         because it does not hold {@link
1146 <     *         java.lang.RuntimePermission}<code>("modifyThread")</code>,
1146 >     *         java.lang.RuntimePermission}{@code ("modifyThread")}
1147       */
1148      public ForkJoinPool() {
1149          this(Runtime.getRuntime().availableProcessors(),
# Line 328 | Line 1151 | public class ForkJoinPool extends Abstra
1151      }
1152  
1153      /**
1154 <     * Creates a ForkJoinPool with the indicated parellelism level
1155 <     * threads, and using the default ForkJoinWorkerThreadFactory,
1156 <     * @param parallelism the number of worker threads
1154 >     * Creates a {@code ForkJoinPool} with the indicated parallelism
1155 >     * level and using the {@linkplain
1156 >     * #defaultForkJoinWorkerThreadFactory default thread factory}.
1157 >     *
1158 >     * @param parallelism the parallelism level
1159       * @throws IllegalArgumentException if parallelism less than or
1160 <     * equal to zero
1160 >     *         equal to zero, or greater than implementation limit
1161       * @throws SecurityException if a security manager exists and
1162       *         the caller is not permitted to modify threads
1163       *         because it does not hold {@link
1164 <     *         java.lang.RuntimePermission}<code>("modifyThread")</code>,
1164 >     *         java.lang.RuntimePermission}{@code ("modifyThread")}
1165       */
1166      public ForkJoinPool(int parallelism) {
1167          this(parallelism, defaultForkJoinWorkerThreadFactory);
1168      }
1169  
1170      /**
1171 <     * Creates a ForkJoinPool with parallelism equal to the number of
1172 <     * processors available on the system and using the given
1173 <     * ForkJoinWorkerThreadFactory,
1171 >     * Creates a {@code ForkJoinPool} with parallelism equal to {@link
1172 >     * java.lang.Runtime#availableProcessors}, and using the given
1173 >     * thread factory.
1174 >     *
1175       * @param factory the factory for creating new threads
1176 <     * @throws NullPointerException if factory is null
1176 >     * @throws NullPointerException if the factory is null
1177       * @throws SecurityException if a security manager exists and
1178       *         the caller is not permitted to modify threads
1179       *         because it does not hold {@link
1180 <     *         java.lang.RuntimePermission}<code>("modifyThread")</code>,
1180 >     *         java.lang.RuntimePermission}{@code ("modifyThread")}
1181       */
1182      public ForkJoinPool(ForkJoinWorkerThreadFactory factory) {
1183          this(Runtime.getRuntime().availableProcessors(), factory);
1184      }
1185  
1186      /**
1187 <     * Creates a ForkJoinPool with the given parallelism and factory.
1187 >     * Creates a {@code ForkJoinPool} with the given parallelism and
1188 >     * thread factory.
1189       *
1190 <     * @param parallelism the targeted number of worker threads
1190 >     * @param parallelism the parallelism level
1191       * @param factory the factory for creating new threads
1192       * @throws IllegalArgumentException if parallelism less than or
1193 <     * equal to zero, or greater than implementation limit.
1194 <     * @throws NullPointerException if factory is null
1193 >     *         equal to zero, or greater than implementation limit
1194 >     * @throws NullPointerException if the factory is null
1195       * @throws SecurityException if a security manager exists and
1196       *         the caller is not permitted to modify threads
1197       *         because it does not hold {@link
1198 <     *         java.lang.RuntimePermission}<code>("modifyThread")</code>,
1198 >     *         java.lang.RuntimePermission}{@code ("modifyThread")}
1199       */
1200      public ForkJoinPool(int parallelism, ForkJoinWorkerThreadFactory factory) {
1201 <        if (parallelism <= 0 || parallelism > MAX_THREADS)
375 <            throw new IllegalArgumentException();
1201 >        checkPermission();
1202          if (factory == null)
1203              throw new NullPointerException();
1204 <        checkPermission();
1205 <        this.factory = factory;
1204 >        if (parallelism <= 0 || parallelism > MAX_THREADS)
1205 >            throw new IllegalArgumentException();
1206 >        this.poolNumber = poolNumberGenerator.incrementAndGet();
1207 >        int arraySize = initialArraySizeFor(parallelism);
1208          this.parallelism = parallelism;
1209 +        this.factory = factory;
1210          this.maxPoolSize = MAX_THREADS;
1211          this.maintainsParallelism = true;
1212 <        this.poolNumber = poolNumberGenerator.incrementAndGet();
384 <        this.workerLock = new ReentrantLock();
385 <        this.termination = workerLock.newCondition();
386 <        this.stealCount = new AtomicLong();
1212 >        this.workers = new ForkJoinWorkerThread[arraySize];
1213          this.submissionQueue = new LinkedTransferQueue<ForkJoinTask<?>>();
1214 <        createAndStartInitialWorkers(parallelism);
1215 <    }
1216 <
1217 <    /**
1218 <     * Create new worker using factory.
393 <     * @param index the index to assign worker
394 <     * @return new worker, or null of factory failed
395 <     */
396 <    private ForkJoinWorkerThread createWorker(int index) {
397 <        Thread.UncaughtExceptionHandler h = ueh;
398 <        ForkJoinWorkerThread w = factory.newThread(this);
399 <        if (w != null) {
400 <            w.poolIndex = index;
401 <            w.setDaemon(true);
402 <            w.setName("ForkJoinPool-" + poolNumber + "-worker-" + index);
403 <            if (h != null)
404 <                w.setUncaughtExceptionHandler(h);
405 <        }
406 <        return w;
407 <    }
408 <
409 <    /**
410 <     * Return a good size for worker array given pool size.
411 <     * Currently requires size to be a power of two.
412 <     */
413 <    private static int arraySizeFor(int ps) {
414 <        return ps <= 1? 1 : (1 << (32 - Integer.numberOfLeadingZeros(ps-1)));
415 <    }
416 <
417 <    /**
418 <     * Create or resize array if necessary to hold newLength
419 <     * @return the array
420 <     */
421 <    private ForkJoinWorkerThread[] ensureWorkerArrayCapacity(int newLength) {
422 <        ForkJoinWorkerThread[] ws = workers;
423 <        if (ws == null)
424 <            return workers = new ForkJoinWorkerThread[arraySizeFor(newLength)];
425 <        else if (newLength > ws.length)
426 <            return workers = Arrays.copyOf(ws, arraySizeFor(newLength));
427 <        else
428 <            return ws;
429 <    }
430 <
431 <    /**
432 <     * Try to shrink workers into smaller array after one or more terminate
433 <     */
434 <    private void tryShrinkWorkerArray() {
435 <        ForkJoinWorkerThread[] ws = workers;
436 <        int len = ws.length;
437 <        int last = len - 1;
438 <        while (last >= 0 && ws[last] == null)
439 <            --last;
440 <        int newLength = arraySizeFor(last+1);
441 <        if (newLength < len)
442 <            workers = Arrays.copyOf(ws, newLength);
443 <    }
444 <
445 <    /**
446 <     * Initial worker array and worker creation and startup. (This
447 <     * must be done under lock to avoid interference by some of the
448 <     * newly started threads while creating others.)
449 <     */
450 <    private void createAndStartInitialWorkers(int ps) {
451 <        final ReentrantLock lock = this.workerLock;
452 <        lock.lock();
453 <        try {
454 <            ForkJoinWorkerThread[] ws = ensureWorkerArrayCapacity(ps);
455 <            for (int i = 0; i < ps; ++i) {
456 <                ForkJoinWorkerThread w = createWorker(i);
457 <                if (w != null) {
458 <                    ws[i] = w;
459 <                    w.start();
460 <                    updateWorkerCount(1);
461 <                }
462 <            }
463 <        } finally {
464 <            lock.unlock();
465 <        }
1214 >        this.workerLock = new ReentrantLock();
1215 >        this.terminationLatch = new CountDownLatch(1);
1216 >        // Start first worker; remaining workers added upon first submission
1217 >        workerCounts = ONE_RUNNING | ONE_TOTAL;
1218 >        addWorker();
1219      }
1220  
1221      /**
1222 <     * Worker creation and startup for threads added via setParallelism.
1223 <     */
1224 <    private void createAndStartAddedWorkers() {
1225 <        resumeAllSpares();  // Allow spares to convert to nonspare
1226 <        int ps = parallelism;
1227 <        ForkJoinWorkerThread[] ws = ensureWorkerArrayCapacity(ps);
1228 <        int len = ws.length;
1229 <        // Sweep through slots, to keep lowest indices most populated
1230 <        int k = 0;
1231 <        while (k < len) {
1232 <            if (ws[k] != null) {
480 <                ++k;
481 <                continue;
482 <            }
483 <            int s = workerCounts;
484 <            int tc = totalCountOf(s);
485 <            int rc = runningCountOf(s);
486 <            if (rc >= ps || tc >= ps)
487 <                break;
488 <            if (casWorkerCounts (s, workerCountsFor(tc+1, rc+1))) {
489 <                ForkJoinWorkerThread w = createWorker(k);
490 <                if (w != null) {
491 <                    ws[k++] = w;
492 <                    w.start();
493 <                }
494 <                else {
495 <                    updateWorkerCount(-1); // back out on failed creation
496 <                    break;
497 <                }
498 <            }
499 <        }
1222 >     * Returns initial power of two size for workers array.
1223 >     * @param pc the initial parallelism level
1224 >     */
1225 >    private static int initialArraySizeFor(int pc) {
1226 >        // See Hackers Delight, sec 3.2. We know MAX_THREADS < (1 >>> 16)
1227 >        int size = pc < MAX_THREADS ? pc + 1 : MAX_THREADS;
1228 >        size |= size >>> 1;
1229 >        size |= size >>> 2;
1230 >        size |= size >>> 4;
1231 >        size |= size >>> 8;
1232 >        return size + 1;
1233      }
1234  
1235      // Execution methods
# Line 505 | Line 1238 | public class ForkJoinPool extends Abstra
1238       * Common code for execute, invoke and submit
1239       */
1240      private <T> void doSubmit(ForkJoinTask<T> task) {
1241 <        if (isShutdown())
1241 >        if (task == null)
1242 >            throw new NullPointerException();
1243 >        if (runState >= SHUTDOWN)
1244              throw new RejectedExecutionException();
1245          submissionQueue.offer(task);
1246 <        signalIdleWorkers(true);
1246 >        advanceEventCount();
1247 >        releaseWaiters();
1248 >        if ((workerCounts >>> TOTAL_COUNT_SHIFT) < parallelism)
1249 >            ensureEnoughTotalWorkers();
1250      }
1251  
1252      /**
1253 <     * Performs the given task; returning its result upon completion
1253 >     * Performs the given task, returning its result upon completion.
1254 >     *
1255       * @param task the task
1256       * @return the task's result
1257 <     * @throws NullPointerException if task is null
1258 <     * @throws RejectedExecutionException if pool is shut down
1257 >     * @throws NullPointerException if the task is null
1258 >     * @throws RejectedExecutionException if the task cannot be
1259 >     *         scheduled for execution
1260       */
1261      public <T> T invoke(ForkJoinTask<T> task) {
1262          doSubmit(task);
# Line 525 | Line 1265 | public class ForkJoinPool extends Abstra
1265  
1266      /**
1267       * Arranges for (asynchronous) execution of the given task.
1268 +     *
1269       * @param task the task
1270 <     * @throws NullPointerException if task is null
1271 <     * @throws RejectedExecutionException if pool is shut down
1270 >     * @throws NullPointerException if the task is null
1271 >     * @throws RejectedExecutionException if the task cannot be
1272 >     *         scheduled for execution
1273       */
1274 <    public <T> void execute(ForkJoinTask<T> task) {
1274 >    public void execute(ForkJoinTask<?> task) {
1275          doSubmit(task);
1276      }
1277  
1278      // AbstractExecutorService methods
1279  
1280 +    /**
1281 +     * @throws NullPointerException if the task is null
1282 +     * @throws RejectedExecutionException if the task cannot be
1283 +     *         scheduled for execution
1284 +     */
1285      public void execute(Runnable task) {
1286 <        doSubmit(new AdaptedRunnable<Void>(task, null));
1286 >        ForkJoinTask<?> job;
1287 >        if (task instanceof ForkJoinTask<?>) // avoid re-wrap
1288 >            job = (ForkJoinTask<?>) task;
1289 >        else
1290 >            job = ForkJoinTask.adapt(task, null);
1291 >        doSubmit(job);
1292      }
1293  
1294 +    /**
1295 +     * @throws NullPointerException if the task is null
1296 +     * @throws RejectedExecutionException if the task cannot be
1297 +     *         scheduled for execution
1298 +     */
1299      public <T> ForkJoinTask<T> submit(Callable<T> task) {
1300 <        ForkJoinTask<T> job = new AdaptedCallable<T>(task);
1300 >        ForkJoinTask<T> job = ForkJoinTask.adapt(task);
1301          doSubmit(job);
1302          return job;
1303      }
1304  
1305 +    /**
1306 +     * @throws NullPointerException if the task is null
1307 +     * @throws RejectedExecutionException if the task cannot be
1308 +     *         scheduled for execution
1309 +     */
1310      public <T> ForkJoinTask<T> submit(Runnable task, T result) {
1311 <        ForkJoinTask<T> job = new AdaptedRunnable<T>(task, result);
1311 >        ForkJoinTask<T> job = ForkJoinTask.adapt(task, result);
1312          doSubmit(job);
1313          return job;
1314      }
1315  
1316 +    /**
1317 +     * @throws NullPointerException if the task is null
1318 +     * @throws RejectedExecutionException if the task cannot be
1319 +     *         scheduled for execution
1320 +     */
1321      public ForkJoinTask<?> submit(Runnable task) {
1322 <        ForkJoinTask<Void> job = new AdaptedRunnable<Void>(task, null);
1322 >        ForkJoinTask<?> job;
1323 >        if (task instanceof ForkJoinTask<?>) // avoid re-wrap
1324 >            job = (ForkJoinTask<?>) task;
1325 >        else
1326 >            job = ForkJoinTask.adapt(task, null);
1327          doSubmit(job);
1328          return job;
1329      }
1330  
1331      /**
1332 <     * Adaptor for Runnables. This implements RunnableFuture
1333 <     * to be compliant with AbstractExecutorService constraints
1332 >     * Submits a ForkJoinTask for execution.
1333 >     *
1334 >     * @param task the task to submit
1335 >     * @return the task
1336 >     * @throws NullPointerException if the task is null
1337 >     * @throws RejectedExecutionException if the task cannot be
1338 >     *         scheduled for execution
1339       */
1340 <    static final class AdaptedRunnable<T> extends ForkJoinTask<T>
1341 <        implements RunnableFuture<T> {
1342 <        final Runnable runnable;
567 <        final T resultOnCompletion;
568 <        T result;
569 <        AdaptedRunnable(Runnable runnable, T result) {
570 <            if (runnable == null) throw new NullPointerException();
571 <            this.runnable = runnable;
572 <            this.resultOnCompletion = result;
573 <        }
574 <        public T getRawResult() { return result; }
575 <        public void setRawResult(T v) { result = v; }
576 <        public boolean exec() {
577 <            runnable.run();
578 <            result = resultOnCompletion;
579 <            return true;
580 <        }
581 <        public void run() { invoke(); }
1340 >    public <T> ForkJoinTask<T> submit(ForkJoinTask<T> task) {
1341 >        doSubmit(task);
1342 >        return task;
1343      }
1344  
1345      /**
1346 <     * Adaptor for Callables
1347 <     */
1348 <    static final class AdaptedCallable<T> extends ForkJoinTask<T>
588 <        implements RunnableFuture<T> {
589 <        final Callable<T> callable;
590 <        T result;
591 <        AdaptedCallable(Callable<T> callable) {
592 <            if (callable == null) throw new NullPointerException();
593 <            this.callable = callable;
594 <        }
595 <        public T getRawResult() { return result; }
596 <        public void setRawResult(T v) { result = v; }
597 <        public boolean exec() {
598 <            try {
599 <                result = callable.call();
600 <                return true;
601 <            } catch (Error err) {
602 <                throw err;
603 <            } catch (RuntimeException rex) {
604 <                throw rex;
605 <            } catch (Exception ex) {
606 <                throw new RuntimeException(ex);
607 <            }
608 <        }
609 <        public void run() { invoke(); }
610 <    }
611 <
1346 >     * @throws NullPointerException       {@inheritDoc}
1347 >     * @throws RejectedExecutionException {@inheritDoc}
1348 >     */
1349      public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) {
1350 <        ArrayList<ForkJoinTask<T>> ts =
1350 >        ArrayList<ForkJoinTask<T>> forkJoinTasks =
1351              new ArrayList<ForkJoinTask<T>>(tasks.size());
1352 <        for (Callable<T> c : tasks)
1353 <            ts.add(new AdaptedCallable<T>(c));
1354 <        invoke(new InvokeAll<T>(ts));
1355 <        return (List<Future<T>>)(List)ts;
1352 >        for (Callable<T> task : tasks)
1353 >            forkJoinTasks.add(ForkJoinTask.adapt(task));
1354 >        invoke(new InvokeAll<T>(forkJoinTasks));
1355 >
1356 >        @SuppressWarnings({"unchecked", "rawtypes"})
1357 >            List<Future<T>> futures = (List<Future<T>>) (List) forkJoinTasks;
1358 >        return futures;
1359      }
1360  
1361      static final class InvokeAll<T> extends RecursiveAction {
1362          final ArrayList<ForkJoinTask<T>> tasks;
1363          InvokeAll(ArrayList<ForkJoinTask<T>> tasks) { this.tasks = tasks; }
1364          public void compute() {
1365 <            try { invokeAll(tasks); } catch(Exception ignore) {}
1365 >            try { invokeAll(tasks); }
1366 >            catch (Exception ignore) {}
1367          }
1368 +        private static final long serialVersionUID = -7914297376763021607L;
1369      }
1370  
629    // Configuration and status settings and queries
630
1371      /**
1372 <     * Returns the factory used for constructing new workers
1372 >     * Returns the factory used for constructing new workers.
1373       *
1374       * @return the factory used for constructing new workers
1375       */
# Line 640 | Line 1380 | public class ForkJoinPool extends Abstra
1380      /**
1381       * Returns the handler for internal worker threads that terminate
1382       * due to unrecoverable errors encountered while executing tasks.
1383 <     * @return the handler, or null if none
1383 >     *
1384 >     * @return the handler, or {@code null} if none
1385       */
1386      public Thread.UncaughtExceptionHandler getUncaughtExceptionHandler() {
1387 <        Thread.UncaughtExceptionHandler h;
1388 <        final ReentrantLock lock = this.workerLock;
648 <        lock.lock();
649 <        try {
650 <            h = ueh;
651 <        } finally {
652 <            lock.unlock();
653 <        }
654 <        return h;
1387 >        workerCountReadFence();
1388 >        return ueh;
1389      }
1390  
1391      /**
# Line 661 | Line 1395 | public class ForkJoinPool extends Abstra
1395       * as handler.
1396       *
1397       * @param h the new handler
1398 <     * @return the old handler, or null if none
1398 >     * @return the old handler, or {@code null} if none
1399       * @throws SecurityException if a security manager exists and
1400       *         the caller is not permitted to modify threads
1401       *         because it does not hold {@link
1402 <     *         java.lang.RuntimePermission}<code>("modifyThread")</code>,
1402 >     *         java.lang.RuntimePermission}{@code ("modifyThread")}
1403       */
1404      public Thread.UncaughtExceptionHandler
1405          setUncaughtExceptionHandler(Thread.UncaughtExceptionHandler h) {
1406          checkPermission();
1407 <        Thread.UncaughtExceptionHandler old = null;
1408 <        final ReentrantLock lock = this.workerLock;
1409 <        lock.lock();
676 <        try {
677 <            old = ueh;
1407 >        workerCountReadFence();
1408 >        Thread.UncaughtExceptionHandler old = ueh;
1409 >        if (h != old) {
1410              ueh = h;
1411 <            ForkJoinWorkerThread[] ws = workers;
1412 <            for (int i = 0; i < ws.length; ++i) {
681 <                ForkJoinWorkerThread w = ws[i];
1411 >            workerCountWriteFence();
1412 >            for (ForkJoinWorkerThread w : workers) {
1413                  if (w != null)
1414                      w.setUncaughtExceptionHandler(h);
1415              }
685        } finally {
686            lock.unlock();
1416          }
1417          return old;
1418      }
1419  
691
1420      /**
1421 <     * Sets the target paralleism level of this pool.
1421 >     * Sets the target parallelism level of this pool.
1422 >     *
1423       * @param parallelism the target parallelism
1424       * @throws IllegalArgumentException if parallelism less than or
1425 <     * equal to zero or greater than maximum size bounds.
1425 >     * equal to zero or greater than maximum size bounds
1426       * @throws SecurityException if a security manager exists and
1427       *         the caller is not permitted to modify threads
1428       *         because it does not hold {@link
1429 <     *         java.lang.RuntimePermission}<code>("modifyThread")</code>,
1429 >     *         java.lang.RuntimePermission}{@code ("modifyThread")}
1430       */
1431      public void setParallelism(int parallelism) {
1432          checkPermission();
1433          if (parallelism <= 0 || parallelism > maxPoolSize)
1434              throw new IllegalArgumentException();
1435 <        final ReentrantLock lock = this.workerLock;
1436 <        lock.lock();
1437 <        try {
1438 <            if (!isTerminating()) {
1439 <                int p = this.parallelism;
1440 <                this.parallelism = parallelism;
1441 <                if (parallelism > p)
1442 <                    createAndStartAddedWorkers();
1443 <                else
1444 <                    trimSpares();
1435 >        workerCountReadFence();
1436 >        int pc = this.parallelism;
1437 >        if (pc != parallelism) {
1438 >            this.parallelism = parallelism;
1439 >            workerCountWriteFence();
1440 >            // Release spares. If too many, some will die after re-suspend
1441 >            for (ForkJoinWorkerThread w : workers) {
1442 >                if (w != null && w.tryUnsuspend()) {
1443 >                    updateRunningCount(1);
1444 >                    LockSupport.unpark(w);
1445 >                }
1446              }
1447 <        } finally {
1448 <            lock.unlock();
1447 >            ensureEnoughTotalWorkers();
1448 >            advanceEventCount();
1449 >            releaseWaiters(); // force config recheck by existing workers
1450          }
720        signalIdleWorkers(false);
1451      }
1452  
1453      /**
1454 <     * Returns the targeted number of worker threads in this pool.
1454 >     * Returns the targeted parallelism level of this pool.
1455       *
1456 <     * @return the targeted number of worker threads in this pool
1456 >     * @return the targeted parallelism level of this pool
1457       */
1458      public int getParallelism() {
1459 +        //        workerCountReadFence(); // inlined below
1460 +        int ignore = workerCounts;
1461          return parallelism;
1462      }
1463  
1464      /**
1465       * Returns the number of worker threads that have started but not
1466       * yet terminated.  This result returned by this method may differ
1467 <     * from <code>getParallelism</code> when threads are created to
1467 >     * from {@link #getParallelism} when threads are created to
1468       * maintain parallelism when others are cooperatively blocked.
1469       *
1470       * @return the number of worker threads
1471       */
1472      public int getPoolSize() {
1473 <        return totalCountOf(workerCounts);
1473 >        return workerCounts >>> TOTAL_COUNT_SHIFT;
1474      }
1475  
1476      /**
1477       * Returns the maximum number of threads allowed to exist in the
1478 <     * pool, even if there are insufficient unblocked running threads.
1478 >     * pool. Unless set using {@link #setMaximumPoolSize}, the
1479 >     * maximum is an implementation-defined value designed only to
1480 >     * prevent runaway growth.
1481 >     *
1482       * @return the maximum
1483       */
1484      public int getMaximumPoolSize() {
1485 +        workerCountReadFence();
1486          return maxPoolSize;
1487      }
1488  
1489      /**
1490       * Sets the maximum number of threads allowed to exist in the
1491 <     * pool, even if there are insufficient unblocked running threads.
1492 <     * Setting this value has no effect on current pool size. It
1493 <     * controls construction of new threads.
1494 <     * @throws IllegalArgumentException if negative or greater then
1495 <     * internal implementation limit.
1491 >     * pool. The given value should normally be greater than or equal
1492 >     * to the {@link #getParallelism parallelism} level. Setting this
1493 >     * value has no effect on current pool size. It controls
1494 >     * construction of new threads. The use of this method may cause
1495 >     * tasks that intrinsically require extra threads for dependent
1496 >     * computations to indefinitely stall. If you are instead trying
1497 >     * to minimize internal thread creation, consider setting {link
1498 >     * #setMaintainsParallelism} as false.
1499 >     *
1500 >     * @throws IllegalArgumentException if negative or greater than
1501 >     * internal implementation limit
1502       */
1503      public void setMaximumPoolSize(int newMax) {
1504          if (newMax < 0 || newMax > MAX_THREADS)
1505              throw new IllegalArgumentException();
1506          maxPoolSize = newMax;
1507 +        workerCountWriteFence();
1508      }
1509  
767
1510      /**
1511 <     * Returns true if this pool dynamically maintains its target
1512 <     * parallelism level. If false, new threads are added only to
1513 <     * avoid possible starvation.
1514 <     * This setting is by default true;
1515 <     * @return true if maintains parallelism
1511 >     * Returns {@code true} if this pool dynamically maintains its
1512 >     * target parallelism level. If false, new threads are added only
1513 >     * to avoid possible starvation.  This setting is by default true.
1514 >     *
1515 >     * @return {@code true} if maintains parallelism
1516       */
1517      public boolean getMaintainsParallelism() {
1518 +        workerCountReadFence();
1519          return maintainsParallelism;
1520      }
1521  
# Line 780 | Line 1523 | public class ForkJoinPool extends Abstra
1523       * Sets whether this pool dynamically maintains its target
1524       * parallelism level. If false, new threads are added only to
1525       * avoid possible starvation.
1526 <     * @param enable true to maintains parallelism
1526 >     *
1527 >     * @param enable {@code true} to maintain parallelism
1528       */
1529      public void setMaintainsParallelism(boolean enable) {
1530          maintainsParallelism = enable;
1531 +        workerCountWriteFence();
1532 +    }
1533 +
1534 +    /**
1535 +     * Establishes local first-in-first-out scheduling mode for forked
1536 +     * tasks that are never joined. This mode may be more appropriate
1537 +     * than default locally stack-based mode in applications in which
1538 +     * worker threads only process asynchronous tasks.  This method is
1539 +     * designed to be invoked only when the pool is quiescent, and
1540 +     * typically only before any tasks are submitted. The effects of
1541 +     * invocations at other times may be unpredictable.
1542 +     *
1543 +     * @param async if {@code true}, use locally FIFO scheduling
1544 +     * @return the previous mode
1545 +     * @see #getAsyncMode
1546 +     */
1547 +    public boolean setAsyncMode(boolean async) {
1548 +        workerCountReadFence();
1549 +        boolean oldMode = locallyFifo;
1550 +        if (oldMode != async) {
1551 +            locallyFifo = async;
1552 +            workerCountWriteFence();
1553 +            for (ForkJoinWorkerThread w : workers) {
1554 +                if (w != null)
1555 +                    w.setAsyncMode(async);
1556 +            }
1557 +        }
1558 +        return oldMode;
1559 +    }
1560 +
1561 +    /**
1562 +     * Returns {@code true} if this pool uses local first-in-first-out
1563 +     * scheduling mode for forked tasks that are never joined.
1564 +     *
1565 +     * @return {@code true} if this pool uses async mode
1566 +     * @see #setAsyncMode
1567 +     */
1568 +    public boolean getAsyncMode() {
1569 +        workerCountReadFence();
1570 +        return locallyFifo;
1571      }
1572  
1573      /**
1574       * Returns an estimate of the number of worker threads that are
1575       * not blocked waiting to join tasks or for other managed
1576 <     * synchronization.
1576 >     * synchronization. This method may overestimate the
1577 >     * number of running threads.
1578       *
1579       * @return the number of worker threads
1580       */
1581      public int getRunningThreadCount() {
1582 <        return runningCountOf(workerCounts);
1582 >        return workerCounts & RUNNING_COUNT_MASK;
1583      }
1584  
1585      /**
1586       * Returns an estimate of the number of threads that are currently
1587       * stealing or executing tasks. This method may overestimate the
1588       * number of active threads.
1589 <     * @return the number of active threads.
1589 >     *
1590 >     * @return the number of active threads
1591       */
1592      public int getActiveThreadCount() {
1593 <        return activeCountOf(runControl);
1593 >        return runState & ACTIVE_COUNT_MASK;
1594      }
1595  
1596      /**
1597 <     * Returns an estimate of the number of threads that are currently
1598 <     * idle waiting for tasks. This method may underestimate the
1599 <     * number of idle threads.
1600 <     * @return the number of idle threads.
1601 <     */
1602 <    final int getIdleThreadCount() {
1603 <        int c = runningCountOf(workerCounts) - activeCountOf(runControl);
1604 <        return (c <= 0)? 0 : c;
1605 <    }
820 <
821 <    /**
822 <     * Returns true if all worker threads are currently idle. An idle
823 <     * worker is one that cannot obtain a task to execute because none
824 <     * are available to steal from other threads, and there are no
825 <     * pending submissions to the pool. This method is conservative:
826 <     * It might not return true immediately upon idleness of all
827 <     * threads, but will eventually become true if threads remain
828 <     * inactive.
829 <     * @return true if all threads are currently idle
1597 >     * Returns {@code true} if all worker threads are currently idle.
1598 >     * An idle worker is one that cannot obtain a task to execute
1599 >     * because none are available to steal from other threads, and
1600 >     * there are no pending submissions to the pool. This method is
1601 >     * conservative; it might not return {@code true} immediately upon
1602 >     * idleness of all threads, but will eventually become true if
1603 >     * threads remain inactive.
1604 >     *
1605 >     * @return {@code true} if all threads are currently idle
1606       */
1607      public boolean isQuiescent() {
1608 <        return activeCountOf(runControl) == 0;
1608 >        return (runState & ACTIVE_COUNT_MASK) == 0;
1609      }
1610  
1611      /**
# Line 837 | Line 1613 | public class ForkJoinPool extends Abstra
1613       * one thread's work queue by another. The reported value
1614       * underestimates the actual total number of steals when the pool
1615       * is not quiescent. This value may be useful for monitoring and
1616 <     * tuning fork/join programs: In general, steal counts should be
1616 >     * tuning fork/join programs: in general, steal counts should be
1617       * high enough to keep threads busy, but low enough to avoid
1618       * overhead and contention across threads.
1619 <     * @return the number of steals.
1619 >     *
1620 >     * @return the number of steals
1621       */
1622      public long getStealCount() {
1623 <        return stealCount.get();
847 <    }
848 <
849 <    /**
850 <     * Accumulate steal count from a worker. Call only
851 <     * when worker known to be idle.
852 <     */
853 <    private void updateStealCount(ForkJoinWorkerThread w) {
854 <        int sc = w.getAndClearStealCount();
855 <        if (sc != 0)
856 <            stealCount.addAndGet(sc);
1623 >        return stealCount;
1624      }
1625  
1626      /**
# Line 863 | Line 1630 | public class ForkJoinPool extends Abstra
1630       * an approximation, obtained by iterating across all threads in
1631       * the pool. This method may be useful for tuning task
1632       * granularities.
1633 <     * @return the number of queued tasks.
1633 >     *
1634 >     * @return the number of queued tasks
1635       */
1636      public long getQueuedTaskCount() {
1637          long count = 0;
1638 <        ForkJoinWorkerThread[] ws = workers;
1639 <        for (int i = 0; i < ws.length; ++i) {
1640 <            ForkJoinWorkerThread t = ws[i];
873 <            if (t != null)
874 <                count += t.getQueueSize();
1638 >        for (ForkJoinWorkerThread w : workers) {
1639 >            if (w != null)
1640 >                count += w.getQueueSize();
1641          }
1642          return count;
1643      }
1644  
1645      /**
1646 <     * Returns an estimate of the number tasks submitted to this pool
1647 <     * that have not yet begun executing. This method takes time
1646 >     * Returns an estimate of the number of tasks submitted to this
1647 >     * pool that have not yet begun executing.  This method takes time
1648       * proportional to the number of submissions.
1649 <     * @return the number of queued submissions.
1649 >     *
1650 >     * @return the number of queued submissions
1651       */
1652      public int getQueuedSubmissionCount() {
1653          return submissionQueue.size();
1654      }
1655  
1656      /**
1657 <     * Returns true if there are any tasks submitted to this pool
1658 <     * that have not yet begun executing.
1659 <     * @return <code>true</code> if there are any queued submissions.
1657 >     * Returns {@code true} if there are any tasks submitted to this
1658 >     * pool that have not yet begun executing.
1659 >     *
1660 >     * @return {@code true} if there are any queued submissions
1661       */
1662      public boolean hasQueuedSubmissions() {
1663          return !submissionQueue.isEmpty();
# Line 899 | Line 1667 | public class ForkJoinPool extends Abstra
1667       * Removes and returns the next unexecuted submission if one is
1668       * available.  This method may be useful in extensions to this
1669       * class that re-assign work in systems with multiple pools.
1670 <     * @return the next submission, or null if none
1670 >     *
1671 >     * @return the next submission, or {@code null} if none
1672       */
1673      protected ForkJoinTask<?> pollSubmission() {
1674          return submissionQueue.poll();
1675      }
1676  
1677      /**
1678 +     * Removes all available unexecuted submitted and forked tasks
1679 +     * from scheduling queues and adds them to the given collection,
1680 +     * without altering their execution status. These may include
1681 +     * artificially generated or wrapped tasks. This method is
1682 +     * designed to be invoked only when the pool is known to be
1683 +     * quiescent. Invocations at other times may not remove all
1684 +     * tasks. A failure encountered while attempting to add elements
1685 +     * to collection {@code c} may result in elements being in
1686 +     * neither, either or both collections when the associated
1687 +     * exception is thrown.  The behavior of this operation is
1688 +     * undefined if the specified collection is modified while the
1689 +     * operation is in progress.
1690 +     *
1691 +     * @param c the collection to transfer elements into
1692 +     * @return the number of elements transferred
1693 +     */
1694 +    protected int drainTasksTo(Collection<? super ForkJoinTask<?>> c) {
1695 +        int n = submissionQueue.drainTo(c);
1696 +        for (ForkJoinWorkerThread w : workers) {
1697 +            if (w != null)
1698 +                n += w.drainTasksTo(c);
1699 +        }
1700 +        return n;
1701 +    }
1702 +
1703 +    /**
1704       * Returns a string identifying this pool, as well as its state,
1705       * including indications of run state, parallelism level, and
1706       * worker and task counts.
# Line 913 | Line 1708 | public class ForkJoinPool extends Abstra
1708       * @return a string identifying this pool, as well as its state
1709       */
1710      public String toString() {
916        int ps = parallelism;
917        int wc = workerCounts;
918        int rc = runControl;
1711          long st = getStealCount();
1712          long qt = getQueuedTaskCount();
1713          long qs = getQueuedSubmissionCount();
1714 +        int wc = workerCounts;
1715 +        int tc = wc >>> TOTAL_COUNT_SHIFT;
1716 +        int rc = wc & RUNNING_COUNT_MASK;
1717 +        int pc = parallelism;
1718 +        int rs = runState;
1719 +        int ac = rs & ACTIVE_COUNT_MASK;
1720          return super.toString() +
1721 <            "[" + runStateToString(runStateOf(rc)) +
1722 <            ", parallelism = " + ps +
1723 <            ", size = " + totalCountOf(wc) +
1724 <            ", active = " + activeCountOf(rc) +
1725 <            ", running = " + runningCountOf(wc) +
1721 >            "[" + runLevelToString(rs) +
1722 >            ", parallelism = " + pc +
1723 >            ", size = " + tc +
1724 >            ", active = " + ac +
1725 >            ", running = " + rc +
1726              ", steals = " + st +
1727              ", tasks = " + qt +
1728              ", submissions = " + qs +
1729              "]";
1730      }
1731  
1732 <    private static String runStateToString(int rs) {
1733 <        switch(rs) {
1734 <        case RUNNING: return "Running";
1735 <        case SHUTDOWN: return "Shutting down";
1736 <        case TERMINATING: return "Terminating";
939 <        case TERMINATED: return "Terminated";
940 <        default: throw new Error("Unknown run state");
941 <        }
1732 >    private static String runLevelToString(int s) {
1733 >        return ((s & TERMINATED) != 0 ? "Terminated" :
1734 >                ((s & TERMINATING) != 0 ? "Terminating" :
1735 >                 ((s & SHUTDOWN) != 0 ? "Shutting down" :
1736 >                  "Running")));
1737      }
1738  
944    // lifecycle control
945
1739      /**
1740       * Initiates an orderly shutdown in which previously submitted
1741       * tasks are executed, but no new tasks will be accepted.
1742       * Invocation has no additional effect if already shut down.
1743       * Tasks that are in the process of being submitted concurrently
1744       * during the course of this method may or may not be rejected.
1745 +     *
1746       * @throws SecurityException if a security manager exists and
1747       *         the caller is not permitted to modify threads
1748       *         because it does not hold {@link
1749 <     *         java.lang.RuntimePermission}<code>("modifyThread")</code>,
1749 >     *         java.lang.RuntimePermission}{@code ("modifyThread")}
1750       */
1751      public void shutdown() {
1752          checkPermission();
1753 <        transitionRunStateTo(SHUTDOWN);
1754 <        if (canTerminateOnShutdown(runControl))
961 <            terminateOnShutdown();
1753 >        advanceRunLevel(SHUTDOWN);
1754 >        tryTerminate(false);
1755      }
1756  
1757      /**
1758 <     * Attempts to stop all actively executing tasks, and cancels all
1759 <     * waiting tasks.  Tasks that are in the process of being
1760 <     * submitted or executed concurrently during the course of this
1761 <     * method may or may not be rejected. Unlike some other executors,
1762 <     * this method cancels rather than collects non-executed tasks,
1763 <     * so always returns an empty list.
1758 >     * Attempts to cancel and/or stop all tasks, and reject all
1759 >     * subsequently submitted tasks.  Tasks that are in the process of
1760 >     * being submitted or executed concurrently during the course of
1761 >     * this method may or may not be rejected. This method cancels
1762 >     * both existing and unexecuted tasks, in order to permit
1763 >     * termination in the presence of task dependencies. So the method
1764 >     * always returns an empty list (unlike the case for some other
1765 >     * Executors).
1766 >     *
1767       * @return an empty list
1768       * @throws SecurityException if a security manager exists and
1769       *         the caller is not permitted to modify threads
1770       *         because it does not hold {@link
1771 <     *         java.lang.RuntimePermission}<code>("modifyThread")</code>,
1771 >     *         java.lang.RuntimePermission}{@code ("modifyThread")}
1772       */
1773      public List<Runnable> shutdownNow() {
1774          checkPermission();
1775 <        terminate();
1775 >        tryTerminate(true);
1776          return Collections.emptyList();
1777      }
1778  
1779      /**
1780 <     * Returns <code>true</code> if all tasks have completed following shut down.
1780 >     * Returns {@code true} if all tasks have completed following shut down.
1781       *
1782 <     * @return <code>true</code> if all tasks have completed following shut down
1782 >     * @return {@code true} if all tasks have completed following shut down
1783       */
1784      public boolean isTerminated() {
1785 <        return runStateOf(runControl) == TERMINATED;
1785 >        return runState >= TERMINATED;
1786      }
1787  
1788      /**
1789 <     * Returns <code>true</code> if the process of termination has
1790 <     * commenced but possibly not yet completed.
1789 >     * Returns {@code true} if the process of termination has
1790 >     * commenced but not yet completed.  This method may be useful for
1791 >     * debugging. A return of {@code true} reported a sufficient
1792 >     * period after shutdown may indicate that submitted tasks have
1793 >     * ignored or suppressed interruption, causing this executor not
1794 >     * to properly terminate.
1795       *
1796 <     * @return <code>true</code> if terminating
1796 >     * @return {@code true} if terminating but not yet terminated
1797       */
1798      public boolean isTerminating() {
1799 <        return runStateOf(runControl) >= TERMINATING;
1799 >        return (runState & (TERMINATING|TERMINATED)) == TERMINATING;
1800      }
1801  
1802      /**
1803 <     * Returns <code>true</code> if this pool has been shut down.
1803 >     * Returns {@code true} if this pool has been shut down.
1804       *
1805 <     * @return <code>true</code> if this pool has been shut down
1805 >     * @return {@code true} if this pool has been shut down
1806       */
1807      public boolean isShutdown() {
1808 <        return runStateOf(runControl) >= SHUTDOWN;
1808 >        return runState >= SHUTDOWN;
1809      }
1810  
1811      /**
# Line 1015 | Line 1815 | public class ForkJoinPool extends Abstra
1815       *
1816       * @param timeout the maximum time to wait
1817       * @param unit the time unit of the timeout argument
1818 <     * @return <code>true</code> if this executor terminated and
1819 <     *         <code>false</code> if the timeout elapsed before termination
1818 >     * @return {@code true} if this executor terminated and
1819 >     *         {@code false} if the timeout elapsed before termination
1820       * @throws InterruptedException if interrupted while waiting
1821       */
1822      public boolean awaitTermination(long timeout, TimeUnit unit)
1823          throws InterruptedException {
1824 <        long nanos = unit.toNanos(timeout);
1025 <        final ReentrantLock lock = this.workerLock;
1026 <        lock.lock();
1027 <        try {
1028 <            for (;;) {
1029 <                if (isTerminated())
1030 <                    return true;
1031 <                if (nanos <= 0)
1032 <                    return false;
1033 <                nanos = termination.awaitNanos(nanos);
1034 <            }
1035 <        } finally {
1036 <            lock.unlock();
1037 <        }
1038 <    }
1039 <
1040 <    // Shutdown and termination support
1041 <
1042 <    /**
1043 <     * Callback from terminating worker. Null out the corresponding
1044 <     * workers slot, and if terminating, try to terminate, else try to
1045 <     * shrink workers array.
1046 <     * @param w the worker
1047 <     */
1048 <    final void workerTerminated(ForkJoinWorkerThread w) {
1049 <        updateStealCount(w);
1050 <        updateWorkerCount(-1);
1051 <        final ReentrantLock lock = this.workerLock;
1052 <        lock.lock();
1053 <        try {
1054 <            ForkJoinWorkerThread[] ws = workers;
1055 <            int idx = w.poolIndex;
1056 <            if (idx >= 0 && idx < ws.length && ws[idx] == w)
1057 <                ws[idx] = null;
1058 <            if (totalCountOf(workerCounts) == 0) {
1059 <                terminate(); // no-op if already terminating
1060 <                transitionRunStateTo(TERMINATED);
1061 <                termination.signalAll();
1062 <            }
1063 <            else if (!isTerminating()) {
1064 <                tryShrinkWorkerArray();
1065 <                tryResumeSpare(true); // allow replacement
1066 <            }
1067 <        } finally {
1068 <            lock.unlock();
1069 <        }
1070 <        signalIdleWorkers(false);
1824 >        return terminationLatch.await(timeout, unit);
1825      }
1826  
1827      /**
1828 <     * Initiate termination.
1829 <     */
1076 <    private void terminate() {
1077 <        if (transitionRunStateTo(TERMINATING)) {
1078 <            stopAllWorkers();
1079 <            resumeAllSpares();
1080 <            signalIdleWorkers(true);
1081 <            cancelQueuedSubmissions();
1082 <            cancelQueuedWorkerTasks();
1083 <            interruptUnterminatedWorkers();
1084 <            signalIdleWorkers(true); // resignal after interrupt
1085 <        }
1086 <    }
1087 <
1088 <    /**
1089 <     * Possibly terminate when on shutdown state
1090 <     */
1091 <    private void terminateOnShutdown() {
1092 <        if (!hasQueuedSubmissions() && canTerminateOnShutdown(runControl))
1093 <            terminate();
1094 <    }
1095 <
1096 <    /**
1097 <     * Clear out and cancel submissions
1098 <     */
1099 <    private void cancelQueuedSubmissions() {
1100 <        ForkJoinTask<?> task;
1101 <        while ((task = pollSubmission()) != null)
1102 <            task.cancel(false);
1103 <    }
1104 <
1105 <    /**
1106 <     * Clean out worker queues.
1107 <     */
1108 <    private void cancelQueuedWorkerTasks() {
1109 <        final ReentrantLock lock = this.workerLock;
1110 <        lock.lock();
1111 <        try {
1112 <            ForkJoinWorkerThread[] ws = workers;
1113 <            for (int i = 0; i < ws.length; ++i) {
1114 <                ForkJoinWorkerThread t = ws[i];
1115 <                if (t != null)
1116 <                    t.cancelTasks();
1117 <            }
1118 <        } finally {
1119 <            lock.unlock();
1120 <        }
1121 <    }
1122 <
1123 <    /**
1124 <     * Set each worker's status to terminating. Requires lock to avoid
1125 <     * conflicts with add/remove
1126 <     */
1127 <    private void stopAllWorkers() {
1128 <        final ReentrantLock lock = this.workerLock;
1129 <        lock.lock();
1130 <        try {
1131 <            ForkJoinWorkerThread[] ws = workers;
1132 <            for (int i = 0; i < ws.length; ++i) {
1133 <                ForkJoinWorkerThread t = ws[i];
1134 <                if (t != null)
1135 <                    t.shutdownNow();
1136 <            }
1137 <        } finally {
1138 <            lock.unlock();
1139 <        }
1140 <    }
1141 <
1142 <    /**
1143 <     * Interrupt all unterminated workers.  This is not required for
1144 <     * sake of internal control, but may help unstick user code during
1145 <     * shutdown.
1146 <     */
1147 <    private void interruptUnterminatedWorkers() {
1148 <        final ReentrantLock lock = this.workerLock;
1149 <        lock.lock();
1150 <        try {
1151 <            ForkJoinWorkerThread[] ws = workers;
1152 <            for (int i = 0; i < ws.length; ++i) {
1153 <                ForkJoinWorkerThread t = ws[i];
1154 <                if (t != null && !t.isTerminated()) {
1155 <                    try {
1156 <                        t.interrupt();
1157 <                    } catch (SecurityException ignore) {
1158 <                    }
1159 <                }
1160 <            }
1161 <        } finally {
1162 <            lock.unlock();
1163 <        }
1164 <    }
1165 <
1166 <
1167 <    /*
1168 <     * Nodes for event barrier to manage idle threads.
1169 <     *
1170 <     * The event barrier has an event count and a wait queue (actually
1171 <     * a Treiber stack).  Workers are enabled to look for work when
1172 <     * the eventCount is incremented. If they fail to find some,
1173 <     * they may wait for next count. Synchronization events occur only
1174 <     * in enough contexts to maintain overall liveness:
1828 >     * Interface for extending managed parallelism for tasks running
1829 >     * in {@link ForkJoinPool}s.
1830       *
1831 <     *   - Submission of a new task to the pool
1832 <     *   - Creation or termination of a worker
1833 <     *   - pool termination
1834 <     *   - A worker pushing a task on an empty queue
1831 >     * <p>A {@code ManagedBlocker} provides two methods.
1832 >     * Method {@code isReleasable} must return {@code true} if
1833 >     * blocking is not necessary. Method {@code block} blocks the
1834 >     * current thread if necessary (perhaps internally invoking
1835 >     * {@code isReleasable} before actually blocking).
1836       *
1181     * The last case (pushing a task) occurs often enough, and is
1182     * heavy enough compared to simple stack pushes to require some
1183     * special handling: Method signalNonEmptyWorkerQueue returns
1184     * without advancing count if the queue appears to be empty.  This
1185     * would ordinarily result in races causing some queued waiters
1186     * not to be woken up. To avoid this, a worker in sync
1187     * rescans for tasks after being enqueued if it was the first to
1188     * enqueue, and aborts the wait if finding one, also helping to
1189     * signal others. This works well because the worker has nothing
1190     * better to do anyway, and so might as well help alleviate the
1191     * overhead and contention on the threads actually doing work.
1192     *
1193     * Queue nodes are basic Treiber stack nodes, also used for spare
1194     * stack.
1195     */
1196    static final class WaitQueueNode {
1197        WaitQueueNode next; // only written before enqueued
1198        volatile ForkJoinWorkerThread thread; // nulled to cancel wait
1199        final long count; // unused for spare stack
1200        WaitQueueNode(ForkJoinWorkerThread w, long c) {
1201            count = c;
1202            thread = w;
1203        }
1204        final boolean signal() {
1205            ForkJoinWorkerThread t = thread;
1206            thread = null;
1207            if (t != null) {
1208                LockSupport.unpark(t);
1209                return true;
1210            }
1211            return false;
1212        }
1213    }
1214
1215    /**
1216     * Release at least one thread waiting for event count to advance,
1217     * if one exists. If initial attempt fails, release all threads.
1218     * @param all if false, at first try to only release one thread
1219     * @return current event
1220     */
1221    private long releaseIdleWorkers(boolean all) {
1222        long c;
1223        for (;;) {
1224            WaitQueueNode q = barrierStack;
1225            c = eventCount;
1226            long qc;
1227            if (q == null || (qc = q.count) >= c)
1228                break;
1229            if (!all) {
1230                if (casBarrierStack(q, q.next) && q.signal())
1231                    break;
1232                all = true;
1233            }
1234            else if (casBarrierStack(q, null)) {
1235                do {
1236                 q.signal();
1237                } while ((q = q.next) != null);
1238                break;
1239            }
1240        }
1241        return c;
1242    }
1243
1244    /**
1245     * Returns current barrier event count
1246     * @return current barrier event count
1247     */
1248    final long getEventCount() {
1249        long ec = eventCount;
1250        releaseIdleWorkers(true); // release to ensure accurate result
1251        return ec;
1252    }
1253
1254    /**
1255     * Increment event count and release at least one waiting thread,
1256     * if one exists (released threads will in turn wake up others).
1257     * @param all if true, try to wake up all
1258     */
1259    final void signalIdleWorkers(boolean all) {
1260        long c;
1261        do;while (!casEventCount(c = eventCount, c+1));
1262        releaseIdleWorkers(all);
1263    }
1264
1265    /**
1266     * Wake up threads waiting to steal a task. Because method
1267     * sync rechecks availability, it is OK to only proceed if
1268     * queue appears to be non-empty.
1269     */
1270    final void signalNonEmptyWorkerQueue() {
1271        // If CAS fails another signaller must have succeeded
1272        long c;
1273        if (barrierStack != null && casEventCount(c = eventCount, c+1))
1274            releaseIdleWorkers(false);
1275    }
1276
1277    /**
1278     * Waits until event count advances from count, or some thread is
1279     * waiting on a previous count, or there is stealable work
1280     * available. Help wake up others on release.
1281     * @param w the calling worker thread
1282     * @param prev previous value returned by sync (or 0)
1283     * @return current event count
1284     */
1285    final long sync(ForkJoinWorkerThread w, long prev) {
1286        updateStealCount(w);
1287
1288        while (!w.isShutdown() && !isTerminating() &&
1289               (parallelism >= runningCountOf(workerCounts) ||
1290                !suspendIfSpare(w))) { // prefer suspend to waiting here
1291            WaitQueueNode node = null;
1292            boolean queued = false;
1293            for (;;) {
1294                if (!queued) {
1295                    if (eventCount != prev)
1296                        break;
1297                    WaitQueueNode h = barrierStack;
1298                    if (h != null && h.count != prev)
1299                        break; // release below and maybe retry
1300                    if (node == null)
1301                        node = new WaitQueueNode(w, prev);
1302                    queued = casBarrierStack(node.next = h, node);
1303                }
1304                else if (Thread.interrupted() ||
1305                         node.thread == null ||
1306                         (node.next == null && w.prescan()) ||
1307                         eventCount != prev) {
1308                    node.thread = null;
1309                    if (eventCount == prev) // help trigger
1310                        casEventCount(prev, prev+1);
1311                    break;
1312                }
1313                else
1314                    LockSupport.park(this);
1315            }
1316            long ec = eventCount;
1317            if (releaseIdleWorkers(false) != prev)
1318                return ec;
1319        }
1320        return prev; // return old count if aborted
1321    }
1322
1323    //  Parallelism maintenance
1324
1325    /**
1326     * Decrement running count; if too low, add spare.
1327     *
1328     * Conceptually, all we need to do here is add or resume a
1329     * spare thread when one is about to block (and remove or
1330     * suspend it later when unblocked -- see suspendIfSpare).
1331     * However, implementing this idea requires coping with
1332     * several problems: We have imperfect information about the
1333     * states of threads. Some count updates can and usually do
1334     * lag run state changes, despite arrangements to keep them
1335     * accurate (for example, when possible, updating counts
1336     * before signalling or resuming), especially when running on
1337     * dynamic JVMs that don't optimize the infrequent paths that
1338     * update counts. Generating too many threads can make these
1339     * problems become worse, because excess threads are more
1340     * likely to be context-switched with others, slowing them all
1341     * down, especially if there is no work available, so all are
1342     * busy scanning or idling.  Also, excess spare threads can
1343     * only be suspended or removed when they are idle, not
1344     * immediately when they aren't needed. So adding threads will
1345     * raise parallelism level for longer than necessary.  Also,
1346     * FJ applications often enounter highly transient peaks when
1347     * many threads are blocked joining, but for less time than it
1348     * takes to create or resume spares.
1349     *
1350     * @param joinMe if non-null, return early if done
1351     * @param maintainParallelism if true, try to stay within
1352     * target counts, else create only to avoid starvation
1353     * @return true if joinMe known to be done
1354     */
1355    final boolean preJoin(ForkJoinTask<?> joinMe, boolean maintainParallelism) {
1356        maintainParallelism &= maintainsParallelism; // overrride
1357        boolean dec = false;  // true when running count decremented
1358        while (spareStack == null || !tryResumeSpare(dec)) {
1359            int counts = workerCounts;
1360            if (dec || (dec = casWorkerCounts(counts, --counts))) { // CAS cheat
1361                if (!needSpare(counts, maintainParallelism))
1362                    break;
1363                if (joinMe.status < 0)
1364                    return true;
1365                if (tryAddSpare(counts))
1366                    break;
1367            }
1368        }
1369        return false;
1370    }
1371
1372    /**
1373     * Same idea as preJoin
1374     */
1375    final boolean preBlock(ManagedBlocker blocker, boolean maintainParallelism){
1376        maintainParallelism &= maintainsParallelism;
1377        boolean dec = false;
1378        while (spareStack == null || !tryResumeSpare(dec)) {
1379            int counts = workerCounts;
1380            if (dec || (dec = casWorkerCounts(counts, --counts))) {
1381                if (!needSpare(counts, maintainParallelism))
1382                    break;
1383                if (blocker.isReleasable())
1384                    return true;
1385                if (tryAddSpare(counts))
1386                    break;
1387            }
1388        }
1389        return false;
1390    }
1391
1392    /**
1393     * Returns true if a spare thread appears to be needed.  If
1394     * maintaining parallelism, returns true when the deficit in
1395     * running threads is more than the surplus of total threads, and
1396     * there is apparently some work to do.  This self-limiting rule
1397     * means that the more threads that have already been added, the
1398     * less parallelism we will tolerate before adding another.
1399     * @param counts current worker counts
1400     * @param maintainParallelism try to maintain parallelism
1401     */
1402    private boolean needSpare(int counts, boolean maintainParallelism) {
1403        int ps = parallelism;
1404        int rc = runningCountOf(counts);
1405        int tc = totalCountOf(counts);
1406        int runningDeficit = ps - rc;
1407        int totalSurplus = tc - ps;
1408        return (tc < maxPoolSize &&
1409                (rc == 0 || totalSurplus < 0 ||
1410                 (maintainParallelism &&
1411                  runningDeficit > totalSurplus && mayHaveQueuedWork())));
1412    }
1413
1414    /**
1415     * Returns true if at least one worker queue appears to be
1416     * nonempty. This is expensive but not often called. It is not
1417     * critical that this be accurate, but if not, more or fewer
1418     * running threads than desired might be maintained.
1419     */
1420    private boolean mayHaveQueuedWork() {
1421        ForkJoinWorkerThread[] ws = workers;
1422        int len = ws.length;
1423        ForkJoinWorkerThread v;
1424        for (int i = 0; i < len; ++i) {
1425            if ((v = ws[i]) != null && v.getRawQueueSize() > 0) {
1426                releaseIdleWorkers(false); // help wake up stragglers
1427                return true;
1428            }
1429        }
1430        return false;
1431    }
1432
1433    /**
1434     * Add a spare worker if lock available and no more than the
1435     * expected numbers of threads exist
1436     * @return true if successful
1437     */
1438    private boolean tryAddSpare(int expectedCounts) {
1439        final ReentrantLock lock = this.workerLock;
1440        int expectedRunning = runningCountOf(expectedCounts);
1441        int expectedTotal = totalCountOf(expectedCounts);
1442        boolean success = false;
1443        boolean locked = false;
1444        // confirm counts while locking; CAS after obtaining lock
1445        try {
1446            for (;;) {
1447                int s = workerCounts;
1448                int tc = totalCountOf(s);
1449                int rc = runningCountOf(s);
1450                if (rc > expectedRunning || tc > expectedTotal)
1451                    break;
1452                if (!locked && !(locked = lock.tryLock()))
1453                    break;
1454                if (casWorkerCounts(s, workerCountsFor(tc+1, rc+1))) {
1455                    createAndStartSpare(tc);
1456                    success = true;
1457                    break;
1458                }
1459            }
1460        } finally {
1461            if (locked)
1462                lock.unlock();
1463        }
1464        return success;
1465    }
1466
1467    /**
1468     * Add the kth spare worker. On entry, pool coounts are already
1469     * adjusted to reflect addition.
1470     */
1471    private void createAndStartSpare(int k) {
1472        ForkJoinWorkerThread w = null;
1473        ForkJoinWorkerThread[] ws = ensureWorkerArrayCapacity(k + 1);
1474        int len = ws.length;
1475        // Probably, we can place at slot k. If not, find empty slot
1476        if (k < len && ws[k] != null) {
1477            for (k = 0; k < len && ws[k] != null; ++k)
1478                ;
1479        }
1480        if (k < len && (w = createWorker(k)) != null) {
1481            ws[k] = w;
1482            w.start();
1483        }
1484        else
1485            updateWorkerCount(-1); // adjust on failure
1486        signalIdleWorkers(false);
1487    }
1488
1489    /**
1490     * Suspend calling thread w if there are excess threads.  Called
1491     * only from sync.  Spares are enqueued in a Treiber stack
1492     * using the same WaitQueueNodes as barriers.  They are resumed
1493     * mainly in preJoin, but are also woken on pool events that
1494     * require all threads to check run state.
1495     * @param w the caller
1496     */
1497    private boolean suspendIfSpare(ForkJoinWorkerThread w) {
1498        WaitQueueNode node = null;
1499        int s;
1500        while (parallelism < runningCountOf(s = workerCounts)) {
1501            if (node == null)
1502                node = new WaitQueueNode(w, 0);
1503            if (casWorkerCounts(s, s-1)) { // representation-dependent
1504                // push onto stack
1505                do;while (!casSpareStack(node.next = spareStack, node));
1506
1507                // block until released by resumeSpare
1508                while (node.thread != null) {
1509                    if (!Thread.interrupted())
1510                        LockSupport.park(this);
1511                }
1512                w.activate(); // help warm up
1513                return true;
1514            }
1515        }
1516        return false;
1517    }
1518
1519    /**
1520     * Try to pop and resume a spare thread.
1521     * @param updateCount if true, increment running count on success
1522     * @return true if successful
1523     */
1524    private boolean tryResumeSpare(boolean updateCount) {
1525        WaitQueueNode q;
1526        while ((q = spareStack) != null) {
1527            if (casSpareStack(q, q.next)) {
1528                if (updateCount)
1529                    updateRunningCount(1);
1530                q.signal();
1531                return true;
1532            }
1533        }
1534        return false;
1535    }
1536
1537    /**
1538     * Pop and resume all spare threads. Same idea as
1539     * releaseIdleWorkers.
1540     * @return true if any spares released
1541     */
1542    private boolean resumeAllSpares() {
1543        WaitQueueNode q;
1544        while ( (q = spareStack) != null) {
1545            if (casSpareStack(q, null)) {
1546                do {
1547                    updateRunningCount(1);
1548                    q.signal();
1549                } while ((q = q.next) != null);
1550                return true;
1551            }
1552        }
1553        return false;
1554    }
1555
1556    /**
1557     * Pop and shutdown excessive spare threads. Call only while
1558     * holding lock. This is not guaranteed to eliminate all excess
1559     * threads, only those suspended as spares, which are the ones
1560     * unlikely to be needed in the future.
1561     */
1562    private void trimSpares() {
1563        int surplus = totalCountOf(workerCounts) - parallelism;
1564        WaitQueueNode q;
1565        while (surplus > 0 && (q = spareStack) != null) {
1566            if (casSpareStack(q, null)) {
1567                do {
1568                    updateRunningCount(1);
1569                    ForkJoinWorkerThread w = q.thread;
1570                    if (w != null && surplus > 0 &&
1571                        runningCountOf(workerCounts) > 0 && w.shutdown())
1572                        --surplus;
1573                    q.signal();
1574                } while ((q = q.next) != null);
1575            }
1576        }
1577    }
1578
1579    /**
1580     * Returns approximate number of spares, just for diagnostics.
1581     */
1582    private int countSpares() {
1583        int sum = 0;
1584        for (WaitQueueNode q = spareStack; q != null; q = q.next)
1585            ++sum;
1586        return sum;
1587    }
1588
1589    /**
1590     * Interface for extending managed parallelism for tasks running
1591     * in ForkJoinPools. A ManagedBlocker provides two methods.
1592     * Method <code>isReleasable</code> must return true if blocking is not
1593     * necessary. Method <code>block</code> blocks the current thread
1594     * if necessary (perhaps internally invoking isReleasable before
1595     * actually blocking.).
1837       * <p>For example, here is a ManagedBlocker based on a
1838       * ReentrantLock:
1839 <     * <pre>
1840 <     *   class ManagedLocker implements ManagedBlocker {
1841 <     *     final ReentrantLock lock;
1842 <     *     boolean hasLock = false;
1843 <     *     ManagedLocker(ReentrantLock lock) { this.lock = lock; }
1844 <     *     public boolean block() {
1845 <     *        if (!hasLock)
1846 <     *           lock.lock();
1847 <     *        return true;
1607 <     *     }
1608 <     *     public boolean isReleasable() {
1609 <     *        return hasLock || (hasLock = lock.tryLock());
1610 <     *     }
1839 >     *  <pre> {@code
1840 >     * class ManagedLocker implements ManagedBlocker {
1841 >     *   final ReentrantLock lock;
1842 >     *   boolean hasLock = false;
1843 >     *   ManagedLocker(ReentrantLock lock) { this.lock = lock; }
1844 >     *   public boolean block() {
1845 >     *     if (!hasLock)
1846 >     *       lock.lock();
1847 >     *     return true;
1848       *   }
1849 <     * </pre>
1849 >     *   public boolean isReleasable() {
1850 >     *     return hasLock || (hasLock = lock.tryLock());
1851 >     *   }
1852 >     * }}</pre>
1853       */
1854      public static interface ManagedBlocker {
1855          /**
1856           * Possibly blocks the current thread, for example waiting for
1857           * a lock or condition.
1858 <         * @return true if no additional blocking is necessary (i.e.,
1859 <         * if isReleasable would return true).
1858 >         *
1859 >         * @return {@code true} if no additional blocking is necessary
1860 >         * (i.e., if isReleasable would return true)
1861           * @throws InterruptedException if interrupted while waiting
1862 <         * (the method is not required to do so, but is allowe to).
1862 >         * (the method is not required to do so, but is allowed to)
1863           */
1864          boolean block() throws InterruptedException;
1865  
1866          /**
1867 <         * Returns true if blocking is unnecessary.
1867 >         * Returns {@code true} if blocking is unnecessary.
1868           */
1869          boolean isReleasable();
1870      }
1871  
1872      /**
1873       * Blocks in accord with the given blocker.  If the current thread
1874 <     * is a ForkJoinWorkerThread, this method possibly arranges for a
1875 <     * spare thread to be activated if necessary to ensure parallelism
1876 <     * while the current thread is blocked.  If
1877 <     * <code>maintainParallelism</code> is true and the pool supports
1878 <     * it ({@link #getMaintainsParallelism}), this method attempts to
1879 <     * maintain the pool's nominal parallelism. Otherwise if activates
1880 <     * a thread only if necessary to avoid complete starvation. This
1881 <     * option may be preferable when blockages use timeouts, or are
1882 <     * almost always brief.
1883 <     *
1884 <     * <p> If the caller is not a ForkJoinTask, this method is behaviorally
1885 <     * equivalent to
1886 <     * <pre>
1887 <     *   while (!blocker.isReleasable())
1888 <     *      if (blocker.block())
1889 <     *         return;
1890 <     * </pre>
1891 <     * If the caller is a ForkJoinTask, then the pool may first
1892 <     * be expanded to ensure parallelism, and later adjusted.
1874 >     * is a {@link ForkJoinWorkerThread}, this method possibly
1875 >     * arranges for a spare thread to be activated if necessary to
1876 >     * ensure parallelism while the current thread is blocked.
1877 >     *
1878 >     * <p>If {@code maintainParallelism} is {@code true} and the pool
1879 >     * supports it ({@link #getMaintainsParallelism}), this method
1880 >     * attempts to maintain the pool's nominal parallelism. Otherwise
1881 >     * it activates a thread only if necessary to avoid complete
1882 >     * starvation. This option may be preferable when blockages use
1883 >     * timeouts, or are almost always brief.
1884 >     *
1885 >     * <p>If the caller is not a {@link ForkJoinTask}, this method is
1886 >     * behaviorally equivalent to
1887 >     *  <pre> {@code
1888 >     * while (!blocker.isReleasable())
1889 >     *   if (blocker.block())
1890 >     *     return;
1891 >     * }</pre>
1892 >     *
1893 >     * If the caller is a {@code ForkJoinTask}, then the pool may
1894 >     * first be expanded to ensure parallelism, and later adjusted.
1895       *
1896       * @param blocker the blocker
1897 <     * @param maintainParallelism if true and supported by this pool,
1898 <     * attempt to maintain the pool's nominal parallelism; otherwise
1899 <     * activate a thread only if necessary to avoid complete
1900 <     * starvation.
1901 <     * @throws InterruptedException if blocker.block did so.
1897 >     * @param maintainParallelism if {@code true} and supported by
1898 >     * this pool, attempt to maintain the pool's nominal parallelism;
1899 >     * otherwise activate a thread only if necessary to avoid
1900 >     * complete starvation.
1901 >     * @throws InterruptedException if blocker.block did so
1902       */
1903      public static void managedBlock(ManagedBlocker blocker,
1904                                      boolean maintainParallelism)
1905          throws InterruptedException {
1906          Thread t = Thread.currentThread();
1907 <        ForkJoinPool pool = (t instanceof ForkJoinWorkerThread?
1908 <                             ((ForkJoinWorkerThread)t).pool : null);
1909 <        if (!blocker.isReleasable()) {
1910 <            try {
1911 <                if (pool == null ||
1669 <                    !pool.preBlock(blocker, maintainParallelism))
1670 <                    awaitBlocker(blocker);
1671 <            } finally {
1672 <                if (pool != null)
1673 <                    pool.updateRunningCount(1);
1674 <            }
1675 <        }
1907 >        if (t instanceof ForkJoinWorkerThread)
1908 >            ((ForkJoinWorkerThread) t).pool.
1909 >                doBlock(blocker, maintainParallelism);
1910 >        else
1911 >            awaitBlocker(blocker);
1912      }
1913  
1914 +    /**
1915 +     * Performs Non-FJ blocking
1916 +     */
1917      private static void awaitBlocker(ManagedBlocker blocker)
1918          throws InterruptedException {
1919 <        do;while (!blocker.isReleasable() && !blocker.block());
1919 >        do {} while (!blocker.isReleasable() && !blocker.block());
1920      }
1921  
1922 <    // AbstractExecutorService overrides
1922 >    // AbstractExecutorService overrides.  These rely on undocumented
1923 >    // fact that ForkJoinTask.adapt returns ForkJoinTasks that also
1924 >    // implement RunnableFuture.
1925  
1926      protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
1927 <        return new AdaptedRunnable(runnable, value);
1927 >        return (RunnableFuture<T>) ForkJoinTask.adapt(runnable, value);
1928      }
1929  
1930      protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
1931 <        return new AdaptedCallable(callable);
1931 >        return (RunnableFuture<T>) ForkJoinTask.adapt(callable);
1932      }
1933  
1934 +    // Unsafe mechanics
1935  
1936 <    // Temporary Unsafe mechanics for preliminary release
1936 >    private static final sun.misc.Unsafe UNSAFE = getUnsafe();
1937 >    private static final long workerCountsOffset =
1938 >        objectFieldOffset("workerCounts", ForkJoinPool.class);
1939 >    private static final long runStateOffset =
1940 >        objectFieldOffset("runState", ForkJoinPool.class);
1941 >    private static final long eventCountOffset =
1942 >        objectFieldOffset("eventCount", ForkJoinPool.class);
1943 >    private static final long eventWaitersOffset =
1944 >        objectFieldOffset("eventWaiters",ForkJoinPool.class);
1945 >    private static final long stealCountOffset =
1946 >        objectFieldOffset("stealCount",ForkJoinPool.class);
1947  
1696    static final Unsafe _unsafe;
1697    static final long eventCountOffset;
1698    static final long workerCountsOffset;
1699    static final long runControlOffset;
1700    static final long barrierStackOffset;
1701    static final long spareStackOffset;
1948  
1949 <    static {
1949 >    private static long objectFieldOffset(String field, Class<?> klazz) {
1950          try {
1951 <            if (ForkJoinPool.class.getClassLoader() != null) {
1952 <                Field f = Unsafe.class.getDeclaredField("theUnsafe");
1953 <                f.setAccessible(true);
1954 <                _unsafe = (Unsafe)f.get(null);
1955 <            }
1956 <            else
1711 <                _unsafe = Unsafe.getUnsafe();
1712 <            eventCountOffset = _unsafe.objectFieldOffset
1713 <                (ForkJoinPool.class.getDeclaredField("eventCount"));
1714 <            workerCountsOffset = _unsafe.objectFieldOffset
1715 <                (ForkJoinPool.class.getDeclaredField("workerCounts"));
1716 <            runControlOffset = _unsafe.objectFieldOffset
1717 <                (ForkJoinPool.class.getDeclaredField("runControl"));
1718 <            barrierStackOffset = _unsafe.objectFieldOffset
1719 <                (ForkJoinPool.class.getDeclaredField("barrierStack"));
1720 <            spareStackOffset = _unsafe.objectFieldOffset
1721 <                (ForkJoinPool.class.getDeclaredField("spareStack"));
1722 <        } catch (Exception e) {
1723 <            throw new RuntimeException("Could not initialize intrinsics", e);
1951 >            return UNSAFE.objectFieldOffset(klazz.getDeclaredField(field));
1952 >        } catch (NoSuchFieldException e) {
1953 >            // Convert Exception to corresponding Error
1954 >            NoSuchFieldError error = new NoSuchFieldError(field);
1955 >            error.initCause(e);
1956 >            throw error;
1957          }
1958      }
1959  
1960 <    private boolean casEventCount(long cmp, long val) {
1961 <        return _unsafe.compareAndSwapLong(this, eventCountOffset, cmp, val);
1962 <    }
1963 <    private boolean casWorkerCounts(int cmp, int val) {
1964 <        return _unsafe.compareAndSwapInt(this, workerCountsOffset, cmp, val);
1965 <    }
1966 <    private boolean casRunControl(int cmp, int val) {
1967 <        return _unsafe.compareAndSwapInt(this, runControlOffset, cmp, val);
1968 <    }
1969 <    private boolean casSpareStack(WaitQueueNode cmp, WaitQueueNode val) {
1970 <        return _unsafe.compareAndSwapObject(this, spareStackOffset, cmp, val);
1971 <    }
1972 <    private boolean casBarrierStack(WaitQueueNode cmp, WaitQueueNode val) {
1973 <        return _unsafe.compareAndSwapObject(this, barrierStackOffset, cmp, val);
1960 >    /**
1961 >     * Returns a sun.misc.Unsafe.  Suitable for use in a 3rd party package.
1962 >     * Replace with a simple call to Unsafe.getUnsafe when integrating
1963 >     * into a jdk.
1964 >     *
1965 >     * @return a sun.misc.Unsafe
1966 >     */
1967 >    private static sun.misc.Unsafe getUnsafe() {
1968 >        try {
1969 >            return sun.misc.Unsafe.getUnsafe();
1970 >        } catch (SecurityException se) {
1971 >            try {
1972 >                return java.security.AccessController.doPrivileged
1973 >                    (new java.security
1974 >                     .PrivilegedExceptionAction<sun.misc.Unsafe>() {
1975 >                        public sun.misc.Unsafe run() throws Exception {
1976 >                            java.lang.reflect.Field f = sun.misc
1977 >                                .Unsafe.class.getDeclaredField("theUnsafe");
1978 >                            f.setAccessible(true);
1979 >                            return (sun.misc.Unsafe) f.get(null);
1980 >                        }});
1981 >            } catch (java.security.PrivilegedActionException e) {
1982 >                throw new RuntimeException("Could not initialize intrinsics",
1983 >                                           e.getCause());
1984 >            }
1985 >        }
1986      }
1987   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines