ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinPool.java
Revision: 1.22
Committed: Tue Aug 17 18:31:59 2010 UTC (13 years, 9 months ago) by dl
Branch: MAIN
Changes since 1.21: +307 -202 lines
Log Message:
Reduce resources during periods without use

File Contents

# User Rev Content
1 jsr166 1.1 /*
2     * Written by Doug Lea with assistance from members of JCP JSR-166
3     * Expert Group and released to the public domain, as explained at
4     * http://creativecommons.org/licenses/publicdomain
5     */
6    
7     package java.util.concurrent;
8    
9     import java.util.ArrayList;
10     import java.util.Arrays;
11     import java.util.Collection;
12     import java.util.Collections;
13     import java.util.List;
14     import java.util.concurrent.locks.LockSupport;
15     import java.util.concurrent.locks.ReentrantLock;
16     import java.util.concurrent.atomic.AtomicInteger;
17 dl 1.14 import java.util.concurrent.CountDownLatch;
18 jsr166 1.1
19     /**
20 jsr166 1.4 * An {@link ExecutorService} for running {@link ForkJoinTask}s.
21 jsr166 1.8 * A {@code ForkJoinPool} provides the entry point for submissions
22 dl 1.18 * from non-{@code ForkJoinTask} clients, as well as management and
23 jsr166 1.11 * monitoring operations.
24 jsr166 1.1 *
25 jsr166 1.9 * <p>A {@code ForkJoinPool} differs from other kinds of {@link
26     * ExecutorService} mainly by virtue of employing
27     * <em>work-stealing</em>: all threads in the pool attempt to find and
28     * execute subtasks created by other active tasks (eventually blocking
29     * waiting for work if none exist). This enables efficient processing
30     * when most tasks spawn other subtasks (as do most {@code
31 dl 1.18 * ForkJoinTask}s). When setting <em>asyncMode</em> to true in
32     * constructors, {@code ForkJoinPool}s may also be appropriate for use
33     * with event-style tasks that are never joined.
34 jsr166 1.1 *
35 jsr166 1.9 * <p>A {@code ForkJoinPool} is constructed with a given target
36     * parallelism level; by default, equal to the number of available
37 dl 1.18 * processors. The pool attempts to maintain enough active (or
38     * available) threads by dynamically adding, suspending, or resuming
39     * internal worker threads, even if some tasks are stalled waiting to
40     * join others. However, no such adjustments are guaranteed in the
41     * face of blocked IO or other unmanaged synchronization. The nested
42     * {@link ManagedBlocker} interface enables extension of the kinds of
43     * synchronization accommodated.
44 jsr166 1.1 *
45     * <p>In addition to execution and lifecycle control methods, this
46     * class provides status check methods (for example
47 jsr166 1.4 * {@link #getStealCount}) that are intended to aid in developing,
48 jsr166 1.1 * tuning, and monitoring fork/join applications. Also, method
49 jsr166 1.4 * {@link #toString} returns indications of pool state in a
50 jsr166 1.1 * convenient form for informal monitoring.
51     *
52 dl 1.18 * <p> As is the case with other ExecutorServices, there are three
53 dl 1.19 * main task execution methods summarized in the following
54 dl 1.18 * table. These are designed to be used by clients not already engaged
55     * in fork/join computations in the current pool. The main forms of
56     * these methods accept instances of {@code ForkJoinTask}, but
57     * overloaded forms also allow mixed execution of plain {@code
58     * Runnable}- or {@code Callable}- based activities as well. However,
59     * tasks that are already executing in a pool should normally
60     * <em>NOT</em> use these pool execution methods, but instead use the
61 dl 1.19 * within-computation forms listed in the table.
62 dl 1.18 *
63     * <table BORDER CELLPADDING=3 CELLSPACING=1>
64     * <tr>
65     * <td></td>
66     * <td ALIGN=CENTER> <b>Call from non-fork/join clients</b></td>
67     * <td ALIGN=CENTER> <b>Call from within fork/join computations</b></td>
68     * </tr>
69     * <tr>
70     * <td> <b>Arange async execution</td>
71     * <td> {@link #execute(ForkJoinTask)}</td>
72     * <td> {@link ForkJoinTask#fork}</td>
73     * </tr>
74     * <tr>
75     * <td> <b>Await and obtain result</td>
76     * <td> {@link #invoke(ForkJoinTask)}</td>
77     * <td> {@link ForkJoinTask#invoke}</td>
78     * </tr>
79     * <tr>
80     * <td> <b>Arrange exec and obtain Future</td>
81     * <td> {@link #submit(ForkJoinTask)}</td>
82     * <td> {@link ForkJoinTask#fork} (ForkJoinTasks <em>are</em> Futures)</td>
83     * </tr>
84     * </table>
85 dl 1.19 *
86 jsr166 1.9 * <p><b>Sample Usage.</b> Normally a single {@code ForkJoinPool} is
87     * used for all parallel task execution in a program or subsystem.
88     * Otherwise, use would not usually outweigh the construction and
89     * bookkeeping overhead of creating a large set of threads. For
90     * example, a common pool could be used for the {@code SortTasks}
91     * illustrated in {@link RecursiveAction}. Because {@code
92     * ForkJoinPool} uses threads in {@linkplain java.lang.Thread#isDaemon
93     * daemon} mode, there is typically no need to explicitly {@link
94     * #shutdown} such a pool upon program exit.
95     *
96     * <pre>
97     * static final ForkJoinPool mainPool = new ForkJoinPool();
98     * ...
99     * public void sort(long[] array) {
100     * mainPool.invoke(new SortTask(array, 0, array.length));
101     * }
102     * </pre>
103     *
104 jsr166 1.1 * <p><b>Implementation notes</b>: This implementation restricts the
105     * maximum number of running threads to 32767. Attempts to create
106 jsr166 1.11 * pools with greater than the maximum number result in
107 jsr166 1.8 * {@code IllegalArgumentException}.
108 jsr166 1.1 *
109 jsr166 1.11 * <p>This implementation rejects submitted tasks (that is, by throwing
110 dl 1.19 * {@link RejectedExecutionException}) only when the pool is shut down
111 dl 1.20 * or internal resources have been exhausted.
112 jsr166 1.11 *
113 jsr166 1.1 * @since 1.7
114     * @author Doug Lea
115     */
116     public class ForkJoinPool extends AbstractExecutorService {
117    
118     /*
119 dl 1.14 * Implementation Overview
120     *
121     * This class provides the central bookkeeping and control for a
122     * set of worker threads: Submissions from non-FJ threads enter
123     * into a submission queue. Workers take these tasks and typically
124     * split them into subtasks that may be stolen by other workers.
125     * The main work-stealing mechanics implemented in class
126     * ForkJoinWorkerThread give first priority to processing tasks
127     * from their own queues (LIFO or FIFO, depending on mode), then
128     * to randomized FIFO steals of tasks in other worker queues, and
129     * lastly to new submissions. These mechanics do not consider
130     * affinities, loads, cache localities, etc, so rarely provide the
131     * best possible performance on a given machine, but portably
132     * provide good throughput by averaging over these factors.
133     * (Further, even if we did try to use such information, we do not
134     * usually have a basis for exploiting it. For example, some sets
135     * of tasks profit from cache affinities, but others are harmed by
136     * cache pollution effects.)
137     *
138 dl 1.19 * Beyond work-stealing support and essential bookkeeping, the
139     * main responsibility of this framework is to take actions when
140     * one worker is waiting to join a task stolen (or always held by)
141     * another. Becauae we are multiplexing many tasks on to a pool
142     * of workers, we can't just let them block (as in Thread.join).
143     * We also cannot just reassign the joiner's run-time stack with
144     * another and replace it later, which would be a form of
145     * "continuation", that even if possible is not necessarily a good
146     * idea. Given that the creation costs of most threads on most
147     * systems mainly surrounds setting up runtime stacks, thread
148     * creation and switching is usually not much more expensive than
149     * stack creation and switching, and is more flexible). Instead we
150     * combine two tactics:
151     *
152     * Helping: Arranging for the joiner to execute some task that it
153     * would be running if the steal had not occurred. Method
154     * ForkJoinWorkerThread.helpJoinTask tracks joining->stealing
155     * links to try to find such a task.
156     *
157     * Compensating: Unless there are already enough live threads,
158     * method helpMaintainParallelism() may create or or
159     * re-activate a spare thread to compensate for blocked
160     * joiners until they unblock.
161     *
162     * Because the determining existence of conservatively safe
163     * helping targets, the availability of already-created spares,
164     * and the apparent need to create new spares are all racy and
165     * require heuristic guidance, we rely on multiple retries of
166     * each. Further, because it is impossible to keep exactly the
167     * target (parallelism) number of threads running at any given
168     * time, we allow compensation during joins to fail, and enlist
169     * all other threads to help out whenever they are not otherwise
170     * occupied (i.e., mainly in method preStep).
171     *
172     * The ManagedBlocker extension API can't use helping so relies
173     * only on compensation in method awaitBlocker.
174     *
175 dl 1.14 * The main throughput advantages of work-stealing stem from
176     * decentralized control -- workers mostly steal tasks from each
177     * other. We do not want to negate this by creating bottlenecks
178 dl 1.19 * implementing other management responsibilities. So we use a
179     * collection of techniques that avoid, reduce, or cope well with
180     * contention. These entail several instances of bit-packing into
181     * CASable fields to maintain only the minimally required
182     * atomicity. To enable such packing, we restrict maximum
183     * parallelism to (1<<15)-1 (enabling twice this (to accommodate
184     * unbalanced increments and decrements) to fit into a 16 bit
185     * field, which is far in excess of normal operating range. Even
186     * though updates to some of these bookkeeping fields do sometimes
187     * contend with each other, they don't normally cache-contend with
188     * updates to others enough to warrant memory padding or
189     * isolation. So they are all held as fields of ForkJoinPool
190     * objects. The main capabilities are as follows:
191 dl 1.14 *
192     * 1. Creating and removing workers. Workers are recorded in the
193     * "workers" array. This is an array as opposed to some other data
194     * structure to support index-based random steals by workers.
195     * Updates to the array recording new workers and unrecording
196     * terminated ones are protected from each other by a lock
197     * (workerLock) but the array is otherwise concurrently readable,
198     * and accessed directly by workers. To simplify index-based
199     * operations, the array size is always a power of two, and all
200 dl 1.17 * readers must tolerate null slots. Currently, all worker thread
201     * creation is on-demand, triggered by task submissions,
202     * replacement of terminated workers, and/or compensation for
203     * blocked workers. However, all other support code is set up to
204     * work with other policies.
205 dl 1.14 *
206 dl 1.19 * To ensure that we do not hold on to worker references that
207     * would prevent GC, ALL accesses to workers are via indices into
208     * the workers array (which is one source of some of the unusual
209     * code constructions here). In essence, the workers array serves
210     * as a WeakReference mechanism. Thus for example the event queue
211     * stores worker indices, not worker references. Access to the
212     * workers in associated methods (for example releaseEventWaiters)
213     * must both index-check and null-check the IDs. All such accesses
214     * ignore bad IDs by returning out early from what they are doing,
215     * since this can only be associated with shutdown, in which case
216     * it is OK to give up. On termination, we just clobber these
217     * data structures without trying to use them.
218     *
219 dl 1.14 * 2. Bookkeeping for dynamically adding and removing workers. We
220 dl 1.18 * aim to approximately maintain the given level of parallelism.
221     * When some workers are known to be blocked (on joins or via
222 dl 1.14 * ManagedBlocker), we may create or resume others to take their
223     * place until they unblock (see below). Implementing this
224     * requires counts of the number of "running" threads (i.e., those
225     * that are neither blocked nor artifically suspended) as well as
226     * the total number. These two values are packed into one field,
227     * "workerCounts" because we need accurate snapshots when deciding
228 dl 1.19 * to create, resume or suspend. Note however that the
229     * correspondance of these counts to reality is not guaranteed. In
230     * particular updates for unblocked threads may lag until they
231     * actually wake up.
232 dl 1.14 *
233     * 3. Maintaining global run state. The run state of the pool
234     * consists of a runLevel (SHUTDOWN, TERMINATING, etc) similar to
235     * those in other Executor implementations, as well as a count of
236     * "active" workers -- those that are, or soon will be, or
237     * recently were executing tasks. The runLevel and active count
238     * are packed together in order to correctly trigger shutdown and
239     * termination. Without care, active counts can be subject to very
240     * high contention. We substantially reduce this contention by
241     * relaxing update rules. A worker must claim active status
242     * prospectively, by activating if it sees that a submitted or
243     * stealable task exists (it may find after activating that the
244     * task no longer exists). It stays active while processing this
245     * task (if it exists) and any other local subtasks it produces,
246     * until it cannot find any other tasks. It then tries
247     * inactivating (see method preStep), but upon update contention
248     * instead scans for more tasks, later retrying inactivation if it
249     * doesn't find any.
250     *
251     * 4. Managing idle workers waiting for tasks. We cannot let
252     * workers spin indefinitely scanning for tasks when none are
253     * available. On the other hand, we must quickly prod them into
254     * action when new tasks are submitted or generated. We
255     * park/unpark these idle workers using an event-count scheme.
256     * Field eventCount is incremented upon events that may enable
257     * workers that previously could not find a task to now find one:
258     * Submission of a new task to the pool, or another worker pushing
259     * a task onto a previously empty queue. (We also use this
260 dl 1.22 * mechanism for configuration and termination actions that
261     * require wakeups of idle workers). Each worker maintains its
262     * last known event count, and blocks when a scan for work did not
263     * find a task AND its lastEventCount matches the current
264     * eventCount. Waiting idle workers are recorded in a variant of
265     * Treiber stack headed by field eventWaiters which, when nonzero,
266     * encodes the thread index and count awaited for by the worker
267     * thread most recently calling eventSync. This thread in turn has
268     * a record (field nextEventWaiter) for the next waiting worker.
269     * In addition to allowing simpler decisions about need for
270     * wakeup, the event count bits in eventWaiters serve the role of
271     * tags to avoid ABA errors in Treiber stacks. Upon any wakeup,
272     * released threads also try to release others (but give up upon
273     * contention to reduce useless flailing). The net effect is a
274     * tree-like diffusion of signals, where released threads (and
275     * possibly others) help with unparks. To further reduce
276     * contention effects a bit, failed CASes to increment field
277     * eventCount are tolerated without retries in signalWork.
278 dl 1.14 * Conceptually they are merged into the same event, which is OK
279     * when their only purpose is to enable workers to scan for work.
280     *
281     * 5. Managing suspension of extra workers. When a worker is about
282     * to block waiting for a join (or via ManagedBlockers), we may
283     * create a new thread to maintain parallelism level, or at least
284 dl 1.19 * avoid starvation. Usually, extra threads are needed for only
285     * very short periods, yet join dependencies are such that we
286     * sometimes need them in bursts. Rather than create new threads
287     * each time this happens, we suspend no-longer-needed extra ones
288     * as "spares". For most purposes, we don't distinguish "extra"
289     * spare threads from normal "core" threads: On each call to
290     * preStep (the only point at which we can do this) a worker
291 dl 1.14 * checks to see if there are now too many running workers, and if
292 dl 1.19 * so, suspends itself. Method helpMaintainParallelism looks for
293     * suspended threads to resume before considering creating a new
294     * replacement. The spares themselves are encoded on another
295     * variant of a Treiber Stack, headed at field "spareWaiters".
296     * Note that the use of spares is intrinsically racy. One thread
297 dl 1.14 * may become a spare at about the same time as another is
298     * needlessly being created. We counteract this and related slop
299     * in part by requiring resumed spares to immediately recheck (in
300 dl 1.22 * preStep) to see whether they they should re-suspend.
301 dl 1.14 *
302 dl 1.22 * 6. Killing off unneeded workers. The Spare and Event queues use
303     * similar mechanisms to shed unused workers: The oldest (first)
304     * waiter uses a timed rather than hard wait. When this wait times
305     * out without a normal wakeup, it tries to shutdown any one (for
306     * convenience the newest) other waiter via tryShutdownSpare or
307     * tryShutdownWaiter, respectively. The wakeup rates for spares
308     * are much shorter than for waiters. Together, they will
309     * eventually reduce the number of worker threads to a minimum of
310     * one after a long enough period without use.
311     *
312     * 7. Deciding when to create new workers. The main dynamic
313 dl 1.19 * control in this class is deciding when to create extra threads
314     * in method helpMaintainParallelism. We would like to keep
315     * exactly #parallelism threads running, which is an impossble
316     * task. We always need to create one when the number of running
317     * threads would become zero and all workers are busy. Beyond
318     * this, we must rely on heuristics that work well in the the
319     * presence of transients phenomena such as GC stalls, dynamic
320     * compilation, and wake-up lags. These transients are extremely
321     * common -- we are normally trying to fully saturate the CPUs on
322     * a machine, so almost any activity other than running tasks
323     * impedes accuracy. Our main defense is to allow some slack in
324     * creation thresholds, using rules that reflect the fact that the
325     * more threads we have running, the more likely that we are
326 dl 1.22 * underestimating the number running threads. (We also include
327     * some heuristic use of Thread.yield when all workers appear to
328     * be busy, to improve likelihood of counts settling.) The rules
329     * also better cope with the fact that some of the methods in this
330 dl 1.19 * class tend to never become compiled (but are interpreted), so
331     * some components of the entire set of controls might execute 100
332     * times faster than others. And similarly for cases where the
333     * apparent lack of work is just due to GC stalls and other
334     * transient system activity.
335 dl 1.14 *
336     * Beware that there is a lot of representation-level coupling
337     * among classes ForkJoinPool, ForkJoinWorkerThread, and
338     * ForkJoinTask. For example, direct access to "workers" array by
339     * workers, and direct access to ForkJoinTask.status by both
340     * ForkJoinPool and ForkJoinWorkerThread. There is little point
341     * trying to reduce this, since any associated future changes in
342     * representations will need to be accompanied by algorithmic
343     * changes anyway.
344     *
345     * Style notes: There are lots of inline assignments (of form
346     * "while ((local = field) != 0)") which are usually the simplest
347 dl 1.19 * way to ensure the required read orderings (which are sometimes
348     * critical). Also several occurrences of the unusual "do {}
349     * while(!cas...)" which is the simplest way to force an update of
350     * a CAS'ed variable. There are also other coding oddities that
351     * help some methods perform reasonably even when interpreted (not
352     * compiled), at the expense of some messy constructions that
353     * reduce byte code counts.
354 dl 1.14 *
355     * The order of declarations in this file is: (1) statics (2)
356     * fields (along with constants used when unpacking some of them)
357     * (3) internal control methods (4) callbacks and other support
358     * for ForkJoinTask and ForkJoinWorkerThread classes, (5) exported
359     * methods (plus a few little helpers).
360 jsr166 1.1 */
361    
362     /**
363 jsr166 1.8 * Factory for creating new {@link ForkJoinWorkerThread}s.
364     * A {@code ForkJoinWorkerThreadFactory} must be defined and used
365     * for {@code ForkJoinWorkerThread} subclasses that extend base
366     * functionality or initialize threads with different contexts.
367 jsr166 1.1 */
368     public static interface ForkJoinWorkerThreadFactory {
369     /**
370     * Returns a new worker thread operating in the given pool.
371     *
372     * @param pool the pool this thread works in
373 jsr166 1.11 * @throws NullPointerException if the pool is null
374 jsr166 1.1 */
375     public ForkJoinWorkerThread newThread(ForkJoinPool pool);
376     }
377    
378     /**
379     * Default ForkJoinWorkerThreadFactory implementation; creates a
380     * new ForkJoinWorkerThread.
381     */
382 dl 1.18 static class DefaultForkJoinWorkerThreadFactory
383 jsr166 1.1 implements ForkJoinWorkerThreadFactory {
384     public ForkJoinWorkerThread newThread(ForkJoinPool pool) {
385 dl 1.14 return new ForkJoinWorkerThread(pool);
386 jsr166 1.1 }
387     }
388    
389     /**
390     * Creates a new ForkJoinWorkerThread. This factory is used unless
391     * overridden in ForkJoinPool constructors.
392     */
393     public static final ForkJoinWorkerThreadFactory
394     defaultForkJoinWorkerThreadFactory =
395     new DefaultForkJoinWorkerThreadFactory();
396    
397     /**
398     * Permission required for callers of methods that may start or
399     * kill threads.
400     */
401     private static final RuntimePermission modifyThreadPermission =
402     new RuntimePermission("modifyThread");
403    
404     /**
405     * If there is a security manager, makes sure caller has
406     * permission to modify threads.
407     */
408     private static void checkPermission() {
409     SecurityManager security = System.getSecurityManager();
410     if (security != null)
411     security.checkPermission(modifyThreadPermission);
412     }
413    
414     /**
415     * Generator for assigning sequence numbers as pool names.
416     */
417     private static final AtomicInteger poolNumberGenerator =
418     new AtomicInteger();
419    
420     /**
421 dl 1.22 * The wakeup interval (in nanoseconds) for the oldest worker
422     * worker waiting for an event invokes tryShutdownWaiter to shrink
423     * the number of workers. The exact value does not matter too
424     * much, but should be long enough to slowly release resources
425     * during long periods without use without disrupting normal use.
426     */
427     private static final long SHRINK_RATE_NANOS =
428     60L * 1000L * 1000L * 1000L; // one minute
429    
430     /**
431 dl 1.19 * Absolute bound for parallelism level. Twice this number plus
432     * one (i.e., 0xfff) must fit into a 16bit field to enable
433     * word-packing for some counts and indices.
434 dl 1.14 */
435 dl 1.19 private static final int MAX_WORKERS = 0x7fff;
436 dl 1.14
437     /**
438     * Array holding all worker threads in the pool. Array size must
439     * be a power of two. Updates and replacements are protected by
440     * workerLock, but the array is always kept in a consistent enough
441     * state to be randomly accessed without locking by workers
442     * performing work-stealing, as well as other traversal-based
443     * methods in this class. All readers must tolerate that some
444     * array slots may be null.
445 jsr166 1.1 */
446     volatile ForkJoinWorkerThread[] workers;
447    
448     /**
449 dl 1.14 * Queue for external submissions.
450 jsr166 1.1 */
451 dl 1.14 private final LinkedTransferQueue<ForkJoinTask<?>> submissionQueue;
452 jsr166 1.1
453     /**
454 dl 1.14 * Lock protecting updates to workers array.
455 jsr166 1.1 */
456 dl 1.14 private final ReentrantLock workerLock;
457 jsr166 1.1
458     /**
459 dl 1.14 * Latch released upon termination.
460 jsr166 1.1 */
461 dl 1.18 private final Phaser termination;
462 jsr166 1.1
463     /**
464     * Creation factory for worker threads.
465     */
466     private final ForkJoinWorkerThreadFactory factory;
467    
468     /**
469 dl 1.14 * Sum of per-thread steal counts, updated only when threads are
470     * idle or terminating.
471 jsr166 1.1 */
472 dl 1.14 private volatile long stealCount;
473 jsr166 1.1
474     /**
475 dl 1.14 * Encoded record of top of treiber stack of threads waiting for
476     * events. The top 32 bits contain the count being waited for. The
477 dl 1.19 * bottom 16 bits contains one plus the pool index of waiting
478     * worker thread. (Bits 16-31 are unused.)
479 jsr166 1.1 */
480 dl 1.14 private volatile long eventWaiters;
481    
482     private static final int EVENT_COUNT_SHIFT = 32;
483 dl 1.19 private static final long WAITER_ID_MASK = (1L << 16) - 1L;
484 jsr166 1.1
485     /**
486 dl 1.14 * A counter for events that may wake up worker threads:
487     * - Submission of a new task to the pool
488     * - A worker pushing a task on an empty queue
489 dl 1.19 * - termination
490 jsr166 1.1 */
491 dl 1.14 private volatile int eventCount;
492    
493     /**
494 dl 1.19 * Encoded record of top of treiber stack of spare threads waiting
495     * for resumption. The top 16 bits contain an arbitrary count to
496     * avoid ABA effects. The bottom 16bits contains one plus the pool
497     * index of waiting worker thread.
498     */
499     private volatile int spareWaiters;
500    
501     private static final int SPARE_COUNT_SHIFT = 16;
502     private static final int SPARE_ID_MASK = (1 << 16) - 1;
503    
504     /**
505 dl 1.14 * Lifecycle control. The low word contains the number of workers
506     * that are (probably) executing tasks. This value is atomically
507     * incremented before a worker gets a task to run, and decremented
508     * when worker has no tasks and cannot find any. Bits 16-18
509     * contain runLevel value. When all are zero, the pool is
510     * running. Level transitions are monotonic (running -> shutdown
511     * -> terminating -> terminated) so each transition adds a bit.
512     * These are bundled together to ensure consistent read for
513     * termination checks (i.e., that runLevel is at least SHUTDOWN
514     * and active threads is zero).
515 dl 1.22 *
516     * Notes: Most direct CASes are dependent on these bitfield
517     * positions. Also, this field is non-private to enable direct
518     * performance-sensitive CASes in ForkJoinWorkerThread.
519 dl 1.14 */
520 dl 1.22 volatile int runState;
521 dl 1.14
522     // Note: The order among run level values matters.
523     private static final int RUNLEVEL_SHIFT = 16;
524     private static final int SHUTDOWN = 1 << RUNLEVEL_SHIFT;
525     private static final int TERMINATING = 1 << (RUNLEVEL_SHIFT + 1);
526     private static final int TERMINATED = 1 << (RUNLEVEL_SHIFT + 2);
527     private static final int ACTIVE_COUNT_MASK = (1 << RUNLEVEL_SHIFT) - 1;
528 jsr166 1.1
529     /**
530 dl 1.14 * Holds number of total (i.e., created and not yet terminated)
531     * and running (i.e., not blocked on joins or other managed sync)
532     * threads, packed together to ensure consistent snapshot when
533     * making decisions about creating and suspending spare
534     * threads. Updated only by CAS. Note that adding a new worker
535     * requires incrementing both counts, since workers start off in
536 dl 1.19 * running state.
537 dl 1.14 */
538     private volatile int workerCounts;
539    
540     private static final int TOTAL_COUNT_SHIFT = 16;
541     private static final int RUNNING_COUNT_MASK = (1 << TOTAL_COUNT_SHIFT) - 1;
542     private static final int ONE_RUNNING = 1;
543     private static final int ONE_TOTAL = 1 << TOTAL_COUNT_SHIFT;
544    
545 jsr166 1.1 /**
546 dl 1.14 * The target parallelism level.
547 dl 1.18 * Accessed directly by ForkJoinWorkerThreads.
548 jsr166 1.1 */
549 dl 1.18 final int parallelism;
550 jsr166 1.1
551     /**
552 dl 1.14 * True if use local fifo, not default lifo, for local polling
553 dl 1.18 * Read by, and replicated by ForkJoinWorkerThreads
554 jsr166 1.1 */
555 dl 1.18 final boolean locallyFifo;
556 jsr166 1.1
557     /**
558 dl 1.18 * The uncaught exception handler used when any worker abruptly
559     * terminates.
560 jsr166 1.1 */
561 dl 1.18 private final Thread.UncaughtExceptionHandler ueh;
562 jsr166 1.1
563     /**
564 dl 1.14 * Pool number, just for assigning useful names to worker threads
565 jsr166 1.1 */
566 dl 1.14 private final int poolNumber;
567 jsr166 1.1
568 dl 1.19
569 dl 1.22 // Utilities for CASing fields. Note that most of these
570     // are usually manually inlined by callers
571 jsr166 1.1
572     /**
573 dl 1.19 * Increments running count part of workerCounts
574 jsr166 1.1 */
575 dl 1.18 final void incrementRunningCount() {
576     int c;
577 dl 1.14 do {} while (!UNSAFE.compareAndSwapInt(this, workerCountsOffset,
578 dl 1.19 c = workerCounts,
579 dl 1.18 c + ONE_RUNNING));
580 jsr166 1.1 }
581 dl 1.19
582 jsr166 1.1 /**
583 dl 1.18 * Tries to decrement running count unless already zero
584 dl 1.17 */
585     final boolean tryDecrementRunningCount() {
586     int wc = workerCounts;
587     if ((wc & RUNNING_COUNT_MASK) == 0)
588     return false;
589     return UNSAFE.compareAndSwapInt(this, workerCountsOffset,
590     wc, wc - ONE_RUNNING);
591     }
592    
593     /**
594 dl 1.19 * Forces decrement of encoded workerCounts, awaiting nonzero if
595     * (rarely) necessary when other count updates lag.
596     *
597     * @param dr -- either zero or ONE_RUNNING
598     * @param dt == either zero or ONE_TOTAL
599     */
600     private void decrementWorkerCounts(int dr, int dt) {
601     for (;;) {
602     int wc = workerCounts;
603     if ((wc & RUNNING_COUNT_MASK) - dr < 0 ||
604 dl 1.22 (wc >>> TOTAL_COUNT_SHIFT) - dt < 0) {
605     if ((runState & TERMINATED) != 0)
606     return; // lagging termination on a backout
607 dl 1.19 Thread.yield();
608 dl 1.22 }
609 dl 1.19 if (UNSAFE.compareAndSwapInt(this, workerCountsOffset,
610     wc, wc - (dr + dt)))
611     return;
612     }
613     }
614    
615     /**
616     * Increments event count
617     */
618     private void advanceEventCount() {
619     int c;
620     do {} while(!UNSAFE.compareAndSwapInt(this, eventCountOffset,
621     c = eventCount, c+1));
622     }
623    
624     /**
625 jsr166 1.1 * Tries incrementing active count; fails on contention.
626 dl 1.14 * Called by workers before executing tasks.
627 jsr166 1.1 *
628     * @return true on success
629     */
630     final boolean tryIncrementActiveCount() {
631 dl 1.14 int c;
632     return UNSAFE.compareAndSwapInt(this, runStateOffset,
633 dl 1.22 c = runState, c + 1);
634 jsr166 1.1 }
635    
636     /**
637     * Tries decrementing active count; fails on contention.
638 dl 1.14 * Called when workers cannot find tasks to run.
639     */
640     final boolean tryDecrementActiveCount() {
641     int c;
642     return UNSAFE.compareAndSwapInt(this, runStateOffset,
643 dl 1.22 c = runState, c - 1);
644 dl 1.14 }
645    
646     /**
647     * Advances to at least the given level. Returns true if not
648     * already in at least the given level.
649     */
650     private boolean advanceRunLevel(int level) {
651     for (;;) {
652     int s = runState;
653     if ((s & level) != 0)
654     return false;
655     if (UNSAFE.compareAndSwapInt(this, runStateOffset, s, s | level))
656     return true;
657     }
658     }
659    
660     // workers array maintenance
661    
662     /**
663     * Records and returns a workers array index for new worker.
664     */
665     private int recordWorker(ForkJoinWorkerThread w) {
666     // Try using slot totalCount-1. If not available, scan and/or resize
667     int k = (workerCounts >>> TOTAL_COUNT_SHIFT) - 1;
668     final ReentrantLock lock = this.workerLock;
669     lock.lock();
670     try {
671     ForkJoinWorkerThread[] ws = workers;
672 dl 1.19 int n = ws.length;
673     if (k < 0 || k >= n || ws[k] != null) {
674     for (k = 0; k < n && ws[k] != null; ++k)
675 dl 1.14 ;
676 dl 1.19 if (k == n)
677     ws = Arrays.copyOf(ws, n << 1);
678 dl 1.14 }
679     ws[k] = w;
680     workers = ws; // volatile array write ensures slot visibility
681     } finally {
682     lock.unlock();
683     }
684     return k;
685     }
686    
687     /**
688     * Nulls out record of worker in workers array
689     */
690     private void forgetWorker(ForkJoinWorkerThread w) {
691     int idx = w.poolIndex;
692     // Locking helps method recordWorker avoid unecessary expansion
693     final ReentrantLock lock = this.workerLock;
694     lock.lock();
695     try {
696     ForkJoinWorkerThread[] ws = workers;
697     if (idx >= 0 && idx < ws.length && ws[idx] == w) // verify
698     ws[idx] = null;
699     } finally {
700     lock.unlock();
701     }
702     }
703    
704     // adding and removing workers
705    
706     /**
707     * Tries to create and add new worker. Assumes that worker counts
708     * are already updated to accommodate the worker, so adjusts on
709     * failure.
710 dl 1.22 *
711     * @return the worker, or null on failure
712 dl 1.14 */
713 dl 1.22 private ForkJoinWorkerThread addWorker() {
714 dl 1.14 ForkJoinWorkerThread w = null;
715     try {
716     w = factory.newThread(this);
717     } finally { // Adjust on either null or exceptional factory return
718     if (w == null) {
719 dl 1.19 decrementWorkerCounts(ONE_RUNNING, ONE_TOTAL);
720     tryTerminate(false); // in case of failure during shutdown
721 dl 1.14 }
722     }
723 dl 1.22 if (w != null) {
724 dl 1.19 w.start(recordWorker(w), ueh);
725 dl 1.22 advanceEventCount();
726     }
727     return w;
728 dl 1.14 }
729    
730     /**
731     * Final callback from terminating worker. Removes record of
732     * worker from array, and adjusts counts. If pool is shutting
733 dl 1.19 * down, tries to complete terminatation.
734 dl 1.14 *
735     * @param w the worker
736     */
737     final void workerTerminated(ForkJoinWorkerThread w) {
738     forgetWorker(w);
739 dl 1.19 decrementWorkerCounts(w.isTrimmed()? 0 : ONE_RUNNING, ONE_TOTAL);
740     while (w.stealCount != 0) // collect final count
741     tryAccumulateStealCount(w);
742     tryTerminate(false);
743 dl 1.14 }
744    
745     // Waiting for and signalling events
746    
747     /**
748     * Releases workers blocked on a count not equal to current count.
749 dl 1.19 * Normally called after precheck that eventWaiters isn't zero to
750 dl 1.22 * avoid wasted array checks. Gives up upon a change in count or
751     * contention, letting other workers take over.
752 dl 1.14 */
753 dl 1.22 private void releaseEventWaiters() {
754 dl 1.19 ForkJoinWorkerThread[] ws = workers;
755     int n = ws.length;
756 dl 1.22 long h = eventWaiters;
757     int ec = eventCount;
758     ForkJoinWorkerThread w; int id;
759     while ((int)(h >>> EVENT_COUNT_SHIFT) != ec &&
760     (id = ((int)(h & WAITER_ID_MASK)) - 1) >= 0 &&
761     id < n && (w = ws[id]) != null &&
762     UNSAFE.compareAndSwapLong(this, eventWaitersOffset,
763     h, h = w.nextWaiter)) {
764     LockSupport.unpark(w);
765     if (eventWaiters != h || eventCount != ec)
766 dl 1.19 break;
767 dl 1.14 }
768     }
769    
770     /**
771 dl 1.19 * Tries to advance eventCount and releases waiters. Called only
772     * from workers.
773 dl 1.18 */
774 dl 1.19 final void signalWork() {
775     int c; // try to increment event count -- CAS failure OK
776     UNSAFE.compareAndSwapInt(this, eventCountOffset, c = eventCount, c+1);
777     if (eventWaiters != 0L)
778 dl 1.22 releaseEventWaiters();
779 dl 1.18 }
780    
781     /**
782 dl 1.22 * Adds the given worker to event queue and blocks until
783     * terminating or event count advances from the workers
784     * lastEventCount value
785 dl 1.19 *
786     * @param w the calling worker thread
787 dl 1.14 */
788 dl 1.19 private void eventSync(ForkJoinWorkerThread w) {
789 dl 1.22 int ec = w.lastEventCount;
790     long nh = (((long)ec) << EVENT_COUNT_SHIFT) | ((long)(w.poolIndex+1));
791 dl 1.19 long h;
792     while ((runState < SHUTDOWN || !tryTerminate(false)) &&
793 dl 1.22 (((int)((h = eventWaiters) & WAITER_ID_MASK)) == 0 ||
794     (int)(h >>> EVENT_COUNT_SHIFT) == ec) &&
795     eventCount == ec) {
796 dl 1.19 if (UNSAFE.compareAndSwapLong(this, eventWaitersOffset,
797     w.nextWaiter = h, nh)) {
798 dl 1.22 awaitEvent(w, ec);
799     break;
800     }
801     }
802     }
803    
804     /**
805     * Blocks the given worker (that has already been entered as an
806     * event waiter) until terminating or event count advances from
807     * the given value. The oldest (first) waiter uses a timed wait to
808     * occasionally one-by-one shrink the number of workers (to a
809     * minumum of one) if the pool has not been used for extended
810     * periods.
811     *
812     * @param w the calling worker thread
813     * @param ec the count
814     */
815     private void awaitEvent(ForkJoinWorkerThread w, int ec) {
816     while (eventCount == ec) {
817     if (tryAccumulateStealCount(w)) { // transfer while idle
818     boolean untimed = (w.nextWaiter != 0L ||
819     (workerCounts & RUNNING_COUNT_MASK) <= 1);
820     long startTime = untimed? 0 : System.nanoTime();
821     Thread.interrupted(); // clear/ignore interrupt
822     if (eventCount != ec || !w.isRunning() ||
823     runState >= TERMINATING) // recheck after clear
824     break;
825     if (untimed)
826     LockSupport.park(w);
827     else {
828     LockSupport.parkNanos(w, SHRINK_RATE_NANOS);
829     if (eventCount != ec || !w.isRunning() ||
830     runState >= TERMINATING)
831 dl 1.19 break;
832 dl 1.22 if (System.nanoTime() - startTime >= SHRINK_RATE_NANOS)
833     tryShutdownWaiter(ec);
834 dl 1.19 }
835 dl 1.14 }
836     }
837 dl 1.22 }
838    
839     /**
840     * Callback from the oldest waiter in awaitEvent waking up after a
841     * period of non-use. Tries (once) to shutdown an event waiter (or
842     * a spare, if one exists). Note that we don't need CAS or locks
843     * here because the method is called only from one thread
844     * occasionally waking (and even misfires are OK). Note that
845     * until the shutdown worker fully terminates, workerCounts
846     * will overestimate total count, which is tolerable.
847     *
848     * @param ec the event count waited on by caller (to abort
849     * attempt if count has since changed).
850     */
851     private void tryShutdownWaiter(int ec) {
852     if (spareWaiters != 0) { // prefer killing spares
853     tryShutdownSpare();
854     return;
855     }
856     ForkJoinWorkerThread[] ws = workers;
857     int n = ws.length;
858     long h = eventWaiters;
859     ForkJoinWorkerThread w; int id; long nh;
860     if (runState == 0 &&
861     submissionQueue.isEmpty() &&
862     eventCount == ec &&
863     (id = ((int)(h & WAITER_ID_MASK)) - 1) >= 0 &&
864     id < n && (w = ws[id]) != null &&
865     (nh = w.nextWaiter) != 0L && // keep at least one worker
866     UNSAFE.compareAndSwapLong(this, eventWaitersOffset, h, nh)) {
867     w.shutdown();
868     LockSupport.unpark(w);
869     }
870     releaseEventWaiters();
871 dl 1.19 }
872    
873     // Maintaining spares
874    
875     /**
876     * Pushes worker onto the spare stack
877     */
878     final void pushSpare(ForkJoinWorkerThread w) {
879 dl 1.22 int ns = (++w.spareCount << SPARE_COUNT_SHIFT) | (w.poolIndex + 1);
880 dl 1.19 do {} while (!UNSAFE.compareAndSwapInt(this, spareWaitersOffset,
881     w.nextSpare = spareWaiters,ns));
882 dl 1.14 }
883    
884     /**
885 dl 1.22 * Callback from oldest spare occasionally waking up. Tries
886     * (once) to shutdown a spare. Same idea as tryShutdownWaiter.
887 dl 1.14 */
888 dl 1.22 final void tryShutdownSpare() {
889 dl 1.19 int sw, id;
890     ForkJoinWorkerThread w;
891     ForkJoinWorkerThread[] ws;
892     if ((id = ((sw = spareWaiters) & SPARE_ID_MASK) - 1) >= 0 &&
893     id < (ws = workers).length && (w = ws[id]) != null &&
894 dl 1.22 (workerCounts & RUNNING_COUNT_MASK) >= parallelism &&
895 dl 1.19 UNSAFE.compareAndSwapInt(this, spareWaitersOffset,
896 dl 1.22 sw, w.nextSpare)) {
897     w.shutdown();
898 dl 1.19 LockSupport.unpark(w);
899 dl 1.22 advanceEventCount();
900     }
901     }
902    
903     /**
904     * Tries (once) to resume a spare if worker counts match
905     * the given count.
906     *
907     * @param wc workerCounts value on invocation of this method
908     */
909     private void tryResumeSpare(int wc) {
910     ForkJoinWorkerThread[] ws = workers;
911     int n = ws.length;
912     int sw, id, rs; ForkJoinWorkerThread w;
913     if ((id = ((sw = spareWaiters) & SPARE_ID_MASK) - 1) >= 0 &&
914     id < n && (w = ws[id]) != null &&
915     (rs = runState) < TERMINATING &&
916     eventWaiters == 0L && workerCounts == wc) {
917     // In case all workers busy, heuristically back off to let settle
918     Thread.yield();
919     if (eventWaiters == 0L && runState == rs && // recheck
920     workerCounts == wc && spareWaiters == sw &&
921     UNSAFE.compareAndSwapInt(this, spareWaitersOffset,
922     sw, w.nextSpare)) {
923     int c; // increment running count before resume
924     do {} while(!UNSAFE.compareAndSwapInt
925     (this, workerCountsOffset,
926     c = workerCounts, c + ONE_RUNNING));
927     if (w.tryUnsuspend())
928     LockSupport.unpark(w);
929     else // back out if w was shutdown
930     decrementWorkerCounts(ONE_RUNNING, 0);
931 dl 1.14 }
932     }
933 dl 1.19 }
934    
935 dl 1.22 // adding workers on demand
936    
937 dl 1.19 /**
938 dl 1.22 * Adds one or more workers if needed to establish target parallelism.
939     * Retries upon contention.
940     */
941     private void addWorkerIfBelowTarget() {
942     int pc = parallelism;
943     int wc;
944     while (((wc = workerCounts) >>> TOTAL_COUNT_SHIFT) < pc &&
945     runState < TERMINATING) {
946     if (UNSAFE.compareAndSwapInt(this, workerCountsOffset, wc,
947     wc + (ONE_RUNNING|ONE_TOTAL))) {
948     if (addWorker() == null)
949     break;
950     }
951     }
952     }
953    
954     /**
955     * Tries (once) to add a new worker if all existing workers are
956     * busy, and there are either no running workers or the deficit is
957     * at least twice the surplus.
958     *
959     * @param wc workerCounts value on invocation of this method
960     */
961     private void tryAddWorkerIfBusy(int wc) {
962     int tc, rc, rs;
963 dl 1.19 int pc = parallelism;
964 dl 1.22 if ((tc = wc >>> TOTAL_COUNT_SHIFT) < MAX_WORKERS &&
965     ((rc = wc & RUNNING_COUNT_MASK) == 0 ||
966     rc < pc - ((tc - pc) << 1)) &&
967     (rs = runState) < TERMINATING &&
968     (rs & ACTIVE_COUNT_MASK) == tc) {
969     // Since all workers busy, heuristically back off to let settle
970     Thread.yield();
971     if (eventWaiters == 0L && spareWaiters == 0 && // recheck
972     runState == rs && workerCounts == wc &&
973     UNSAFE.compareAndSwapInt(this, workerCountsOffset, wc,
974     wc + (ONE_RUNNING|ONE_TOTAL)))
975     addWorker();
976     }
977 dl 1.19 }
978    
979     /**
980     * Does at most one of:
981     *
982     * 1. Help wake up existing workers waiting for work via
983 dl 1.22 * releaseEventWaiters. (If any exist, then it doesn't
984 dl 1.19 * matter right now if under target parallelism level.)
985     *
986 dl 1.22 * 2. If a spare exists, try (once) to resume it via tryResumeSpare.
987 dl 1.19 *
988 dl 1.22 * 3. If there are not enough total workers, add some
989     * via addWorkerIfBelowTarget;
990     *
991     * 4. Try (once) to add a new worker if all existing workers
992     * are busy, via tryAddWorkerIfBusy
993 dl 1.19 */
994     private void helpMaintainParallelism() {
995 dl 1.22 long h; int pc, wc;
996     if (((int)((h = eventWaiters) & WAITER_ID_MASK)) != 0) {
997 dl 1.19 if ((int)(h >>> EVENT_COUNT_SHIFT) != eventCount)
998 dl 1.22 releaseEventWaiters(); // avoid useless call
999 dl 1.19 }
1000     else if ((pc = parallelism) >
1001 dl 1.22 ((wc = workerCounts) & RUNNING_COUNT_MASK)) {
1002 dl 1.19 if (spareWaiters != 0)
1003 dl 1.22 tryResumeSpare(wc);
1004     else if ((wc >>> TOTAL_COUNT_SHIFT) < pc)
1005     addWorkerIfBelowTarget();
1006     else
1007     tryAddWorkerIfBusy(wc);
1008 dl 1.19 }
1009 dl 1.14 }
1010    
1011     /**
1012     * Callback from workers invoked upon each top-level action (i.e.,
1013 dl 1.22 * stealing a task or taking a submission and running it).
1014     * Performs one or more of the following:
1015 dl 1.19 *
1016 dl 1.22 * 1. If the worker is active, try to set its active status to
1017     * inactive and update activeCount. On contention, we may try
1018     * again on this or subsequent call.
1019 dl 1.19 *
1020 dl 1.22 * 2. Release any existing event waiters that are now relesable
1021 dl 1.19 *
1022 dl 1.22 * 3. If there are too many running threads, suspend this worker
1023     * (first forcing inactive if necessary). If it is not
1024 dl 1.19 * needed, it may be killed while suspended via
1025 dl 1.22 * tryShutdownSpare. Otherwise, upon resume it rechecks to make
1026 dl 1.19 * sure that it is still needed.
1027 dl 1.14 *
1028 dl 1.22 * 4. If more than 1 miss, await the next task event via
1029     * eventSync (first forcing inactivation if necessary), upon
1030     * which worker may also be killed, via tryShutdownWaiter.
1031     *
1032     * 5. Help reactivate other workers via helpMaintainParallelism
1033 dl 1.14 *
1034     * @param w the worker
1035 dl 1.19 * @param misses the number of scans by caller failing to find work
1036 dl 1.22 * (saturating at 2 to avoid wraparound)
1037 dl 1.14 */
1038 dl 1.19 final void preStep(ForkJoinWorkerThread w, int misses) {
1039 dl 1.14 boolean active = w.active;
1040 dl 1.19 int pc = parallelism;
1041 dl 1.14 for (;;) {
1042 dl 1.22 int rs, wc, rc, ec; long h;
1043     if (active && UNSAFE.compareAndSwapInt(this, runStateOffset,
1044     rs = runState, rs - 1))
1045     active = w.active = false;
1046     if (((int)((h = eventWaiters) & WAITER_ID_MASK)) != 0 &&
1047     (int)(h >>> EVENT_COUNT_SHIFT) != eventCount) {
1048     releaseEventWaiters();
1049     if (misses > 1)
1050     continue; // clear before sync below
1051 dl 1.19 }
1052 dl 1.22 if ((rc = ((wc = workerCounts) & RUNNING_COUNT_MASK)) > pc) {
1053     if (!active && // must inactivate to suspend
1054     workerCounts == wc && // try to suspend as spare
1055 dl 1.19 UNSAFE.compareAndSwapInt(this, workerCountsOffset,
1056 dl 1.22 wc, wc - ONE_RUNNING)) {
1057     w.suspendAsSpare();
1058     if (!w.isRunning())
1059     break; // was killed while spare
1060     }
1061     continue;
1062 dl 1.19 }
1063 dl 1.22 if (misses > 0) {
1064     if ((ec = eventCount) == w.lastEventCount && misses > 1) {
1065     if (!active) { // must inactivate to sync
1066     eventSync(w);
1067     if (w.isRunning())
1068     misses = 1; // don't re-sync
1069     else
1070     break; // was killed while waiting
1071     }
1072     continue;
1073     }
1074     w.lastEventCount = ec;
1075 dl 1.14 }
1076 dl 1.22 if (rc < pc)
1077     helpMaintainParallelism();
1078     break;
1079 dl 1.14 }
1080     }
1081    
1082     /**
1083 dl 1.19 * Helps and/or blocks awaiting join of the given task.
1084     * Alternates between helpJoinTask() and helpMaintainParallelism()
1085     * as many times as there is a deficit in running count (or longer
1086     * if running count would become zero), then blocks if task still
1087     * not done.
1088 dl 1.17 *
1089     * @param joinMe the task to join
1090 dl 1.14 */
1091 dl 1.19 final void awaitJoin(ForkJoinTask<?> joinMe, ForkJoinWorkerThread worker) {
1092     int threshold = parallelism; // descend blocking thresholds
1093     while (joinMe.status >= 0) {
1094     boolean block; int wc;
1095     worker.helpJoinTask(joinMe);
1096     if (joinMe.status < 0)
1097     break;
1098     if (((wc = workerCounts) & RUNNING_COUNT_MASK) <= threshold) {
1099     if (threshold > 0)
1100     --threshold;
1101     else
1102     advanceEventCount(); // force release
1103     block = false;
1104     }
1105     else
1106     block = UNSAFE.compareAndSwapInt(this, workerCountsOffset,
1107     wc, wc - ONE_RUNNING);
1108     helpMaintainParallelism();
1109     if (block) {
1110     int c;
1111     joinMe.internalAwaitDone();
1112     do {} while (!UNSAFE.compareAndSwapInt
1113     (this, workerCountsOffset,
1114     c = workerCounts, c + ONE_RUNNING));
1115     break;
1116 dl 1.14 }
1117     }
1118     }
1119    
1120     /**
1121 dl 1.19 * Same idea as awaitJoin, but no helping
1122 dl 1.14 */
1123 dl 1.18 final void awaitBlocker(ManagedBlocker blocker)
1124 dl 1.14 throws InterruptedException {
1125 dl 1.19 int threshold = parallelism;
1126     while (!blocker.isReleasable()) {
1127     boolean block; int wc;
1128     if (((wc = workerCounts) & RUNNING_COUNT_MASK) <= threshold) {
1129     if (threshold > 0)
1130     --threshold;
1131     else
1132     advanceEventCount();
1133     block = false;
1134 dl 1.14 }
1135 dl 1.19 else
1136     block = UNSAFE.compareAndSwapInt(this, workerCountsOffset,
1137     wc, wc - ONE_RUNNING);
1138     helpMaintainParallelism();
1139     if (block) {
1140     try {
1141     do {} while (!blocker.isReleasable() && !blocker.block());
1142     } finally {
1143 dl 1.14 int c;
1144 dl 1.17 do {} while (!UNSAFE.compareAndSwapInt
1145     (this, workerCountsOffset,
1146     c = workerCounts, c + ONE_RUNNING));
1147 dl 1.14 }
1148 dl 1.18 break;
1149     }
1150 dl 1.14 }
1151 dl 1.19 }
1152 dl 1.15
1153     /**
1154 dl 1.14 * Possibly initiates and/or completes termination.
1155     *
1156     * @param now if true, unconditionally terminate, else only
1157     * if shutdown and empty queue and no active workers
1158     * @return true if now terminating or terminated
1159 jsr166 1.1 */
1160 dl 1.14 private boolean tryTerminate(boolean now) {
1161     if (now)
1162     advanceRunLevel(SHUTDOWN); // ensure at least SHUTDOWN
1163     else if (runState < SHUTDOWN ||
1164     !submissionQueue.isEmpty() ||
1165     (runState & ACTIVE_COUNT_MASK) != 0)
1166 jsr166 1.1 return false;
1167 dl 1.14
1168     if (advanceRunLevel(TERMINATING))
1169     startTerminating();
1170    
1171     // Finish now if all threads terminated; else in some subsequent call
1172     if ((workerCounts >>> TOTAL_COUNT_SHIFT) == 0) {
1173     advanceRunLevel(TERMINATED);
1174 dl 1.18 termination.arrive();
1175 dl 1.14 }
1176 jsr166 1.1 return true;
1177     }
1178    
1179     /**
1180 dl 1.14 * Actions on transition to TERMINATING
1181 dl 1.19 *
1182     * Runs up to four passes through workers: (0) shutting down each
1183 dl 1.22 * (without waking up if parked) to quickly spread notifications
1184     * without unnecessary bouncing around event queues etc (1) wake
1185     * up and help cancel tasks (2) interrupt (3) mop up races with
1186     * interrupted workers
1187 dl 1.14 */
1188     private void startTerminating() {
1189 dl 1.19 cancelSubmissions();
1190     for (int passes = 0; passes < 4 && workerCounts != 0; ++passes) {
1191     advanceEventCount();
1192     eventWaiters = 0L; // clobber lists
1193     spareWaiters = 0;
1194     ForkJoinWorkerThread[] ws = workers;
1195     int n = ws.length;
1196     for (int i = 0; i < n; ++i) {
1197     ForkJoinWorkerThread w = ws[i];
1198     if (w != null) {
1199 dl 1.22 w.shutdown();
1200 dl 1.19 if (passes > 0 && !w.isTerminated()) {
1201     w.cancelTasks();
1202     LockSupport.unpark(w);
1203     if (passes > 1) {
1204     try {
1205     w.interrupt();
1206     } catch (SecurityException ignore) {
1207     }
1208     }
1209     }
1210     }
1211     }
1212 dl 1.17 }
1213     }
1214    
1215     /**
1216     * Clear out and cancel submissions, ignoring exceptions
1217     */
1218     private void cancelSubmissions() {
1219 dl 1.14 ForkJoinTask<?> task;
1220     while ((task = submissionQueue.poll()) != null) {
1221     try {
1222     task.cancel(false);
1223     } catch (Throwable ignore) {
1224     }
1225     }
1226 dl 1.17 }
1227    
1228 dl 1.14 // misc support for ForkJoinWorkerThread
1229    
1230     /**
1231     * Returns pool number
1232 jsr166 1.1 */
1233 dl 1.14 final int getPoolNumber() {
1234     return poolNumber;
1235 jsr166 1.1 }
1236    
1237     /**
1238 dl 1.19 * Tries to accumulates steal count from a worker, clearing
1239     * the worker's value.
1240     *
1241     * @return true if worker steal count now zero
1242 jsr166 1.1 */
1243 dl 1.19 final boolean tryAccumulateStealCount(ForkJoinWorkerThread w) {
1244 dl 1.14 int sc = w.stealCount;
1245 dl 1.19 long c = stealCount;
1246     // CAS even if zero, for fence effects
1247     if (UNSAFE.compareAndSwapLong(this, stealCountOffset, c, c + sc)) {
1248     if (sc != 0)
1249     w.stealCount = 0;
1250     return true;
1251 jsr166 1.1 }
1252 dl 1.19 return sc == 0;
1253 jsr166 1.1 }
1254    
1255     /**
1256 dl 1.14 * Returns the approximate (non-atomic) number of idle threads per
1257     * active thread.
1258     */
1259     final int idlePerActive() {
1260 dl 1.19 int pc = parallelism; // use parallelism, not rc
1261 dl 1.14 int ac = runState; // no mask -- artifically boosts during shutdown
1262     // Use exact results for small values, saturate past 4
1263     return pc <= ac? 0 : pc >>> 1 <= ac? 1 : pc >>> 2 <= ac? 3 : pc >>> 3;
1264     }
1265    
1266     // Public and protected methods
1267 jsr166 1.1
1268     // Constructors
1269    
1270     /**
1271 jsr166 1.9 * Creates a {@code ForkJoinPool} with parallelism equal to {@link
1272 dl 1.18 * java.lang.Runtime#availableProcessors}, using the {@linkplain
1273     * #defaultForkJoinWorkerThreadFactory default thread factory},
1274     * no UncaughtExceptionHandler, and non-async LIFO processing mode.
1275 jsr166 1.1 *
1276     * @throws SecurityException if a security manager exists and
1277     * the caller is not permitted to modify threads
1278     * because it does not hold {@link
1279     * java.lang.RuntimePermission}{@code ("modifyThread")}
1280     */
1281     public ForkJoinPool() {
1282     this(Runtime.getRuntime().availableProcessors(),
1283 dl 1.18 defaultForkJoinWorkerThreadFactory, null, false);
1284 jsr166 1.1 }
1285    
1286     /**
1287 jsr166 1.9 * Creates a {@code ForkJoinPool} with the indicated parallelism
1288 dl 1.18 * level, the {@linkplain
1289     * #defaultForkJoinWorkerThreadFactory default thread factory},
1290     * no UncaughtExceptionHandler, and non-async LIFO processing mode.
1291 jsr166 1.1 *
1292 jsr166 1.9 * @param parallelism the parallelism level
1293 jsr166 1.1 * @throws IllegalArgumentException if parallelism less than or
1294 jsr166 1.11 * equal to zero, or greater than implementation limit
1295 jsr166 1.1 * @throws SecurityException if a security manager exists and
1296     * the caller is not permitted to modify threads
1297     * because it does not hold {@link
1298     * java.lang.RuntimePermission}{@code ("modifyThread")}
1299     */
1300     public ForkJoinPool(int parallelism) {
1301 dl 1.18 this(parallelism, defaultForkJoinWorkerThreadFactory, null, false);
1302 jsr166 1.1 }
1303    
1304     /**
1305 dl 1.18 * Creates a {@code ForkJoinPool} with the given parameters.
1306 jsr166 1.1 *
1307 dl 1.18 * @param parallelism the parallelism level. For default value,
1308     * use {@link java.lang.Runtime#availableProcessors}.
1309     * @param factory the factory for creating new threads. For default value,
1310     * use {@link #defaultForkJoinWorkerThreadFactory}.
1311 dl 1.19 * @param handler the handler for internal worker threads that
1312     * terminate due to unrecoverable errors encountered while executing
1313 dl 1.18 * tasks. For default value, use <code>null</code>.
1314 dl 1.19 * @param asyncMode if true,
1315 dl 1.18 * establishes local first-in-first-out scheduling mode for forked
1316     * tasks that are never joined. This mode may be more appropriate
1317     * than default locally stack-based mode in applications in which
1318     * worker threads only process event-style asynchronous tasks.
1319     * For default value, use <code>false</code>.
1320 jsr166 1.1 * @throws IllegalArgumentException if parallelism less than or
1321 jsr166 1.11 * equal to zero, or greater than implementation limit
1322     * @throws NullPointerException if the factory is null
1323 jsr166 1.1 * @throws SecurityException if a security manager exists and
1324     * the caller is not permitted to modify threads
1325     * because it does not hold {@link
1326     * java.lang.RuntimePermission}{@code ("modifyThread")}
1327     */
1328 dl 1.19 public ForkJoinPool(int parallelism,
1329 dl 1.18 ForkJoinWorkerThreadFactory factory,
1330     Thread.UncaughtExceptionHandler handler,
1331     boolean asyncMode) {
1332 dl 1.14 checkPermission();
1333     if (factory == null)
1334     throw new NullPointerException();
1335 dl 1.19 if (parallelism <= 0 || parallelism > MAX_WORKERS)
1336 jsr166 1.1 throw new IllegalArgumentException();
1337 dl 1.14 this.parallelism = parallelism;
1338 jsr166 1.1 this.factory = factory;
1339 dl 1.18 this.ueh = handler;
1340     this.locallyFifo = asyncMode;
1341     int arraySize = initialArraySizeFor(parallelism);
1342 dl 1.14 this.workers = new ForkJoinWorkerThread[arraySize];
1343     this.submissionQueue = new LinkedTransferQueue<ForkJoinTask<?>>();
1344 jsr166 1.1 this.workerLock = new ReentrantLock();
1345 dl 1.18 this.termination = new Phaser(1);
1346     this.poolNumber = poolNumberGenerator.incrementAndGet();
1347 jsr166 1.1 }
1348    
1349     /**
1350 dl 1.14 * Returns initial power of two size for workers array.
1351     * @param pc the initial parallelism level
1352     */
1353     private static int initialArraySizeFor(int pc) {
1354 dl 1.19 // See Hackers Delight, sec 3.2. We know MAX_WORKERS < (1 >>> 16)
1355     int size = pc < MAX_WORKERS ? pc + 1 : MAX_WORKERS;
1356 dl 1.14 size |= size >>> 1;
1357     size |= size >>> 2;
1358     size |= size >>> 4;
1359     size |= size >>> 8;
1360     return size + 1;
1361 jsr166 1.1 }
1362    
1363     // Execution methods
1364    
1365     /**
1366     * Common code for execute, invoke and submit
1367     */
1368     private <T> void doSubmit(ForkJoinTask<T> task) {
1369 jsr166 1.2 if (task == null)
1370     throw new NullPointerException();
1371 dl 1.14 if (runState >= SHUTDOWN)
1372 jsr166 1.1 throw new RejectedExecutionException();
1373 dl 1.19 submissionQueue.offer(task);
1374     advanceEventCount();
1375 dl 1.22 if (eventWaiters != 0L)
1376     releaseEventWaiters();
1377     if ((workerCounts >>> TOTAL_COUNT_SHIFT) < parallelism)
1378     addWorkerIfBelowTarget();
1379 jsr166 1.1 }
1380    
1381     /**
1382     * Performs the given task, returning its result upon completion.
1383     *
1384     * @param task the task
1385     * @return the task's result
1386 jsr166 1.11 * @throws NullPointerException if the task is null
1387     * @throws RejectedExecutionException if the task cannot be
1388     * scheduled for execution
1389 jsr166 1.1 */
1390     public <T> T invoke(ForkJoinTask<T> task) {
1391     doSubmit(task);
1392     return task.join();
1393     }
1394    
1395     /**
1396     * Arranges for (asynchronous) execution of the given task.
1397     *
1398     * @param task the task
1399 jsr166 1.11 * @throws NullPointerException if the task is null
1400     * @throws RejectedExecutionException if the task cannot be
1401     * scheduled for execution
1402 jsr166 1.1 */
1403 jsr166 1.8 public void execute(ForkJoinTask<?> task) {
1404 jsr166 1.1 doSubmit(task);
1405     }
1406    
1407     // AbstractExecutorService methods
1408    
1409 jsr166 1.11 /**
1410     * @throws NullPointerException if the task is null
1411     * @throws RejectedExecutionException if the task cannot be
1412     * scheduled for execution
1413     */
1414 jsr166 1.1 public void execute(Runnable task) {
1415 jsr166 1.2 ForkJoinTask<?> job;
1416 jsr166 1.3 if (task instanceof ForkJoinTask<?>) // avoid re-wrap
1417     job = (ForkJoinTask<?>) task;
1418 jsr166 1.2 else
1419 jsr166 1.7 job = ForkJoinTask.adapt(task, null);
1420 jsr166 1.2 doSubmit(job);
1421 jsr166 1.1 }
1422    
1423 jsr166 1.11 /**
1424 dl 1.18 * Submits a ForkJoinTask for execution.
1425     *
1426     * @param task the task to submit
1427     * @return the task
1428     * @throws NullPointerException if the task is null
1429     * @throws RejectedExecutionException if the task cannot be
1430     * scheduled for execution
1431     */
1432     public <T> ForkJoinTask<T> submit(ForkJoinTask<T> task) {
1433     doSubmit(task);
1434     return task;
1435     }
1436    
1437     /**
1438 jsr166 1.11 * @throws NullPointerException if the task is null
1439     * @throws RejectedExecutionException if the task cannot be
1440     * scheduled for execution
1441     */
1442 jsr166 1.1 public <T> ForkJoinTask<T> submit(Callable<T> task) {
1443 jsr166 1.7 ForkJoinTask<T> job = ForkJoinTask.adapt(task);
1444 jsr166 1.1 doSubmit(job);
1445     return job;
1446     }
1447    
1448 jsr166 1.11 /**
1449     * @throws NullPointerException if the task is null
1450     * @throws RejectedExecutionException if the task cannot be
1451     * scheduled for execution
1452     */
1453 jsr166 1.1 public <T> ForkJoinTask<T> submit(Runnable task, T result) {
1454 jsr166 1.7 ForkJoinTask<T> job = ForkJoinTask.adapt(task, result);
1455 jsr166 1.1 doSubmit(job);
1456     return job;
1457     }
1458    
1459 jsr166 1.11 /**
1460     * @throws NullPointerException if the task is null
1461     * @throws RejectedExecutionException if the task cannot be
1462     * scheduled for execution
1463     */
1464 jsr166 1.1 public ForkJoinTask<?> submit(Runnable task) {
1465 jsr166 1.2 ForkJoinTask<?> job;
1466 jsr166 1.3 if (task instanceof ForkJoinTask<?>) // avoid re-wrap
1467     job = (ForkJoinTask<?>) task;
1468 jsr166 1.2 else
1469 jsr166 1.7 job = ForkJoinTask.adapt(task, null);
1470 jsr166 1.1 doSubmit(job);
1471     return job;
1472     }
1473    
1474     /**
1475 jsr166 1.11 * @throws NullPointerException {@inheritDoc}
1476     * @throws RejectedExecutionException {@inheritDoc}
1477     */
1478 jsr166 1.1 public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) {
1479     ArrayList<ForkJoinTask<T>> forkJoinTasks =
1480     new ArrayList<ForkJoinTask<T>>(tasks.size());
1481     for (Callable<T> task : tasks)
1482 jsr166 1.7 forkJoinTasks.add(ForkJoinTask.adapt(task));
1483 jsr166 1.1 invoke(new InvokeAll<T>(forkJoinTasks));
1484    
1485     @SuppressWarnings({"unchecked", "rawtypes"})
1486 dl 1.15 List<Future<T>> futures = (List<Future<T>>) (List) forkJoinTasks;
1487 jsr166 1.1 return futures;
1488     }
1489    
1490     static final class InvokeAll<T> extends RecursiveAction {
1491     final ArrayList<ForkJoinTask<T>> tasks;
1492     InvokeAll(ArrayList<ForkJoinTask<T>> tasks) { this.tasks = tasks; }
1493     public void compute() {
1494     try { invokeAll(tasks); }
1495     catch (Exception ignore) {}
1496     }
1497     private static final long serialVersionUID = -7914297376763021607L;
1498     }
1499    
1500     /**
1501     * Returns the factory used for constructing new workers.
1502     *
1503     * @return the factory used for constructing new workers
1504     */
1505     public ForkJoinWorkerThreadFactory getFactory() {
1506     return factory;
1507     }
1508    
1509     /**
1510     * Returns the handler for internal worker threads that terminate
1511     * due to unrecoverable errors encountered while executing tasks.
1512     *
1513 jsr166 1.4 * @return the handler, or {@code null} if none
1514 jsr166 1.1 */
1515     public Thread.UncaughtExceptionHandler getUncaughtExceptionHandler() {
1516 dl 1.14 return ueh;
1517 jsr166 1.1 }
1518    
1519     /**
1520 jsr166 1.9 * Returns the targeted parallelism level of this pool.
1521 jsr166 1.1 *
1522 jsr166 1.9 * @return the targeted parallelism level of this pool
1523 jsr166 1.1 */
1524     public int getParallelism() {
1525     return parallelism;
1526     }
1527    
1528     /**
1529     * Returns the number of worker threads that have started but not
1530     * yet terminated. This result returned by this method may differ
1531 jsr166 1.4 * from {@link #getParallelism} when threads are created to
1532 jsr166 1.1 * maintain parallelism when others are cooperatively blocked.
1533     *
1534     * @return the number of worker threads
1535     */
1536     public int getPoolSize() {
1537 dl 1.14 return workerCounts >>> TOTAL_COUNT_SHIFT;
1538 jsr166 1.1 }
1539    
1540     /**
1541 jsr166 1.4 * Returns {@code true} if this pool uses local first-in-first-out
1542 jsr166 1.1 * scheduling mode for forked tasks that are never joined.
1543     *
1544 jsr166 1.4 * @return {@code true} if this pool uses async mode
1545 jsr166 1.1 */
1546     public boolean getAsyncMode() {
1547     return locallyFifo;
1548     }
1549    
1550     /**
1551     * Returns an estimate of the number of worker threads that are
1552     * not blocked waiting to join tasks or for other managed
1553 dl 1.14 * synchronization. This method may overestimate the
1554     * number of running threads.
1555 jsr166 1.1 *
1556     * @return the number of worker threads
1557     */
1558     public int getRunningThreadCount() {
1559 dl 1.14 return workerCounts & RUNNING_COUNT_MASK;
1560 jsr166 1.1 }
1561    
1562     /**
1563     * Returns an estimate of the number of threads that are currently
1564     * stealing or executing tasks. This method may overestimate the
1565     * number of active threads.
1566     *
1567     * @return the number of active threads
1568     */
1569     public int getActiveThreadCount() {
1570 dl 1.14 return runState & ACTIVE_COUNT_MASK;
1571 jsr166 1.1 }
1572    
1573     /**
1574 jsr166 1.4 * Returns {@code true} if all worker threads are currently idle.
1575     * An idle worker is one that cannot obtain a task to execute
1576     * because none are available to steal from other threads, and
1577     * there are no pending submissions to the pool. This method is
1578     * conservative; it might not return {@code true} immediately upon
1579     * idleness of all threads, but will eventually become true if
1580     * threads remain inactive.
1581 jsr166 1.1 *
1582 jsr166 1.4 * @return {@code true} if all threads are currently idle
1583 jsr166 1.1 */
1584     public boolean isQuiescent() {
1585 dl 1.14 return (runState & ACTIVE_COUNT_MASK) == 0;
1586 jsr166 1.1 }
1587    
1588     /**
1589     * Returns an estimate of the total number of tasks stolen from
1590     * one thread's work queue by another. The reported value
1591     * underestimates the actual total number of steals when the pool
1592     * is not quiescent. This value may be useful for monitoring and
1593     * tuning fork/join programs: in general, steal counts should be
1594     * high enough to keep threads busy, but low enough to avoid
1595     * overhead and contention across threads.
1596     *
1597     * @return the number of steals
1598     */
1599     public long getStealCount() {
1600 dl 1.14 return stealCount;
1601 jsr166 1.1 }
1602    
1603     /**
1604     * Returns an estimate of the total number of tasks currently held
1605     * in queues by worker threads (but not including tasks submitted
1606     * to the pool that have not begun executing). This value is only
1607     * an approximation, obtained by iterating across all threads in
1608     * the pool. This method may be useful for tuning task
1609     * granularities.
1610     *
1611     * @return the number of queued tasks
1612     */
1613     public long getQueuedTaskCount() {
1614     long count = 0;
1615 dl 1.17 ForkJoinWorkerThread[] ws = workers;
1616 dl 1.19 int n = ws.length;
1617     for (int i = 0; i < n; ++i) {
1618 dl 1.17 ForkJoinWorkerThread w = ws[i];
1619 dl 1.14 if (w != null)
1620     count += w.getQueueSize();
1621 jsr166 1.1 }
1622     return count;
1623     }
1624    
1625     /**
1626 jsr166 1.8 * Returns an estimate of the number of tasks submitted to this
1627     * pool that have not yet begun executing. This method takes time
1628 jsr166 1.1 * proportional to the number of submissions.
1629     *
1630     * @return the number of queued submissions
1631     */
1632     public int getQueuedSubmissionCount() {
1633     return submissionQueue.size();
1634     }
1635    
1636     /**
1637 jsr166 1.4 * Returns {@code true} if there are any tasks submitted to this
1638     * pool that have not yet begun executing.
1639 jsr166 1.1 *
1640     * @return {@code true} if there are any queued submissions
1641     */
1642     public boolean hasQueuedSubmissions() {
1643     return !submissionQueue.isEmpty();
1644     }
1645    
1646     /**
1647     * Removes and returns the next unexecuted submission if one is
1648     * available. This method may be useful in extensions to this
1649     * class that re-assign work in systems with multiple pools.
1650     *
1651 jsr166 1.4 * @return the next submission, or {@code null} if none
1652 jsr166 1.1 */
1653     protected ForkJoinTask<?> pollSubmission() {
1654     return submissionQueue.poll();
1655     }
1656    
1657     /**
1658     * Removes all available unexecuted submitted and forked tasks
1659     * from scheduling queues and adds them to the given collection,
1660     * without altering their execution status. These may include
1661 jsr166 1.8 * artificially generated or wrapped tasks. This method is
1662     * designed to be invoked only when the pool is known to be
1663 jsr166 1.1 * quiescent. Invocations at other times may not remove all
1664     * tasks. A failure encountered while attempting to add elements
1665     * to collection {@code c} may result in elements being in
1666     * neither, either or both collections when the associated
1667     * exception is thrown. The behavior of this operation is
1668     * undefined if the specified collection is modified while the
1669     * operation is in progress.
1670     *
1671     * @param c the collection to transfer elements into
1672     * @return the number of elements transferred
1673     */
1674 jsr166 1.5 protected int drainTasksTo(Collection<? super ForkJoinTask<?>> c) {
1675 dl 1.19 int count = submissionQueue.drainTo(c);
1676 dl 1.18 ForkJoinWorkerThread[] ws = workers;
1677 dl 1.19 int n = ws.length;
1678     for (int i = 0; i < n; ++i) {
1679 dl 1.18 ForkJoinWorkerThread w = ws[i];
1680     if (w != null)
1681 dl 1.19 count += w.drainTasksTo(c);
1682 dl 1.18 }
1683     return count;
1684     }
1685    
1686     /**
1687 jsr166 1.1 * Returns a string identifying this pool, as well as its state,
1688     * including indications of run state, parallelism level, and
1689     * worker and task counts.
1690     *
1691     * @return a string identifying this pool, as well as its state
1692     */
1693     public String toString() {
1694     long st = getStealCount();
1695     long qt = getQueuedTaskCount();
1696     long qs = getQueuedSubmissionCount();
1697 dl 1.14 int wc = workerCounts;
1698     int tc = wc >>> TOTAL_COUNT_SHIFT;
1699     int rc = wc & RUNNING_COUNT_MASK;
1700     int pc = parallelism;
1701     int rs = runState;
1702     int ac = rs & ACTIVE_COUNT_MASK;
1703 jsr166 1.1 return super.toString() +
1704 dl 1.14 "[" + runLevelToString(rs) +
1705     ", parallelism = " + pc +
1706     ", size = " + tc +
1707     ", active = " + ac +
1708     ", running = " + rc +
1709 jsr166 1.1 ", steals = " + st +
1710     ", tasks = " + qt +
1711     ", submissions = " + qs +
1712     "]";
1713     }
1714    
1715 dl 1.14 private static String runLevelToString(int s) {
1716     return ((s & TERMINATED) != 0 ? "Terminated" :
1717     ((s & TERMINATING) != 0 ? "Terminating" :
1718     ((s & SHUTDOWN) != 0 ? "Shutting down" :
1719     "Running")));
1720 jsr166 1.1 }
1721    
1722     /**
1723     * Initiates an orderly shutdown in which previously submitted
1724     * tasks are executed, but no new tasks will be accepted.
1725     * Invocation has no additional effect if already shut down.
1726     * Tasks that are in the process of being submitted concurrently
1727     * during the course of this method may or may not be rejected.
1728     *
1729     * @throws SecurityException if a security manager exists and
1730     * the caller is not permitted to modify threads
1731     * because it does not hold {@link
1732     * java.lang.RuntimePermission}{@code ("modifyThread")}
1733     */
1734     public void shutdown() {
1735     checkPermission();
1736 dl 1.14 advanceRunLevel(SHUTDOWN);
1737     tryTerminate(false);
1738 jsr166 1.1 }
1739    
1740     /**
1741 jsr166 1.9 * Attempts to cancel and/or stop all tasks, and reject all
1742     * subsequently submitted tasks. Tasks that are in the process of
1743     * being submitted or executed concurrently during the course of
1744     * this method may or may not be rejected. This method cancels
1745     * both existing and unexecuted tasks, in order to permit
1746     * termination in the presence of task dependencies. So the method
1747     * always returns an empty list (unlike the case for some other
1748     * Executors).
1749 jsr166 1.1 *
1750     * @return an empty list
1751     * @throws SecurityException if a security manager exists and
1752     * the caller is not permitted to modify threads
1753     * because it does not hold {@link
1754     * java.lang.RuntimePermission}{@code ("modifyThread")}
1755     */
1756     public List<Runnable> shutdownNow() {
1757     checkPermission();
1758 dl 1.14 tryTerminate(true);
1759 jsr166 1.1 return Collections.emptyList();
1760     }
1761    
1762     /**
1763     * Returns {@code true} if all tasks have completed following shut down.
1764     *
1765     * @return {@code true} if all tasks have completed following shut down
1766     */
1767     public boolean isTerminated() {
1768 dl 1.14 return runState >= TERMINATED;
1769 jsr166 1.1 }
1770    
1771     /**
1772     * Returns {@code true} if the process of termination has
1773 jsr166 1.9 * commenced but not yet completed. This method may be useful for
1774     * debugging. A return of {@code true} reported a sufficient
1775     * period after shutdown may indicate that submitted tasks have
1776     * ignored or suppressed interruption, causing this executor not
1777     * to properly terminate.
1778 jsr166 1.1 *
1779 jsr166 1.9 * @return {@code true} if terminating but not yet terminated
1780 jsr166 1.1 */
1781     public boolean isTerminating() {
1782 dl 1.14 return (runState & (TERMINATING|TERMINATED)) == TERMINATING;
1783 jsr166 1.1 }
1784    
1785     /**
1786     * Returns {@code true} if this pool has been shut down.
1787     *
1788     * @return {@code true} if this pool has been shut down
1789     */
1790     public boolean isShutdown() {
1791 dl 1.14 return runState >= SHUTDOWN;
1792 jsr166 1.9 }
1793    
1794     /**
1795 jsr166 1.1 * Blocks until all tasks have completed execution after a shutdown
1796     * request, or the timeout occurs, or the current thread is
1797     * interrupted, whichever happens first.
1798     *
1799     * @param timeout the maximum time to wait
1800     * @param unit the time unit of the timeout argument
1801     * @return {@code true} if this executor terminated and
1802     * {@code false} if the timeout elapsed before termination
1803     * @throws InterruptedException if interrupted while waiting
1804     */
1805     public boolean awaitTermination(long timeout, TimeUnit unit)
1806     throws InterruptedException {
1807 dl 1.18 try {
1808     return termination.awaitAdvanceInterruptibly(0, timeout, unit) > 0;
1809     } catch(TimeoutException ex) {
1810     return false;
1811     }
1812 jsr166 1.1 }
1813    
1814     /**
1815     * Interface for extending managed parallelism for tasks running
1816 jsr166 1.8 * in {@link ForkJoinPool}s.
1817     *
1818 dl 1.19 * <p>A {@code ManagedBlocker} provides two methods. Method
1819     * {@code isReleasable} must return {@code true} if blocking is
1820     * not necessary. Method {@code block} blocks the current thread
1821     * if necessary (perhaps internally invoking {@code isReleasable}
1822     * before actually blocking). The unusual methods in this API
1823     * accommodate synchronizers that may, but don't usually, block
1824     * for long periods. Similarly, they allow more efficient internal
1825     * handling of cases in which additional workers may be, but
1826     * usually are not, needed to ensure sufficient parallelism.
1827     * Toward this end, implementations of method {@code isReleasable}
1828     * must be amenable to repeated invocation.
1829 jsr166 1.1 *
1830     * <p>For example, here is a ManagedBlocker based on a
1831     * ReentrantLock:
1832     * <pre> {@code
1833     * class ManagedLocker implements ManagedBlocker {
1834     * final ReentrantLock lock;
1835     * boolean hasLock = false;
1836     * ManagedLocker(ReentrantLock lock) { this.lock = lock; }
1837     * public boolean block() {
1838     * if (!hasLock)
1839     * lock.lock();
1840     * return true;
1841     * }
1842     * public boolean isReleasable() {
1843     * return hasLock || (hasLock = lock.tryLock());
1844     * }
1845     * }}</pre>
1846 dl 1.19 *
1847     * <p>Here is a class that possibly blocks waiting for an
1848     * item on a given queue:
1849     * <pre> {@code
1850     * class QueueTaker<E> implements ManagedBlocker {
1851     * final BlockingQueue<E> queue;
1852     * volatile E item = null;
1853     * QueueTaker(BlockingQueue<E> q) { this.queue = q; }
1854     * public boolean block() throws InterruptedException {
1855     * if (item == null)
1856     * item = queue.take
1857     * return true;
1858     * }
1859     * public boolean isReleasable() {
1860     * return item != null || (item = queue.poll) != null;
1861     * }
1862     * public E getItem() { // call after pool.managedBlock completes
1863     * return item;
1864     * }
1865     * }}</pre>
1866 jsr166 1.1 */
1867     public static interface ManagedBlocker {
1868     /**
1869     * Possibly blocks the current thread, for example waiting for
1870     * a lock or condition.
1871     *
1872 jsr166 1.4 * @return {@code true} if no additional blocking is necessary
1873     * (i.e., if isReleasable would return true)
1874 jsr166 1.1 * @throws InterruptedException if interrupted while waiting
1875     * (the method is not required to do so, but is allowed to)
1876     */
1877     boolean block() throws InterruptedException;
1878    
1879     /**
1880 jsr166 1.4 * Returns {@code true} if blocking is unnecessary.
1881 jsr166 1.1 */
1882     boolean isReleasable();
1883     }
1884    
1885     /**
1886     * Blocks in accord with the given blocker. If the current thread
1887 jsr166 1.8 * is a {@link ForkJoinWorkerThread}, this method possibly
1888     * arranges for a spare thread to be activated if necessary to
1889 dl 1.18 * ensure sufficient parallelism while the current thread is blocked.
1890 jsr166 1.1 *
1891 jsr166 1.8 * <p>If the caller is not a {@link ForkJoinTask}, this method is
1892     * behaviorally equivalent to
1893 jsr166 1.1 * <pre> {@code
1894     * while (!blocker.isReleasable())
1895     * if (blocker.block())
1896     * return;
1897     * }</pre>
1898 jsr166 1.8 *
1899     * If the caller is a {@code ForkJoinTask}, then the pool may
1900     * first be expanded to ensure parallelism, and later adjusted.
1901 jsr166 1.1 *
1902     * @param blocker the blocker
1903     * @throws InterruptedException if blocker.block did so
1904     */
1905 dl 1.18 public static void managedBlock(ManagedBlocker blocker)
1906 jsr166 1.1 throws InterruptedException {
1907     Thread t = Thread.currentThread();
1908 dl 1.19 if (t instanceof ForkJoinWorkerThread) {
1909     ForkJoinWorkerThread w = (ForkJoinWorkerThread) t;
1910     w.pool.awaitBlocker(blocker);
1911     }
1912 dl 1.18 else {
1913     do {} while (!blocker.isReleasable() && !blocker.block());
1914     }
1915 jsr166 1.1 }
1916    
1917 jsr166 1.7 // AbstractExecutorService overrides. These rely on undocumented
1918     // fact that ForkJoinTask.adapt returns ForkJoinTasks that also
1919     // implement RunnableFuture.
1920 jsr166 1.1
1921     protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
1922 jsr166 1.7 return (RunnableFuture<T>) ForkJoinTask.adapt(runnable, value);
1923 jsr166 1.1 }
1924    
1925     protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
1926 jsr166 1.7 return (RunnableFuture<T>) ForkJoinTask.adapt(callable);
1927 jsr166 1.1 }
1928    
1929     // Unsafe mechanics
1930    
1931     private static final sun.misc.Unsafe UNSAFE = sun.misc.Unsafe.getUnsafe();
1932 dl 1.14 private static final long workerCountsOffset =
1933     objectFieldOffset("workerCounts", ForkJoinPool.class);
1934     private static final long runStateOffset =
1935     objectFieldOffset("runState", ForkJoinPool.class);
1936 jsr166 1.2 private static final long eventCountOffset =
1937 jsr166 1.3 objectFieldOffset("eventCount", ForkJoinPool.class);
1938 dl 1.14 private static final long eventWaitersOffset =
1939     objectFieldOffset("eventWaiters",ForkJoinPool.class);
1940     private static final long stealCountOffset =
1941     objectFieldOffset("stealCount",ForkJoinPool.class);
1942 dl 1.19 private static final long spareWaitersOffset =
1943     objectFieldOffset("spareWaiters",ForkJoinPool.class);
1944 jsr166 1.3
1945     private static long objectFieldOffset(String field, Class<?> klazz) {
1946     try {
1947     return UNSAFE.objectFieldOffset(klazz.getDeclaredField(field));
1948     } catch (NoSuchFieldException e) {
1949     // Convert Exception to corresponding Error
1950     NoSuchFieldError error = new NoSuchFieldError(field);
1951     error.initCause(e);
1952     throw error;
1953     }
1954     }
1955 jsr166 1.1 }