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.23 by dl, Sat Jul 25 15:50:57 2009 UTC vs.
Revision 1.56 by dl, Thu May 27 16:46:48 2010 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines