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.8 by jsr166, Mon Jul 20 21:54:51 2009 UTC vs.
Revision 1.56 by dl, Thu May 27 16:46:48 2010 UTC

# Line 5 | Line 5
5   */
6  
7   package jsr166y;
8 < import java.util.*;
8 >
9   import java.util.concurrent.*;
10 < import java.util.concurrent.locks.*;
11 < import java.util.concurrent.atomic.*;
12 < import sun.misc.Unsafe;
13 < import java.lang.reflect.*;
10 >
11 > import java.util.ArrayList;
12 > import java.util.Arrays;
13 > import java.util.Collection;
14 > import java.util.Collections;
15 > import java.util.List;
16 > import java.util.concurrent.locks.LockSupport;
17 > import java.util.concurrent.locks.ReentrantLock;
18 > import java.util.concurrent.atomic.AtomicInteger;
19 > import java.util.concurrent.CountDownLatch;
20  
21   /**
22 < * An {@link ExecutorService} for running {@link ForkJoinTask}s.  A
23 < * ForkJoinPool provides the entry point for submissions from
24 < * non-ForkJoinTasks, as well as management and monitoring operations.
25 < * Normally a single ForkJoinPool is used for a large number of
20 < * submitted tasks. Otherwise, use would not usually outweigh the
21 < * construction and bookkeeping overhead of creating a large set of
22 < * threads.
22 > * An {@link ExecutorService} for running {@link ForkJoinTask}s.
23 > * A {@code ForkJoinPool} provides the entry point for submissions
24 > * from non-{@code ForkJoinTask}s, as well as management and
25 > * monitoring operations.
26   *
27 < * <p>ForkJoinPools differ from other kinds of Executors mainly in
28 < * that they provide <em>work-stealing</em>: all threads in the pool
29 < * attempt to find and execute subtasks created by other active tasks
30 < * (eventually blocking if none exist). This makes them efficient when
31 < * most tasks spawn other subtasks (as do most ForkJoinTasks), as well
32 < * as the mixed execution of some plain Runnable- or Callable- based
33 < * activities along with ForkJoinTasks. 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
96   */
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      }
344  
345      /**
346 <     * Default ForkJoinWorkerThreadFactory implementation, creates a
346 >     * Default ForkJoinWorkerThreadFactory implementation; creates a
347       * new ForkJoinWorkerThread.
348       */
349      static class  DefaultForkJoinWorkerThreadFactory
350          implements ForkJoinWorkerThreadFactory {
351          public ForkJoinWorkerThread newThread(ForkJoinPool pool) {
352 <            try {
97 <                return new ForkJoinWorkerThread(pool);
98 <            } catch (OutOfMemoryError oom)  {
99 <                return null;
100 <            }
352 >            return new ForkJoinWorkerThread(pool);
353          }
354      }
355  
# Line 133 | 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
138 <     * replacements are protected by workerLock, but it is always kept
139 <     * in a consistent enough state to be randomly accessed without
140 <     * 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
156 <     * abrupty 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
167 <     * parallelism when other threads blocked, but have since
168 <     * 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       */
196    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)
215 <     * and running (i.e., not blocked on joins or other managed sync)
216 <     * threads, packed into one int to ensure consistent snapshot when
217 <     * making decisions about creating and suspending spare
218 <     * threads. Updated only by CAS.  Note: CASes in
219 <     * updateRunningCount and preJoin running active count is in low
220 <     * 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 <     * Add 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 <     * @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 <     * Add delta (which may be negative) to both total and running
241 <     * count.  This must be called upon creation and termination of
242 <     * worker threads.
243 <     * @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
254 <     * tasks. This value is atomically incremented before a worker
255 <     * gets a task to run, and decremented when worker has no tasks
256 <     * and cannot find any. These two fields are bundled together to
257 <     * support correct termination triggering.  Note: activeCount
258 <     * CAS'es cheat by assuming active count is in low word, so need
259 <     * 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;
266 <    private static final int TERMINATING = 2;
267 <    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 <     * Try incrementing active count; fail on contention. Called by
569 <     * workers before/during executing tasks.
570 <     * @return true on success;
568 >     * Tries incrementing active count; fails on contention.
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 <     * Try decrementing active count; fail on contention.
581 <     * Possibly trigger termination on success
286 <     * Called by workers when they can't find tasks.
287 <     * @return true on success
580 >     * Tries decrementing active count; fails on contention.
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))
587 <            return false;
588 <        if (canTerminateOnShutdown(nextc))
589 <            terminateOnShutdown();
590 <        return true;
584 >        int c;
585 >        return UNSAFE.compareAndSwapInt(this, runStateOffset,
586 >                                        c = runState, c - ONE_ACTIVE);
587 >    }
588 >
589 >    /**
590 >     * Advances to at least the given level. Returns true if not
591 >     * already in at least the given level.
592 >     */
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 >     * Records and returns a workers array index for new worker.
607 >     */
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 <     * Return true if argument represents zero active count and
301 <     * nonzero runstate, which is the triggering condition for
302 <     * terminating on shutdown.
631 >     * Nulls out record of worker in workers array
632       */
633 <    private static boolean canTerminateOnShutdown(int c) {
634 <        return ((c & -c) >>> 16) != 0; // i.e. least bit is nonzero runState bit
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 <     * Transition run state to at least the given state. Return true
310 <     * if not already at least given state.
671 >     * Adjusts counts upon failure to create worker
672       */
673 <    private boolean transitionRunStateTo(int state) {
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 and 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
1214       *         because it does not hold {@link
1215 <     *         java.lang.RuntimePermission}{@code ("modifyThread")},
1215 >     *         java.lang.RuntimePermission}{@code ("modifyThread")}
1216       */
1217      public ForkJoinPool() {
1218          this(Runtime.getRuntime().availableProcessors(),
# Line 341 | Line 1220 | public class ForkJoinPool extends Abstra
1220      }
1221  
1222      /**
1223 <     * Creates a ForkJoinPool with the indicated parellelism level
1224 <     * threads, and using the default ForkJoinWorkerThreadFactory,
1225 <     * @param parallelism the number of worker threads
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 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
1233 <     *         java.lang.RuntimePermission}{@code ("modifyThread")},
1233 >     *         java.lang.RuntimePermission}{@code ("modifyThread")}
1234       */
1235      public ForkJoinPool(int parallelism) {
1236          this(parallelism, defaultForkJoinWorkerThreadFactory);
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
1249 <     *         java.lang.RuntimePermission}{@code ("modifyThread")},
1249 >     *         java.lang.RuntimePermission}{@code ("modifyThread")}
1250       */
1251      public ForkJoinPool(ForkJoinWorkerThreadFactory factory) {
1252          this(Runtime.getRuntime().availableProcessors(), factory);
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")},
1267 >     *         java.lang.RuntimePermission}{@code ("modifyThread")}
1268       */
1269      public ForkJoinPool(int parallelism, ForkJoinWorkerThreadFactory factory) {
1270 <        if (parallelism <= 0 || parallelism > MAX_THREADS)
388 <            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();
397 <        this.workerLock = new ReentrantLock();
398 <        this.termination = workerLock.newCondition();
399 <        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 <    }
403 <
404 <    /**
405 <     * Create new worker using factory.
406 <     * @param index the index to assign worker
407 <     * @return new worker, or null of factory failed
408 <     */
409 <    private ForkJoinWorkerThread createWorker(int index) {
410 <        Thread.UncaughtExceptionHandler h = ueh;
411 <        ForkJoinWorkerThread w = factory.newThread(this);
412 <        if (w != null) {
413 <            w.poolIndex = index;
414 <            w.setDaemon(true);
415 <            w.setAsyncMode(locallyFifo);
416 <            w.setName("ForkJoinPool-" + poolNumber + "-worker-" + index);
417 <            if (h != null)
418 <                w.setUncaughtExceptionHandler(h);
419 <        }
420 <        return w;
421 <    }
422 <
423 <    /**
424 <     * Return a good size for worker array given pool size.
425 <     * Currently requires size to be a power of two.
426 <     */
427 <    private static int arraySizeFor(int ps) {
428 <        return ps <= 1? 1 : (1 << (32 - Integer.numberOfLeadingZeros(ps-1)));
429 <    }
430 <
431 <    /**
432 <     * Create or resize array if necessary to hold newLength.
433 <     * Call only under exlusion or lock
434 <     * @return the array
435 <     */
436 <    private ForkJoinWorkerThread[] ensureWorkerArrayCapacity(int newLength) {
437 <        ForkJoinWorkerThread[] ws = workers;
438 <        if (ws == null)
439 <            return workers = new ForkJoinWorkerThread[arraySizeFor(newLength)];
440 <        else if (newLength > ws.length)
441 <            return workers = Arrays.copyOf(ws, arraySizeFor(newLength));
442 <        else
443 <            return ws;
444 <    }
445 <
446 <    /**
447 <     * Try to shrink workers into smaller array after one or more terminate
448 <     */
449 <    private void tryShrinkWorkerArray() {
450 <        ForkJoinWorkerThread[] ws = workers;
451 <        if (ws != null) {
452 <            int len = ws.length;
453 <            int last = len - 1;
454 <            while (last >= 0 && ws[last] == null)
455 <                --last;
456 <            int newLength = arraySizeFor(last+1);
457 <            if (newLength < len)
458 <                workers = Arrays.copyOf(ws, newLength);
459 <        }
460 <    }
461 <
462 <    /**
463 <     * Initialize workers if necessary
464 <     */
465 <    final void ensureWorkerInitialization() {
466 <        ForkJoinWorkerThread[] ws = workers;
467 <        if (ws == null) {
468 <            final ReentrantLock lock = this.workerLock;
469 <            lock.lock();
470 <            try {
471 <                ws = workers;
472 <                if (ws == null) {
473 <                    int ps = parallelism;
474 <                    ws = ensureWorkerArrayCapacity(ps);
475 <                    for (int i = 0; i < ps; ++i) {
476 <                        ForkJoinWorkerThread w = createWorker(i);
477 <                        if (w != null) {
478 <                            ws[i] = w;
479 <                            w.start();
480 <                            updateWorkerCount(1);
481 <                        }
482 <                    }
483 <                }
484 <            } finally {
485 <                lock.unlock();
486 <            }
487 <        }
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) {
501 <            if (ws[k] != null) {
502 <                ++k;
503 <                continue;
504 <            }
505 <            int s = workerCounts;
506 <            int tc = totalCountOf(s);
507 <            int rc = runningCountOf(s);
508 <            if (rc >= ps || tc >= ps)
509 <                break;
510 <            if (casWorkerCounts (s, workerCountsFor(tc+1, rc+1))) {
511 <                ForkJoinWorkerThread w = createWorker(k);
512 <                if (w != null) {
513 <                    ws[k++] = w;
514 <                    w.start();
515 <                }
516 <                else {
517 <                    updateWorkerCount(-1); // back out on failed creation
518 <                    break;
519 <                }
520 <            }
521 <        }
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 527 | Line 1304 | public class ForkJoinPool extends Abstra
1304       * Common code for execute, invoke and submit
1305       */
1306      private <T> void doSubmit(ForkJoinTask<T> task) {
1307 <        if (isShutdown())
1307 >        if (task == null)
1308 >            throw new NullPointerException();
1309 >        if (runState >= SHUTDOWN)
1310              throw new RejectedExecutionException();
532        if (workers == null)
533            ensureWorkerInitialization();
1311          submissionQueue.offer(task);
1312 <        signalIdleWorkers();
1312 >        advanceEventCount();
1313 >        releaseWaiters();
1314 >        ensureEnoughTotalWorkers();
1315      }
1316  
1317      /**
1318 <     * Performs the given task; returning its result upon completion
1318 >     * Performs the given task, returning its result upon completion.
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 549 | Line 1330 | public class ForkJoinPool extends Abstra
1330  
1331      /**
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 <        doSubmit(new AdaptedRunnable<Void>(task, null));
1351 >        ForkJoinTask<?> job;
1352 >        if (task instanceof ForkJoinTask<?>) // avoid re-wrap
1353 >            job = (ForkJoinTask<?>) task;
1354 >        else
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<Void> job = new AdaptedRunnable<Void>(task, null);
1387 >        ForkJoinTask<?> job;
1388 >        if (task instanceof ForkJoinTask<?>) // avoid re-wrap
1389 >            job = (ForkJoinTask<?>) task;
1390 >        else
1391 >            job = ForkJoinTask.adapt(task, null);
1392          doSubmit(job);
1393          return job;
1394      }
1395  
1396      /**
1397 <     * Adaptor for Runnables. This implements RunnableFuture
1398 <     * to be compliant with AbstractExecutorService constraints
1397 >     * Submits a ForkJoinTask for execution.
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
1404       */
1405 <    static final class AdaptedRunnable<T> extends ForkJoinTask<T>
1406 <        implements RunnableFuture<T> {
1407 <        final Runnable runnable;
591 <        final T resultOnCompletion;
592 <        T result;
593 <        AdaptedRunnable(Runnable runnable, T result) {
594 <            if (runnable == null) throw new NullPointerException();
595 <            this.runnable = runnable;
596 <            this.resultOnCompletion = result;
597 <        }
598 <        public T getRawResult() { return result; }
599 <        public void setRawResult(T v) { result = v; }
600 <        public boolean exec() {
601 <            runnable.run();
602 <            result = resultOnCompletion;
603 <            return true;
604 <        }
605 <        public void run() { invoke(); }
1405 >    public <T> ForkJoinTask<T> submit(ForkJoinTask<T> task) {
1406 >        doSubmit(task);
1407 >        return task;
1408      }
1409  
1410      /**
1411 <     * Adaptor for Callables
1412 <     */
1413 <    static final class AdaptedCallable<T> extends ForkJoinTask<T>
612 <        implements RunnableFuture<T> {
613 <        final Callable<T> callable;
614 <        T result;
615 <        AdaptedCallable(Callable<T> callable) {
616 <            if (callable == null) throw new NullPointerException();
617 <            this.callable = callable;
618 <        }
619 <        public T getRawResult() { return result; }
620 <        public void setRawResult(T v) { result = v; }
621 <        public boolean exec() {
622 <            try {
623 <                result = callable.call();
624 <                return true;
625 <            } catch (Error err) {
626 <                throw err;
627 <            } catch (RuntimeException rex) {
628 <                throw rex;
629 <            } catch (Exception ex) {
630 <                throw new RuntimeException(ex);
631 <            }
632 <        }
633 <        public void run() { invoke(); }
634 <    }
635 <
1411 >     * @throws NullPointerException       {@inheritDoc}
1412 >     * @throws RejectedExecutionException {@inheritDoc}
1413 >     */
1414      public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) {
1415 <        ArrayList<ForkJoinTask<T>> ts =
1415 >        ArrayList<ForkJoinTask<T>> forkJoinTasks =
1416              new ArrayList<ForkJoinTask<T>>(tasks.size());
1417 <        for (Callable<T> c : tasks)
1418 <            ts.add(new AdaptedCallable<T>(c));
1419 <        invoke(new InvokeAll<T>(ts));
1420 <        return (List<Future<T>>)(List)ts;
1417 >        for (Callable<T> task : tasks)
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;
1423 >        return futures;
1424      }
1425  
1426      static final class InvokeAll<T> extends RecursiveAction {
1427          final ArrayList<ForkJoinTask<T>> tasks;
1428          InvokeAll(ArrayList<ForkJoinTask<T>> tasks) { this.tasks = tasks; }
1429          public void compute() {
1430 <            try { invokeAll(tasks); } catch(Exception ignore) {}
1430 >            try { invokeAll(tasks); }
1431 >            catch (Exception ignore) {}
1432          }
1433 +        private static final long serialVersionUID = -7914297376763021607L;
1434      }
1435  
653    // Configuration and status settings and queries
654
1436      /**
1437 <     * Returns the factory used for constructing new workers
1437 >     * Returns the factory used for constructing new workers.
1438       *
1439       * @return the factory used for constructing new workers
1440       */
# Line 664 | Line 1445 | public class ForkJoinPool extends Abstra
1445      /**
1446       * Returns the handler for internal worker threads that terminate
1447       * due to unrecoverable errors encountered while executing tasks.
1448 <     * @return the handler, or null if none
1448 >     *
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;
672 <        lock.lock();
673 <        try {
674 <            h = ueh;
675 <        } finally {
676 <            lock.unlock();
677 <        }
678 <        return h;
1452 >        workerCountReadFence();
1453 >        return ueh;
1454      }
1455  
1456      /**
# Line 685 | 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
1467 <     *         java.lang.RuntimePermission}{@code ("modifyThread")},
1467 >     *         java.lang.RuntimePermission}{@code ("modifyThread")}
1468       */
1469      public Thread.UncaughtExceptionHandler
1470          setUncaughtExceptionHandler(Thread.UncaughtExceptionHandler h) {
1471          checkPermission();
1472 <        Thread.UncaughtExceptionHandler old = null;
1473 <        final ReentrantLock lock = this.workerLock;
699 <        lock.lock();
700 <        try {
701 <            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);
709 <                }
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              }
711        } finally {
712            lock.unlock();
1482          }
1483          return old;
1484      }
1485  
717
1486      /**
1487 <     * Sets the target paralleism level of this pool.
1487 >     * Sets the target parallelism level of this pool.
1488 >     *
1489       * @param parallelism the target parallelism
1490       * @throws IllegalArgumentException if parallelism less than or
1491 <     * equal to zero or greater than maximum size bounds.
1491 >     * equal to zero or greater than maximum size bounds
1492       * @throws SecurityException if a security manager exists and
1493       *         the caller is not permitted to modify threads
1494       *         because it does not hold {@link
1495 <     *         java.lang.RuntimePermission}{@code ("modifyThread")},
1495 >     *         java.lang.RuntimePermission}{@code ("modifyThread")}
1496       */
1497      public void setParallelism(int parallelism) {
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          }
746        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.
1566 <     * @throws IllegalArgumentException if negative or greater then
1567 <     * internal implementation limit.
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 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  
793
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.
1586 <     * This setting is by default true;
1587 <     * @return true if maintains parallelism
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 {@code true} if maintains parallelism
1588       */
1589      public boolean getMaintainsParallelism() {
1590 +        workerCountReadFence();
1591          return maintainsParallelism;
1592      }
1593  
# Line 806 | Line 1595 | public class ForkJoinPool extends Abstra
1595       * Sets whether this pool dynamically maintains its target
1596       * parallelism level. If false, new threads are added only to
1597       * avoid possible starvation.
1598 <     * @param enable true to maintains parallelism
1598 >     *
1599 >     * @param enable {@code true} to maintain parallelism
1600       */
1601      public void setMaintainsParallelism(boolean enable) {
1602          maintainsParallelism = enable;
1603 +        workerCountWriteFence();
1604      }
1605  
1606      /**
# Line 817 | 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 ather times may be unpredictable.
1613 >     * invocations at other times may be unpredictable.
1614       *
1615 <     * @param async if true, use locally FIFO scheduling
1616 <     * @return the previous mode.
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      /**
1661       * Returns an estimate of the number of threads that are currently
1662       * stealing or executing tasks. This method may overestimate the
1663       * number of active threads.
1664 <     * @return the number of active threads.
1664 >     *
1665 >     * @return the number of active threads
1666       */
1667      public int getActiveThreadCount() {
1668 <        return activeCountOf(runControl);
870 <    }
871 <
872 <    /**
873 <     * Returns an estimate of the number of threads that are currently
874 <     * idle waiting for tasks. This method may underestimate the
875 <     * number of idle threads.
876 <     * @return the number of idle threads.
877 <     */
878 <    final int getIdleThreadCount() {
879 <        int c = runningCountOf(workerCounts) - activeCountOf(runControl);
880 <        return (c <= 0)? 0 : c;
1668 >        return runState & ACTIVE_COUNT_MASK;
1669      }
1670  
1671      /**
1672 <     * Returns true if all worker threads are currently idle. An idle
1673 <     * worker is one that cannot obtain a task to execute because none
1674 <     * are available to steal from other threads, and there are no
1675 <     * pending submissions to the pool. This method is conservative:
1676 <     * It might not return true immediately upon idleness of all
1677 <     * threads, but will eventually become true if threads remain
1678 <     * inactive.
1679 <     * @return true if all threads are currently idle
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 {@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 899 | Line 1688 | public class ForkJoinPool extends Abstra
1688       * one thread's work queue by another. The reported value
1689       * underestimates the actual total number of steals when the pool
1690       * is not quiescent. This value may be useful for monitoring and
1691 <     * tuning fork/join programs: In general, steal counts should be
1691 >     * tuning fork/join programs: in general, steal counts should be
1692       * high enough to keep threads busy, but low enough to avoid
1693       * overhead and contention across threads.
1694 <     * @return the number of steals.
1694 >     *
1695 >     * @return the number of steals
1696       */
1697      public long getStealCount() {
1698 <        return stealCount.get();
909 <    }
910 <
911 <    /**
912 <     * Accumulate steal count from a worker. Call only
913 <     * when worker known to be idle.
914 <     */
915 <    private void updateStealCount(ForkJoinWorkerThread w) {
916 <        int sc = w.getAndClearStealCount();
917 <        if (sc != 0)
918 <            stealCount.addAndGet(sc);
1698 >        return stealCount;
1699      }
1700  
1701      /**
# Line 925 | Line 1705 | public class ForkJoinPool extends Abstra
1705       * an approximation, obtained by iterating across all threads in
1706       * the pool. This method may be useful for tuning task
1707       * granularities.
1708 <     * @return the number of queued tasks.
1708 >     *
1709 >     * @return the number of queued tasks
1710       */
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();
938 <            }
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 <     * @return the number of queued submissions.
1727 >     *
1728 >     * @return the number of queued submissions
1729       */
1730      public int getQueuedSubmissionCount() {
1731          return submissionQueue.size();
1732      }
1733  
1734      /**
1735 <     * Returns true if there are any tasks submitted to this pool
1736 <     * that have not yet begun executing.
1737 <     * @return {@code true} if there are any queued submissions.
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       */
1740      public boolean hasQueuedSubmissions() {
1741          return !submissionQueue.isEmpty();
# Line 963 | Line 1745 | public class ForkJoinPool extends Abstra
1745       * Removes and returns the next unexecuted submission if one is
1746       * available.  This method may be useful in extensions to this
1747       * class that re-assign work in systems with multiple pools.
1748 <     * @return the next submission, or null if none
1748 >     *
1749 >     * @return the next submission, or {@code null} if none
1750       */
1751      protected ForkJoinTask<?> pollSubmission() {
1752          return submissionQueue.poll();
# Line 973 | 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 <     * artifically generated or wrapped tasks. This method id 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 982 | Line 1765 | public class ForkJoinPool extends Abstra
1765       * exception is thrown.  The behavior of this operation is
1766       * undefined if the specified collection is modified while the
1767       * operation is in progress.
1768 +     *
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);
996 <            }
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 1006 | Line 1789 | public class ForkJoinPool extends Abstra
1789       * @return a string identifying this pool, as well as its state
1790       */
1791      public String toString() {
1009        int ps = parallelism;
1010        int wc = workerCounts;
1011        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";
1032 <        case TERMINATED: return "Terminated";
1033 <        default: throw new Error("Unknown run state");
1034 <        }
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  
1037    // lifecycle control
1038
1820      /**
1821       * Initiates an orderly shutdown in which previously submitted
1822       * tasks are executed, but no new tasks will be accepted.
1823       * Invocation has no additional effect if already shut down.
1824       * Tasks that are in the process of being submitted concurrently
1825       * during the course of this method may or may not be rejected.
1826 +     *
1827       * @throws SecurityException if a security manager exists and
1828       *         the caller is not permitted to modify threads
1829       *         because it does not hold {@link
1830 <     *         java.lang.RuntimePermission}{@code ("modifyThread")},
1830 >     *         java.lang.RuntimePermission}{@code ("modifyThread")}
1831       */
1832      public void shutdown() {
1833          checkPermission();
1834 <        transitionRunStateTo(SHUTDOWN);
1835 <        if (canTerminateOnShutdown(runControl))
1054 <            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
1850       *         the caller is not permitted to modify threads
1851       *         because it does not hold {@link
1852 <     *         java.lang.RuntimePermission}{@code ("modifyThread")},
1852 >     *         java.lang.RuntimePermission}{@code ("modifyThread")}
1853       */
1854      public List<Runnable> shutdownNow() {
1855          checkPermission();
1856 <        terminate();
1856 >        tryTerminate(true);
1857          return Collections.emptyList();
1858      }
1859  
# Line 1081 | 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 1100 | 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 1116 | 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);
1120 <        final ReentrantLock lock = this.workerLock;
1121 <        lock.lock();
1122 <        try {
1123 <            for (;;) {
1124 <                if (isTerminated())
1125 <                    return true;
1126 <                if (nanos <= 0)
1127 <                    return false;
1128 <                nanos = termination.awaitNanos(nanos);
1129 <            }
1130 <        } finally {
1131 <            lock.unlock();
1132 <        }
1133 <    }
1134 <
1135 <    // Shutdown and termination support
1136 <
1137 <    /**
1138 <     * Callback from terminating worker. Null out the corresponding
1139 <     * workers slot, and if terminating, try to terminate, else try to
1140 <     * shrink workers array.
1141 <     * @param w the worker
1142 <     */
1143 <    final void workerTerminated(ForkJoinWorkerThread w) {
1144 <        updateStealCount(w);
1145 <        updateWorkerCount(-1);
1146 <        final ReentrantLock lock = this.workerLock;
1147 <        lock.lock();
1148 <        try {
1149 <            ForkJoinWorkerThread[] ws = workers;
1150 <            if (ws != null) {
1151 <                int idx = w.poolIndex;
1152 <                if (idx >= 0 && idx < ws.length && ws[idx] == w)
1153 <                    ws[idx] = null;
1154 <                if (totalCountOf(workerCounts) == 0) {
1155 <                    terminate(); // no-op if already terminating
1156 <                    transitionRunStateTo(TERMINATED);
1157 <                    termination.signalAll();
1158 <                }
1159 <                else if (!isTerminating()) {
1160 <                    tryShrinkWorkerArray();
1161 <                    tryResumeSpare(true); // allow replacement
1162 <                }
1163 <            }
1164 <        } finally {
1165 <            lock.unlock();
1166 <        }
1167 <        signalIdleWorkers();
1905 >        return terminationLatch.await(timeout, unit);
1906      }
1907  
1908      /**
1909 <     * Initiate termination.
1910 <     */
1173 <    private void terminate() {
1174 <        if (transitionRunStateTo(TERMINATING)) {
1175 <            stopAllWorkers();
1176 <            resumeAllSpares();
1177 <            signalIdleWorkers();
1178 <            cancelQueuedSubmissions();
1179 <            cancelQueuedWorkerTasks();
1180 <            interruptUnterminatedWorkers();
1181 <            signalIdleWorkers(); // resignal after interrupt
1182 <        }
1183 <    }
1184 <
1185 <    /**
1186 <     * Possibly terminate when on shutdown state
1187 <     */
1188 <    private void terminateOnShutdown() {
1189 <        if (!hasQueuedSubmissions() && canTerminateOnShutdown(runControl))
1190 <            terminate();
1191 <    }
1192 <
1193 <    /**
1194 <     * Clear out and cancel submissions
1195 <     */
1196 <    private void cancelQueuedSubmissions() {
1197 <        ForkJoinTask<?> task;
1198 <        while ((task = pollSubmission()) != null)
1199 <            task.cancel(false);
1200 <    }
1201 <
1202 <    /**
1203 <     * Clean out worker queues.
1204 <     */
1205 <    private void cancelQueuedWorkerTasks() {
1206 <        final ReentrantLock lock = this.workerLock;
1207 <        lock.lock();
1208 <        try {
1209 <            ForkJoinWorkerThread[] ws = workers;
1210 <            if (ws != null) {
1211 <                for (int i = 0; i < ws.length; ++i) {
1212 <                    ForkJoinWorkerThread t = ws[i];
1213 <                    if (t != null)
1214 <                        t.cancelTasks();
1215 <                }
1216 <            }
1217 <        } finally {
1218 <            lock.unlock();
1219 <        }
1220 <    }
1221 <
1222 <    /**
1223 <     * Set each worker's status to terminating. Requires lock to avoid
1224 <     * conflicts with add/remove
1225 <     */
1226 <    private void stopAllWorkers() {
1227 <        final ReentrantLock lock = this.workerLock;
1228 <        lock.lock();
1229 <        try {
1230 <            ForkJoinWorkerThread[] ws = workers;
1231 <            if (ws != null) {
1232 <                for (int i = 0; i < ws.length; ++i) {
1233 <                    ForkJoinWorkerThread t = ws[i];
1234 <                    if (t != null)
1235 <                        t.shutdownNow();
1236 <                }
1237 <            }
1238 <        } finally {
1239 <            lock.unlock();
1240 <        }
1241 <    }
1242 <
1243 <    /**
1244 <     * Interrupt all unterminated workers.  This is not required for
1245 <     * sake of internal control, but may help unstick user code during
1246 <     * shutdown.
1247 <     */
1248 <    private void interruptUnterminatedWorkers() {
1249 <        final ReentrantLock lock = this.workerLock;
1250 <        lock.lock();
1251 <        try {
1252 <            ForkJoinWorkerThread[] ws = workers;
1253 <            if (ws != null) {
1254 <                for (int i = 0; i < ws.length; ++i) {
1255 <                    ForkJoinWorkerThread t = ws[i];
1256 <                    if (t != null && !t.isTerminated()) {
1257 <                        try {
1258 <                            t.interrupt();
1259 <                        } catch (SecurityException ignore) {
1260 <                        }
1261 <                    }
1262 <                }
1263 <            }
1264 <        } finally {
1265 <            lock.unlock();
1266 <        }
1267 <    }
1268 <
1269 <
1270 <    /*
1271 <     * Nodes for event barrier to manage idle threads.  Queue nodes
1272 <     * are basic Treiber stack nodes, also used for spare stack.
1273 <     *
1274 <     * The event barrier has an event count and a wait queue (actually
1275 <     * a Treiber stack).  Workers are enabled to look for work when
1276 <     * the eventCount is incremented. If they fail to find work, they
1277 <     * may wait for next count. Upon release, threads help others wake
1278 <     * up.
1279 <     *
1280 <     * Synchronization events occur only in enough contexts to
1281 <     * maintain overall liveness:
1909 >     * Interface for extending managed parallelism for tasks running
1910 >     * in {@link ForkJoinPool}s.
1911       *
1912 <     *   - Submission of a new task to the pool
1913 <     *   - Resizes or other changes to the workers array
1914 <     *   - pool termination
1915 <     *   - A worker pushing a task on an empty queue
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       *
1288     * The case of pushing a task occurs often enough, and is heavy
1289     * enough compared to simple stack pushes, to require special
1290     * handling: Method signalWork returns without advancing count if
1291     * the queue appears to be empty.  This would ordinarily result in
1292     * races causing some queued waiters not to be woken up. To avoid
1293     * this, the first worker enqueued in method sync (see
1294     * syncIsReleasable) rescans for tasks after being enqueued, and
1295     * helps signal if any are found. This works well because the
1296     * worker has nothing better to do, and so might as well help
1297     * alleviate the overhead and contention on the threads actually
1298     * doing work.  Also, since event counts increments on task
1299     * availability exist to maintain liveness (rather than to force
1300     * refreshes etc), it is OK for callers to exit early if
1301     * contending with another signaller.
1302     */
1303    static final class WaitQueueNode {
1304        WaitQueueNode next; // only written before enqueued
1305        volatile ForkJoinWorkerThread thread; // nulled to cancel wait
1306        final long count; // unused for spare stack
1307
1308        WaitQueueNode(long c, ForkJoinWorkerThread w) {
1309            count = c;
1310            thread = w;
1311        }
1312
1313        /**
1314         * Wake up waiter, returning false if known to already
1315         */
1316        boolean signal() {
1317            ForkJoinWorkerThread t = thread;
1318            if (t == null)
1319                return false;
1320            thread = null;
1321            LockSupport.unpark(t);
1322            return true;
1323        }
1324
1325        /**
1326         * Await release on sync
1327         */
1328        void awaitSyncRelease(ForkJoinPool p) {
1329            while (thread != null && !p.syncIsReleasable(this))
1330                LockSupport.park(this);
1331        }
1332
1333        /**
1334         * Await resumption as spare
1335         */
1336        void awaitSpareRelease() {
1337            while (thread != null) {
1338                if (!Thread.interrupted())
1339                    LockSupport.park(this);
1340            }
1341        }
1342    }
1343
1344    /**
1345     * Ensures that no thread is waiting for count to advance from the
1346     * current value of eventCount read on entry to this method, by
1347     * releasing waiting threads if necessary.
1348     * @return the count
1349     */
1350    final long ensureSync() {
1351        long c = eventCount;
1352        WaitQueueNode q;
1353        while ((q = syncStack) != null && q.count < c) {
1354            if (casBarrierStack(q, null)) {
1355                do {
1356                    q.signal();
1357                } while ((q = q.next) != null);
1358                break;
1359            }
1360        }
1361        return c;
1362    }
1363
1364    /**
1365     * Increments event count and releases waiting threads.
1366     */
1367    private void signalIdleWorkers() {
1368        long c;
1369        do;while (!casEventCount(c = eventCount, c+1));
1370        ensureSync();
1371    }
1372
1373    /**
1374     * Signal threads waiting to poll a task. Because method sync
1375     * rechecks availability, it is OK to only proceed if queue
1376     * appears to be non-empty, and OK to skip under contention to
1377     * increment count (since some other thread succeeded).
1378     */
1379    final void signalWork() {
1380        long c;
1381        WaitQueueNode q;
1382        if (syncStack != null &&
1383            casEventCount(c = eventCount, c+1) &&
1384            (((q = syncStack) != null && q.count <= c) &&
1385             (!casBarrierStack(q, q.next) || !q.signal())))
1386            ensureSync();
1387    }
1388
1389    /**
1390     * Waits until event count advances from last value held by
1391     * caller, or if excess threads, caller is resumed as spare, or
1392     * caller or pool is terminating. Updates caller's event on exit.
1393     * @param w the calling worker thread
1394     */
1395    final void sync(ForkJoinWorkerThread w) {
1396        updateStealCount(w); // Transfer w's count while it is idle
1397
1398        while (!w.isShutdown() && !isTerminating() && !suspendIfSpare(w)) {
1399            long prev = w.lastEventCount;
1400            WaitQueueNode node = null;
1401            WaitQueueNode h;
1402            while (eventCount == prev &&
1403                   ((h = syncStack) == null || h.count == prev)) {
1404                if (node == null)
1405                    node = new WaitQueueNode(prev, w);
1406                if (casBarrierStack(node.next = h, node)) {
1407                    node.awaitSyncRelease(this);
1408                    break;
1409                }
1410            }
1411            long ec = ensureSync();
1412            if (ec != prev) {
1413                w.lastEventCount = ec;
1414                break;
1415            }
1416        }
1417    }
1418
1419    /**
1420     * Returns true if worker waiting on sync can proceed:
1421     *  - on signal (thread == null)
1422     *  - on event count advance (winning race to notify vs signaller)
1423     *  - on Interrupt
1424     *  - if the first queued node, we find work available
1425     * If node was not signalled and event count not advanced on exit,
1426     * then we also help advance event count.
1427     * @return true if node can be released
1428     */
1429    final boolean syncIsReleasable(WaitQueueNode node) {
1430        long prev = node.count;
1431        if (!Thread.interrupted() && node.thread != null &&
1432            (node.next != null ||
1433             !ForkJoinWorkerThread.hasQueuedTasks(workers)) &&
1434            eventCount == prev)
1435            return false;
1436        if (node.thread != null) {
1437            node.thread = null;
1438            long ec = eventCount;
1439            if (prev <= ec) // help signal
1440                casEventCount(ec, ec+1);
1441        }
1442        return true;
1443    }
1444
1445    /**
1446     * Returns true if a new sync event occurred since last call to
1447     * sync or this method, if so, updating caller's count.
1448     */
1449    final boolean hasNewSyncEvent(ForkJoinWorkerThread w) {
1450        long lc = w.lastEventCount;
1451        long ec = ensureSync();
1452        if (ec == lc)
1453            return false;
1454        w.lastEventCount = ec;
1455        return true;
1456    }
1457
1458    //  Parallelism maintenance
1459
1460    /**
1461     * Decrement running count; if too low, add spare.
1462     *
1463     * Conceptually, all we need to do here is add or resume a
1464     * spare thread when one is about to block (and remove or
1465     * suspend it later when unblocked -- see suspendIfSpare).
1466     * However, implementing this idea requires coping with
1467     * several problems: We have imperfect information about the
1468     * states of threads. Some count updates can and usually do
1469     * lag run state changes, despite arrangements to keep them
1470     * accurate (for example, when possible, updating counts
1471     * before signalling or resuming), especially when running on
1472     * dynamic JVMs that don't optimize the infrequent paths that
1473     * update counts. Generating too many threads can make these
1474     * problems become worse, because excess threads are more
1475     * likely to be context-switched with others, slowing them all
1476     * down, especially if there is no work available, so all are
1477     * busy scanning or idling.  Also, excess spare threads can
1478     * only be suspended or removed when they are idle, not
1479     * immediately when they aren't needed. So adding threads will
1480     * raise parallelism level for longer than necessary.  Also,
1481     * FJ applications often enounter highly transient peaks when
1482     * many threads are blocked joining, but for less time than it
1483     * takes to create or resume spares.
1484     *
1485     * @param joinMe if non-null, return early if done
1486     * @param maintainParallelism if true, try to stay within
1487     * target counts, else create only to avoid starvation
1488     * @return true if joinMe known to be done
1489     */
1490    final boolean preJoin(ForkJoinTask<?> joinMe, boolean maintainParallelism) {
1491        maintainParallelism &= maintainsParallelism; // overrride
1492        boolean dec = false;  // true when running count decremented
1493        while (spareStack == null || !tryResumeSpare(dec)) {
1494            int counts = workerCounts;
1495            if (dec || (dec = casWorkerCounts(counts, --counts))) { // CAS cheat
1496                if (!needSpare(counts, maintainParallelism))
1497                    break;
1498                if (joinMe.status < 0)
1499                    return true;
1500                if (tryAddSpare(counts))
1501                    break;
1502            }
1503        }
1504        return false;
1505    }
1506
1507    /**
1508     * Same idea as preJoin
1509     */
1510    final boolean preBlock(ManagedBlocker blocker, boolean maintainParallelism){
1511        maintainParallelism &= maintainsParallelism;
1512        boolean dec = false;
1513        while (spareStack == null || !tryResumeSpare(dec)) {
1514            int counts = workerCounts;
1515            if (dec || (dec = casWorkerCounts(counts, --counts))) {
1516                if (!needSpare(counts, maintainParallelism))
1517                    break;
1518                if (blocker.isReleasable())
1519                    return true;
1520                if (tryAddSpare(counts))
1521                    break;
1522            }
1523        }
1524        return false;
1525    }
1526
1527    /**
1528     * Returns true if a spare thread appears to be needed.  If
1529     * maintaining parallelism, returns true when the deficit in
1530     * running threads is more than the surplus of total threads, and
1531     * there is apparently some work to do.  This self-limiting rule
1532     * means that the more threads that have already been added, the
1533     * less parallelism we will tolerate before adding another.
1534     * @param counts current worker counts
1535     * @param maintainParallelism try to maintain parallelism
1536     */
1537    private boolean needSpare(int counts, boolean maintainParallelism) {
1538        int ps = parallelism;
1539        int rc = runningCountOf(counts);
1540        int tc = totalCountOf(counts);
1541        int runningDeficit = ps - rc;
1542        int totalSurplus = tc - ps;
1543        return (tc < maxPoolSize &&
1544                (rc == 0 || totalSurplus < 0 ||
1545                 (maintainParallelism &&
1546                  runningDeficit > totalSurplus &&
1547                  ForkJoinWorkerThread.hasQueuedTasks(workers))));
1548    }
1549
1550    /**
1551     * Add a spare worker if lock available and no more than the
1552     * expected numbers of threads exist
1553     * @return true if successful
1554     */
1555    private boolean tryAddSpare(int expectedCounts) {
1556        final ReentrantLock lock = this.workerLock;
1557        int expectedRunning = runningCountOf(expectedCounts);
1558        int expectedTotal = totalCountOf(expectedCounts);
1559        boolean success = false;
1560        boolean locked = false;
1561        // confirm counts while locking; CAS after obtaining lock
1562        try {
1563            for (;;) {
1564                int s = workerCounts;
1565                int tc = totalCountOf(s);
1566                int rc = runningCountOf(s);
1567                if (rc > expectedRunning || tc > expectedTotal)
1568                    break;
1569                if (!locked && !(locked = lock.tryLock()))
1570                    break;
1571                if (casWorkerCounts(s, workerCountsFor(tc+1, rc+1))) {
1572                    createAndStartSpare(tc);
1573                    success = true;
1574                    break;
1575                }
1576            }
1577        } finally {
1578            if (locked)
1579                lock.unlock();
1580        }
1581        return success;
1582    }
1583
1584    /**
1585     * Add the kth spare worker. On entry, pool coounts are already
1586     * adjusted to reflect addition.
1587     */
1588    private void createAndStartSpare(int k) {
1589        ForkJoinWorkerThread w = null;
1590        ForkJoinWorkerThread[] ws = ensureWorkerArrayCapacity(k + 1);
1591        int len = ws.length;
1592        // Probably, we can place at slot k. If not, find empty slot
1593        if (k < len && ws[k] != null) {
1594            for (k = 0; k < len && ws[k] != null; ++k)
1595                ;
1596        }
1597        if (k < len && !isTerminating() && (w = createWorker(k)) != null) {
1598            ws[k] = w;
1599            w.start();
1600        }
1601        else
1602            updateWorkerCount(-1); // adjust on failure
1603        signalIdleWorkers();
1604    }
1605
1606    /**
1607     * Suspend calling thread w if there are excess threads.  Called
1608     * only from sync.  Spares are enqueued in a Treiber stack
1609     * using the same WaitQueueNodes as barriers.  They are resumed
1610     * mainly in preJoin, but are also woken on pool events that
1611     * require all threads to check run state.
1612     * @param w the caller
1613     */
1614    private boolean suspendIfSpare(ForkJoinWorkerThread w) {
1615        WaitQueueNode node = null;
1616        int s;
1617        while (parallelism < runningCountOf(s = workerCounts)) {
1618            if (node == null)
1619                node = new WaitQueueNode(0, w);
1620            if (casWorkerCounts(s, s-1)) { // representation-dependent
1621                // push onto stack
1622                do;while (!casSpareStack(node.next = spareStack, node));
1623                // block until released by resumeSpare
1624                node.awaitSpareRelease();
1625                return true;
1626            }
1627        }
1628        return false;
1629    }
1630
1631    /**
1632     * Try to pop and resume a spare thread.
1633     * @param updateCount if true, increment running count on success
1634     * @return true if successful
1635     */
1636    private boolean tryResumeSpare(boolean updateCount) {
1637        WaitQueueNode q;
1638        while ((q = spareStack) != null) {
1639            if (casSpareStack(q, q.next)) {
1640                if (updateCount)
1641                    updateRunningCount(1);
1642                q.signal();
1643                return true;
1644            }
1645        }
1646        return false;
1647    }
1648
1649    /**
1650     * Pop and resume all spare threads. Same idea as ensureSync.
1651     * @return true if any spares released
1652     */
1653    private boolean resumeAllSpares() {
1654        WaitQueueNode q;
1655        while ( (q = spareStack) != null) {
1656            if (casSpareStack(q, null)) {
1657                do {
1658                    updateRunningCount(1);
1659                    q.signal();
1660                } while ((q = q.next) != null);
1661                return true;
1662            }
1663        }
1664        return false;
1665    }
1666
1667    /**
1668     * Pop and shutdown excessive spare threads. Call only while
1669     * holding lock. This is not guaranteed to eliminate all excess
1670     * threads, only those suspended as spares, which are the ones
1671     * unlikely to be needed in the future.
1672     */
1673    private void trimSpares() {
1674        int surplus = totalCountOf(workerCounts) - parallelism;
1675        WaitQueueNode q;
1676        while (surplus > 0 && (q = spareStack) != null) {
1677            if (casSpareStack(q, null)) {
1678                do {
1679                    updateRunningCount(1);
1680                    ForkJoinWorkerThread w = q.thread;
1681                    if (w != null && surplus > 0 &&
1682                        runningCountOf(workerCounts) > 0 && w.shutdown())
1683                        --surplus;
1684                    q.signal();
1685                } while ((q = q.next) != null);
1686            }
1687        }
1688    }
1689
1690    /**
1691     * Interface for extending managed parallelism for tasks running
1692     * in ForkJoinPools. A ManagedBlocker provides two methods.
1693     * Method {@code isReleasable} must return true if blocking is not
1694     * necessary. Method {@code block} blocks the current thread
1695     * if necessary (perhaps internally invoking isReleasable before
1696     * actually blocking.).
1918       * <p>For example, here is a ManagedBlocker based on a
1919       * ReentrantLock:
1920 <     * <pre>
1921 <     *   class ManagedLocker implements ManagedBlocker {
1922 <     *     final ReentrantLock lock;
1923 <     *     boolean hasLock = false;
1924 <     *     ManagedLocker(ReentrantLock lock) { this.lock = lock; }
1925 <     *     public boolean block() {
1926 <     *        if (!hasLock)
1927 <     *           lock.lock();
1928 <     *        return true;
1929 <     *     }
1930 <     *     public boolean isReleasable() {
1931 <     *        return hasLock || (hasLock = lock.tryLock());
1711 <     *     }
1920 >     *  <pre> {@code
1921 >     * class ManagedLocker implements ManagedBlocker {
1922 >     *   final ReentrantLock lock;
1923 >     *   boolean hasLock = false;
1924 >     *   ManagedLocker(ReentrantLock lock) { this.lock = lock; }
1925 >     *   public boolean block() {
1926 >     *     if (!hasLock)
1927 >     *       lock.lock();
1928 >     *     return true;
1929 >     *   }
1930 >     *   public boolean isReleasable() {
1931 >     *     return hasLock || (hasLock = lock.tryLock());
1932       *   }
1933 <     * </pre>
1933 >     * }}</pre>
1934       */
1935      public static interface ManagedBlocker {
1936          /**
1937           * Possibly blocks the current thread, for example waiting for
1938           * a lock or condition.
1939 <         * @return true if no additional blocking is necessary (i.e.,
1940 <         * if isReleasable would return true).
1939 >         *
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 allowe to).
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 if 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.
1964 <     *
1965 <     * <p> If the caller is not a ForkJoinTask, this method is behaviorally
1966 <     * equivalent to
1967 <     * <pre>
1968 <     *   while (!blocker.isReleasable())
1969 <     *      if (blocker.block())
1970 <     *         return;
1971 <     * </pre>
1972 <     * If the caller is a ForkJoinTask, then the pool may first
1973 <     * be expanded to ensure parallelism, and later adjusted.
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 {@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 >     *
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.
1982 <     * @throws InterruptedException if blocker.block did so.
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 ||
1770 <                    !pool.preBlock(blocker, maintainParallelism))
1771 <                    awaitBlocker(blocker);
1772 <            } finally {
1773 <                if (pool != null)
1774 <                    pool.updateRunningCount(1);
1775 <            }
1776 <        }
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());
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(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(callable);
2012 >        return (RunnableFuture<T>) ForkJoinTask.adapt(callable);
2013      }
2014  
2015 +    // Unsafe mechanics
2016  
2017 <    // Temporary Unsafe mechanics for preliminary release
2018 <    private static Unsafe getUnsafe() throws Throwable {
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 >    /**
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 Unsafe.getUnsafe();
2050 >            return sun.misc.Unsafe.getUnsafe();
2051          } catch (SecurityException se) {
2052              try {
2053                  return java.security.AccessController.doPrivileged
2054 <                    (new java.security.PrivilegedExceptionAction<Unsafe>() {
2055 <                        public Unsafe run() throws Exception {
2056 <                            return getUnsafePrivileged();
2054 >                    (new java.security
2055 >                     .PrivilegedExceptionAction<sun.misc.Unsafe>() {
2056 >                        public sun.misc.Unsafe run() throws Exception {
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 e.getCause();
2063 >                throw new RuntimeException("Could not initialize intrinsics",
2064 >                                           e.getCause());
2065              }
2066          }
2067      }
1811
1812    private static Unsafe getUnsafePrivileged()
1813            throws NoSuchFieldException, IllegalAccessException {
1814        Field f = Unsafe.class.getDeclaredField("theUnsafe");
1815        f.setAccessible(true);
1816        return (Unsafe) f.get(null);
1817    }
1818
1819    private static long fieldOffset(String fieldName)
1820            throws NoSuchFieldException {
1821        return _unsafe.objectFieldOffset
1822            (ForkJoinPool.class.getDeclaredField(fieldName));
1823    }
1824
1825    static final Unsafe _unsafe;
1826    static final long eventCountOffset;
1827    static final long workerCountsOffset;
1828    static final long runControlOffset;
1829    static final long syncStackOffset;
1830    static final long spareStackOffset;
1831
1832    static {
1833        try {
1834            _unsafe = getUnsafe();
1835            eventCountOffset = fieldOffset("eventCount");
1836            workerCountsOffset = fieldOffset("workerCounts");
1837            runControlOffset = fieldOffset("runControl");
1838            syncStackOffset = fieldOffset("syncStack");
1839            spareStackOffset = fieldOffset("spareStack");
1840        } catch (Throwable e) {
1841            throw new RuntimeException("Could not initialize intrinsics", e);
1842        }
1843    }
1844
1845    private boolean casEventCount(long cmp, long val) {
1846        return _unsafe.compareAndSwapLong(this, eventCountOffset, cmp, val);
1847    }
1848    private boolean casWorkerCounts(int cmp, int val) {
1849        return _unsafe.compareAndSwapInt(this, workerCountsOffset, cmp, val);
1850    }
1851    private boolean casRunControl(int cmp, int val) {
1852        return _unsafe.compareAndSwapInt(this, runControlOffset, cmp, val);
1853    }
1854    private boolean casSpareStack(WaitQueueNode cmp, WaitQueueNode val) {
1855        return _unsafe.compareAndSwapObject(this, spareStackOffset, cmp, val);
1856    }
1857    private boolean casBarrierStack(WaitQueueNode cmp, WaitQueueNode val) {
1858        return _unsafe.compareAndSwapObject(this, syncStackOffset, cmp, val);
1859    }
2068   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines