ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinPool.java
Revision: 1.239
Committed: Tue Feb 17 18:55:39 2015 UTC (9 years, 3 months ago) by jsr166
Branch: MAIN
Changes since 1.238: +3 -3 lines
Log Message:
standardize code sample idiom: * <pre> {@code

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 jsr166 1.58 * http://creativecommons.org/publicdomain/zero/1.0/
5 jsr166 1.1 */
6    
7     package java.util.concurrent;
8    
9 jsr166 1.156 import java.lang.Thread.UncaughtExceptionHandler;
10 jsr166 1.228 import java.security.AccessControlContext;
11     import java.security.Permissions;
12     import java.security.ProtectionDomain;
13 jsr166 1.1 import java.util.ArrayList;
14     import java.util.Arrays;
15     import java.util.Collection;
16     import java.util.Collections;
17     import java.util.List;
18 dl 1.215 import java.util.concurrent.atomic.AtomicLong;
19 jsr166 1.1
20     /**
21 jsr166 1.4 * An {@link ExecutorService} for running {@link ForkJoinTask}s.
22 jsr166 1.8 * A {@code ForkJoinPool} provides the entry point for submissions
23 dl 1.18 * from non-{@code ForkJoinTask} clients, as well as management and
24 jsr166 1.11 * monitoring operations.
25 jsr166 1.1 *
26 jsr166 1.9 * <p>A {@code ForkJoinPool} differs from other kinds of {@link
27     * ExecutorService} mainly by virtue of employing
28     * <em>work-stealing</em>: all threads in the pool attempt to find and
29 dl 1.78 * execute tasks submitted to the pool and/or created by other active
30     * tasks (eventually blocking waiting for work if none exist). This
31     * enables efficient processing when most tasks spawn other subtasks
32     * (as do most {@code ForkJoinTask}s), as well as when many small
33     * tasks are submitted to the pool from external clients. Especially
34     * when setting <em>asyncMode</em> to true in constructors, {@code
35     * ForkJoinPool}s may also be appropriate for use with event-style
36     * tasks that are never joined.
37 jsr166 1.1 *
38 dl 1.112 * <p>A static {@link #commonPool()} is available and appropriate for
39 dl 1.101 * most applications. The common pool is used by any ForkJoinTask that
40     * is not explicitly submitted to a specified pool. Using the common
41     * pool normally reduces resource usage (its threads are slowly
42     * reclaimed during periods of non-use, and reinstated upon subsequent
43 dl 1.105 * use).
44 dl 1.100 *
45     * <p>For applications that require separate or custom pools, a {@code
46     * ForkJoinPool} may be constructed with a given target parallelism
47 jsr166 1.214 * level; by default, equal to the number of available processors.
48     * The pool attempts to maintain enough active (or available) threads
49     * by dynamically adding, suspending, or resuming internal worker
50 jsr166 1.187 * threads, even if some tasks are stalled waiting to join others.
51     * However, no such adjustments are guaranteed in the face of blocked
52     * I/O or other unmanaged synchronization. The nested {@link
53 dl 1.100 * ManagedBlocker} interface enables extension of the kinds of
54 dl 1.18 * synchronization accommodated.
55 jsr166 1.1 *
56     * <p>In addition to execution and lifecycle control methods, this
57     * class provides status check methods (for example
58 jsr166 1.4 * {@link #getStealCount}) that are intended to aid in developing,
59 jsr166 1.1 * tuning, and monitoring fork/join applications. Also, method
60 jsr166 1.4 * {@link #toString} returns indications of pool state in a
61 jsr166 1.1 * convenient form for informal monitoring.
62     *
63 jsr166 1.109 * <p>As is the case with other ExecutorServices, there are three
64 jsr166 1.84 * main task execution methods summarized in the following table.
65     * These are designed to be used primarily by clients not already
66     * engaged in fork/join computations in the current pool. The main
67     * forms of these methods accept instances of {@code ForkJoinTask},
68     * but overloaded forms also allow mixed execution of plain {@code
69     * Runnable}- or {@code Callable}- based activities as well. However,
70     * tasks that are already executing in a pool should normally instead
71     * use the within-computation forms listed in the table unless using
72     * async event-style tasks that are not usually joined, in which case
73     * there is little difference among choice of methods.
74 dl 1.18 *
75     * <table BORDER CELLPADDING=3 CELLSPACING=1>
76 jsr166 1.159 * <caption>Summary of task execution methods</caption>
77 dl 1.18 * <tr>
78     * <td></td>
79     * <td ALIGN=CENTER> <b>Call from non-fork/join clients</b></td>
80     * <td ALIGN=CENTER> <b>Call from within fork/join computations</b></td>
81     * </tr>
82     * <tr>
83 jsr166 1.153 * <td> <b>Arrange async execution</b></td>
84 dl 1.18 * <td> {@link #execute(ForkJoinTask)}</td>
85     * <td> {@link ForkJoinTask#fork}</td>
86     * </tr>
87     * <tr>
88 jsr166 1.153 * <td> <b>Await and obtain result</b></td>
89 dl 1.18 * <td> {@link #invoke(ForkJoinTask)}</td>
90     * <td> {@link ForkJoinTask#invoke}</td>
91     * </tr>
92     * <tr>
93 jsr166 1.153 * <td> <b>Arrange exec and obtain Future</b></td>
94 dl 1.18 * <td> {@link #submit(ForkJoinTask)}</td>
95     * <td> {@link ForkJoinTask#fork} (ForkJoinTasks <em>are</em> Futures)</td>
96     * </tr>
97     * </table>
98 dl 1.19 *
99 dl 1.105 * <p>The common pool is by default constructed with default
100 jsr166 1.155 * parameters, but these may be controlled by setting three
101 jsr166 1.162 * {@linkplain System#getProperty system properties}:
102     * <ul>
103     * <li>{@code java.util.concurrent.ForkJoinPool.common.parallelism}
104     * - the parallelism level, a non-negative integer
105     * <li>{@code java.util.concurrent.ForkJoinPool.common.threadFactory}
106     * - the class name of a {@link ForkJoinWorkerThreadFactory}
107     * <li>{@code java.util.concurrent.ForkJoinPool.common.exceptionHandler}
108     * - the class name of a {@link UncaughtExceptionHandler}
109 dl 1.208 * <li>{@code java.util.concurrent.ForkJoinPool.common.maximumSpares}
110 dl 1.223 * - the maximum number of allowed extra threads to maintain target
111 dl 1.208 * parallelism (default 256).
112 jsr166 1.162 * </ul>
113 dl 1.197 * If a {@link SecurityManager} is present and no factory is
114     * specified, then the default pool uses a factory supplying
115     * threads that have no {@link Permissions} enabled.
116 jsr166 1.165 * The system class loader is used to load these classes.
117 jsr166 1.156 * Upon any error in establishing these settings, default parameters
118 dl 1.160 * are used. It is possible to disable or limit the use of threads in
119     * the common pool by setting the parallelism property to zero, and/or
120 dl 1.193 * using a factory that may return {@code null}. However doing so may
121     * cause unjoined tasks to never be executed.
122 dl 1.105 *
123 jsr166 1.1 * <p><b>Implementation notes</b>: This implementation restricts the
124     * maximum number of running threads to 32767. Attempts to create
125 jsr166 1.11 * pools with greater than the maximum number result in
126 jsr166 1.8 * {@code IllegalArgumentException}.
127 jsr166 1.1 *
128 jsr166 1.11 * <p>This implementation rejects submitted tasks (that is, by throwing
129 dl 1.19 * {@link RejectedExecutionException}) only when the pool is shut down
130 dl 1.20 * or internal resources have been exhausted.
131 jsr166 1.11 *
132 jsr166 1.1 * @since 1.7
133     * @author Doug Lea
134     */
135 jsr166 1.171 @sun.misc.Contended
136 jsr166 1.1 public class ForkJoinPool extends AbstractExecutorService {
137    
138     /*
139 dl 1.14 * Implementation Overview
140     *
141 dl 1.78 * This class and its nested classes provide the main
142     * functionality and control for a set of worker threads:
143 jsr166 1.84 * Submissions from non-FJ threads enter into submission queues.
144     * Workers take these tasks and typically split them into subtasks
145     * that may be stolen by other workers. Preference rules give
146     * first priority to processing tasks from their own queues (LIFO
147     * or FIFO, depending on mode), then to randomized FIFO steals of
148 dl 1.200 * tasks in other queues. This framework began as vehicle for
149     * supporting tree-structured parallelism using work-stealing.
150     * Over time, its scalability advantages led to extensions and
151 dl 1.208 * changes to better support more diverse usage contexts. Because
152     * most internal methods and nested classes are interrelated,
153     * their main rationale and descriptions are presented here;
154     * individual methods and nested classes contain only brief
155     * comments about details.
156 dl 1.78 *
157 jsr166 1.84 * WorkQueues
158 dl 1.78 * ==========
159     *
160     * Most operations occur within work-stealing queues (in nested
161     * class WorkQueue). These are special forms of Deques that
162     * support only three of the four possible end-operations -- push,
163     * pop, and poll (aka steal), under the further constraints that
164     * push and pop are called only from the owning thread (or, as
165     * extended here, under a lock), while poll may be called from
166     * other threads. (If you are unfamiliar with them, you probably
167     * want to read Herlihy and Shavit's book "The Art of
168     * Multiprocessor programming", chapter 16 describing these in
169     * more detail before proceeding.) The main work-stealing queue
170     * design is roughly similar to those in the papers "Dynamic
171     * Circular Work-Stealing Deque" by Chase and Lev, SPAA 2005
172     * (http://research.sun.com/scalable/pubs/index.html) and
173     * "Idempotent work stealing" by Michael, Saraswat, and Vechev,
174     * PPoPP 2009 (http://portal.acm.org/citation.cfm?id=1504186).
175 dl 1.200 * The main differences ultimately stem from GC requirements that
176     * we null out taken slots as soon as we can, to maintain as small
177     * a footprint as possible even in programs generating huge
178     * numbers of tasks. To accomplish this, we shift the CAS
179     * arbitrating pop vs poll (steal) from being on the indices
180     * ("base" and "top") to the slots themselves.
181     *
182     * Adding tasks then takes the form of a classic array push(task):
183     * q.array[q.top] = task; ++q.top;
184     *
185     * (The actual code needs to null-check and size-check the array,
186     * properly fence the accesses, and possibly signal waiting
187     * workers to start scanning -- see below.) Both a successful pop
188     * and poll mainly entail a CAS of a slot from non-null to null.
189     *
190 jsr166 1.202 * The pop operation (always performed by owner) is:
191 dl 1.200 * if ((base != top) and
192     * (the task at top slot is not null) and
193     * (CAS slot to null))
194     * decrement top and return task;
195     *
196     * And the poll operation (usually by a stealer) is
197     * if ((base != top) and
198     * (the task at base slot is not null) and
199     * (base has not changed) and
200     * (CAS slot to null))
201     * increment base and return task;
202     *
203     * Because we rely on CASes of references, we do not need tag bits
204     * on base or top. They are simple ints as used in any circular
205 dl 1.170 * array-based queue (see for example ArrayDeque). Updates to the
206 dl 1.200 * indices guarantee that top == base means the queue is empty,
207     * but otherwise may err on the side of possibly making the queue
208     * appear nonempty when a push, pop, or poll have not fully
209 dl 1.205 * committed. (Method isEmpty() checks the case of a partially
210 dl 1.211 * completed removal of the last element.) Because of this, the
211     * poll operation, considered individually, is not wait-free. One
212     * thief cannot successfully continue until another in-progress
213     * one (or, if previously empty, a push) completes. However, in
214     * the aggregate, we ensure at least probabilistic
215 dl 1.205 * non-blockingness. If an attempted steal fails, a thief always
216     * chooses a different random victim target to try next. So, in
217     * order for one thief to progress, it suffices for any
218     * in-progress poll or new push on any empty queue to
219     * complete. (This is why we normally use method pollAt and its
220     * variants that try once at the apparent base index, else
221     * consider alternative actions, rather than method poll, which
222     * retries.)
223 dl 1.200 *
224     * This approach also enables support of a user mode in which
225     * local task processing is in FIFO, not LIFO order, simply by
226     * using poll rather than pop. This can be useful in
227     * message-passing frameworks in which tasks are never joined.
228     * However neither mode considers affinities, loads, cache
229     * localities, etc, so rarely provide the best possible
230     * performance on a given machine, but portably provide good
231     * throughput by averaging over these factors. Further, even if
232     * we did try to use such information, we do not usually have a
233     * basis for exploiting it. For example, some sets of tasks
234     * profit from cache affinities, but others are harmed by cache
235     * pollution effects. Additionally, even though it requires
236     * scanning, long-term throughput is often best using random
237     * selection rather than directed selection policies, so cheap
238     * randomization of sufficient quality is used whenever
239     * applicable. Various Marsaglia XorShifts (some with different
240     * shift constants) are inlined at use points.
241 dl 1.78 *
242     * WorkQueues are also used in a similar way for tasks submitted
243     * to the pool. We cannot mix these tasks in the same queues used
244 dl 1.200 * by workers. Instead, we randomly associate submission queues
245 dl 1.83 * with submitting threads, using a form of hashing. The
246 dl 1.139 * ThreadLocalRandom probe value serves as a hash code for
247     * choosing existing queues, and may be randomly repositioned upon
248     * contention with other submitters. In essence, submitters act
249     * like workers except that they are restricted to executing local
250     * tasks that they submitted (or in the case of CountedCompleters,
251 dl 1.200 * others with the same root task). Insertion of tasks in shared
252 dl 1.139 * mode requires a lock (mainly to protect in the case of
253 dl 1.200 * resizing) but we use only a simple spinlock (using field
254     * qlock), because submitters encountering a busy queue move on to
255     * try or create other queues -- they block only when creating and
256 dl 1.211 * registering new queues. Additionally, "qlock" saturates to an
257     * unlockable value (-1) at shutdown. Unlocking still can be and
258     * is performed by cheaper ordered writes of "qlock" in successful
259     * cases, but uses CAS in unsuccessful cases.
260 dl 1.78 *
261 jsr166 1.84 * Management
262 dl 1.78 * ==========
263 dl 1.52 *
264     * The main throughput advantages of work-stealing stem from
265     * decentralized control -- workers mostly take tasks from
266 dl 1.200 * themselves or each other, at rates that can exceed a billion
267     * per second. The pool itself creates, activates (enables
268     * scanning for and running tasks), deactivates, blocks, and
269     * terminates threads, all with minimal central information.
270     * There are only a few properties that we can globally track or
271     * maintain, so we pack them into a small number of variables,
272     * often maintaining atomicity without blocking or locking.
273     * Nearly all essentially atomic control state is held in two
274     * volatile variables that are by far most often read (not
275 dl 1.215 * written) as status and consistency checks. (Also, field
276     * "config" holds unchanging configuration state.)
277 dl 1.78 *
278 dl 1.200 * Field "ctl" contains 64 bits holding information needed to
279     * atomically decide to add, inactivate, enqueue (on an event
280 dl 1.78 * queue), dequeue, and/or re-activate workers. To enable this
281     * packing, we restrict maximum parallelism to (1<<15)-1 (which is
282     * far in excess of normal operating range) to allow ids, counts,
283     * and their negations (used for thresholding) to fit into 16bit
284 dl 1.215 * subfields.
285     *
286     * Field "runState" holds lockable state bits (STARTED, STOP, etc)
287     * also protecting updates to the workQueues array. When used as
288     * a lock, it is normally held only for a few instructions (the
289     * only exceptions are one-time array initialization and uncommon
290     * resizing), so is nearly always available after at most a brief
291     * spin. But to be extra-cautious, after spinning, method
292     * awaitRunStateLock (called only if an initial CAS fails), uses a
293     * wait/notify mechanics on a builtin monitor to block when
294     * (rarely) needed. This would be a terrible idea for a highly
295     * contended lock, but most pools run without the lock ever
296     * contending after the spin limit, so this works fine as a more
297     * conservative alternative. Because we don't otherwise have an
298     * internal Object to use as a monitor, the "stealCounter" (an
299     * AtomicLong) is used when available (it too must be lazily
300     * initialized; see externalSubmit).
301 jsr166 1.216 *
302 dl 1.215 * Usages of "runState" vs "ctl" interact in only one case:
303     * deciding to add a worker thread (see tryAddWorker), in which
304     * case the ctl CAS is performed while the lock is held.
305 dl 1.78 *
306     * Recording WorkQueues. WorkQueues are recorded in the
307 dl 1.200 * "workQueues" array. The array is created upon first use (see
308     * externalSubmit) and expanded if necessary. Updates to the
309     * array while recording new workers and unrecording terminated
310     * ones are protected from each other by the runState lock, but
311     * the array is otherwise concurrently readable, and accessed
312     * directly. We also ensure that reads of the array reference
313     * itself never become too stale. To simplify index-based
314     * operations, the array size is always a power of two, and all
315     * readers must tolerate null slots. Worker queues are at odd
316     * indices. Shared (submission) queues are at even indices, up to
317     * a maximum of 64 slots, to limit growth even if array needs to
318     * expand to add more workers. Grouping them together in this way
319     * simplifies and speeds up task scanning.
320 dl 1.86 *
321     * All worker thread creation is on-demand, triggered by task
322     * submissions, replacement of terminated workers, and/or
323 dl 1.78 * compensation for blocked workers. However, all other support
324     * code is set up to work with other policies. To ensure that we
325 dl 1.200 * do not hold on to worker references that would prevent GC, All
326 dl 1.78 * accesses to workQueues are via indices into the workQueues
327     * array (which is one source of some of the messy code
328     * constructions here). In essence, the workQueues array serves as
329 dl 1.200 * a weak reference mechanism. Thus for example the stack top
330     * subfield of ctl stores indices, not references.
331     *
332     * Queuing Idle Workers. Unlike HPC work-stealing frameworks, we
333     * cannot let workers spin indefinitely scanning for tasks when
334     * none can be found immediately, and we cannot start/resume
335     * workers unless there appear to be tasks available. On the
336     * other hand, we must quickly prod them into action when new
337     * tasks are submitted or generated. In many usages, ramp-up time
338     * to activate workers is the main limiting factor in overall
339     * performance, which is compounded at program start-up by JIT
340     * compilation and allocation. So we streamline this as much as
341     * possible.
342     *
343     * The "ctl" field atomically maintains active and total worker
344     * counts as well as a queue to place waiting threads so they can
345     * be located for signalling. Active counts also play the role of
346     * quiescence indicators, so are decremented when workers believe
347     * that there are no more tasks to execute. The "queue" is
348     * actually a form of Treiber stack. A stack is ideal for
349     * activating threads in most-recently used order. This improves
350     * performance and locality, outweighing the disadvantages of
351     * being prone to contention and inability to release a worker
352     * unless it is topmost on stack. We park/unpark workers after
353     * pushing on the idle worker stack (represented by the lower
354     * 32bit subfield of ctl) when they cannot find work. The top
355     * stack state holds the value of the "scanState" field of the
356     * worker: its index and status, plus a version counter that, in
357     * addition to the count subfields (also serving as version
358     * stamps) provide protection against Treiber stack ABA effects.
359     *
360     * Field scanState is used by both workers and the pool to manage
361     * and track whether a worker is INACTIVE (possibly blocked
362     * waiting for a signal), or SCANNING for tasks (when neither hold
363     * it is busy running tasks). When a worker is inactivated, its
364     * scanState field is set, and is prevented from executing tasks,
365     * even though it must scan once for them to avoid queuing
366     * races. Note that scanState updates lag queue CAS releases so
367     * usage requires care. When queued, the lower 16 bits of
368     * scanState must hold its pool index. So we place the index there
369     * upon initialization (see registerWorker) and otherwise keep it
370     * there or restore it when necessary.
371     *
372     * Memory ordering. See "Correct and Efficient Work-Stealing for
373     * Weak Memory Models" by Le, Pop, Cohen, and Nardelli, PPoPP 2013
374     * (http://www.di.ens.fr/~zappa/readings/ppopp13.pdf) for an
375     * analysis of memory ordering requirements in work-stealing
376     * algorithms similar to the one used here. We usually need
377     * stronger than minimal ordering because we must sometimes signal
378     * workers, requiring Dekker-like full-fences to avoid lost
379     * signals. Arranging for enough ordering without expensive
380     * over-fencing requires tradeoffs among the supported means of
381     * expressing access constraints. The most central operations,
382     * taking from queues and updating ctl state, require full-fence
383     * CAS. Array slots are read using the emulation of volatiles
384     * provided by Unsafe. Access from other threads to WorkQueue
385     * base, top, and array requires a volatile load of the first of
386     * any of these read. We use the convention of declaring the
387     * "base" index volatile, and always read it before other fields.
388     * The owner thread must ensure ordered updates, so writes use
389     * ordered intrinsics unless they can piggyback on those for other
390     * writes. Similar conventions and rationales hold for other
391     * WorkQueue fields (such as "currentSteal") that are only written
392     * by owners but observed by others.
393     *
394     * Creating workers. To create a worker, we pre-increment total
395     * count (serving as a reservation), and attempt to construct a
396     * ForkJoinWorkerThread via its factory. Upon construction, the
397     * new thread invokes registerWorker, where it constructs a
398     * WorkQueue and is assigned an index in the workQueues array
399     * (expanding the array if necessary). The thread is then
400     * started. Upon any exception across these steps, or null return
401     * from factory, deregisterWorker adjusts counts and records
402     * accordingly. If a null return, the pool continues running with
403     * fewer than the target number workers. If exceptional, the
404     * exception is propagated, generally to some external caller.
405     * Worker index assignment avoids the bias in scanning that would
406     * occur if entries were sequentially packed starting at the front
407     * of the workQueues array. We treat the array as a simple
408     * power-of-two hash table, expanding as needed. The seedIndex
409     * increment ensures no collisions until a resize is needed or a
410     * worker is deregistered and replaced, and thereafter keeps
411 jsr166 1.202 * probability of collision low. We cannot use
412 dl 1.200 * ThreadLocalRandom.getProbe() for similar purposes here because
413     * the thread has not started yet, but do so for creating
414     * submission queues for existing external threads.
415     *
416 jsr166 1.202 * Deactivation and waiting. Queuing encounters several intrinsic
417 dl 1.200 * races; most notably that a task-producing thread can miss
418     * seeing (and signalling) another thread that gave up looking for
419     * work but has not yet entered the wait queue. When a worker
420     * cannot find a task to steal, it deactivates and enqueues. Very
421     * often, the lack of tasks is transient due to GC or OS
422     * scheduling. To reduce false-alarm deactivation, scanners
423 dl 1.211 * compute checksums of queue states during sweeps. (The
424 jsr166 1.212 * stability checks used here and elsewhere are probabilistic
425 dl 1.211 * variants of snapshot techniques -- see Herlihy & Shavit.)
426     * Workers give up and try to deactivate only after the sum is
427     * stable across scans. Further, to avoid missed signals, they
428     * repeat this scanning process after successful enqueuing until
429     * again stable. In this state, the worker cannot take/run a task
430     * it sees until it is released from the queue, so the worker
431     * itself eventually tries to release itself or any successor (see
432     * tryRelease). Otherwise, upon an empty scan, a deactivated
433     * worker uses an adaptive local spin construction (see awaitWork)
434     * before blocking (via park). Note the unusual conventions about
435 dl 1.200 * Thread.interrupts surrounding parking and other blocking:
436     * Because interrupts are used solely to alert threads to check
437     * termination, which is checked anyway upon blocking, we clear
438     * status (using Thread.interrupted) before any call to park, so
439     * that park does not immediately return due to status being set
440     * via some other unrelated call to interrupt in user code.
441     *
442     * Signalling and activation. Workers are created or activated
443     * only when there appears to be at least one task they might be
444     * able to find and execute. Upon push (either by a worker or an
445 dl 1.205 * external submission) to a previously (possibly) empty queue,
446     * workers are signalled if idle, or created if fewer exist than
447     * the given parallelism level. These primary signals are
448     * buttressed by others whenever other threads remove a task from
449     * a queue and notice that there are other tasks there as well.
450     * On most platforms, signalling (unpark) overhead time is
451     * noticeably long, and the time between signalling a thread and
452     * it actually making progress can be very noticeably long, so it
453     * is worth offloading these delays from critical paths as much as
454 dl 1.211 * possible. Also, because inactive workers are often rescanning
455 dl 1.200 * or spinning rather than blocking, we set and clear the "parker"
456     * field of WorkQueues to reduce unnecessary calls to unpark.
457     * (This requires a secondary recheck to avoid missed signals.)
458 dl 1.52 *
459     * Trimming workers. To release resources after periods of lack of
460     * use, a worker starting to wait when the pool is quiescent will
461 dl 1.208 * time out and terminate (see awaitWork) if the pool has remained
462     * quiescent for period IDLE_TIMEOUT, increasing the period as the
463     * number of threads decreases, eventually removing all workers.
464     * Also, when more than two spare threads exist, excess threads
465     * are immediately terminated at the next quiescent point.
466 dl 1.211 * (Padding by two avoids hysteresis.)
467 dl 1.52 *
468 dl 1.210 * Shutdown and Termination. A call to shutdownNow invokes
469     * tryTerminate to atomically set a runState bit. The calling
470     * thread, as well as every other worker thereafter terminating,
471     * helps terminate others by setting their (qlock) status,
472     * cancelling their unprocessed tasks, and waking them up, doing
473     * so repeatedly until stable (but with a loop bounded by the
474     * number of workers). Calls to non-abrupt shutdown() preface
475     * this by checking whether termination should commence. This
476     * relies primarily on the active count bits of "ctl" maintaining
477 jsr166 1.212 * consensus -- tryTerminate is called from awaitWork whenever
478 dl 1.211 * quiescent. However, external submitters do not take part in
479     * this consensus. So, tryTerminate sweeps through queues (until
480     * stable) to ensure lack of in-flight submissions and workers
481 dl 1.210 * about to process them before triggering the "STOP" phase of
482 dl 1.211 * termination. (Note: there is an intrinsic conflict if
483     * helpQuiescePool is called when shutdown is enabled. Both wait
484 jsr166 1.212 * for quiescence, but tryTerminate is biased to not trigger until
485 dl 1.211 * helpQuiescePool completes.)
486     *
487 dl 1.78 *
488 jsr166 1.84 * Joining Tasks
489     * =============
490 dl 1.78 *
491     * Any of several actions may be taken when one worker is waiting
492 jsr166 1.84 * to join a task stolen (or always held) by another. Because we
493 dl 1.78 * are multiplexing many tasks on to a pool of workers, we can't
494     * just let them block (as in Thread.join). We also cannot just
495     * reassign the joiner's run-time stack with another and replace
496     * it later, which would be a form of "continuation", that even if
497 dl 1.200 * possible is not necessarily a good idea since we may need both
498     * an unblocked task and its continuation to progress. Instead we
499     * combine two tactics:
500 dl 1.19 *
501     * Helping: Arranging for the joiner to execute some task that it
502 dl 1.78 * would be running if the steal had not occurred.
503 dl 1.19 *
504     * Compensating: Unless there are already enough live threads,
505 dl 1.78 * method tryCompensate() may create or re-activate a spare
506     * thread to compensate for blocked joiners until they unblock.
507     *
508 dl 1.105 * A third form (implemented in tryRemoveAndExec) amounts to
509     * helping a hypothetical compensator: If we can readily tell that
510     * a possible action of a compensator is to steal and execute the
511     * task being joined, the joining thread can do so directly,
512     * without the need for a compensation thread (although at the
513     * expense of larger run-time stacks, but the tradeoff is
514     * typically worthwhile).
515 dl 1.52 *
516     * The ManagedBlocker extension API can't use helping so relies
517     * only on compensation in method awaitBlocker.
518 dl 1.19 *
519 dl 1.200 * The algorithm in helpStealer entails a form of "linear
520     * helping". Each worker records (in field currentSteal) the most
521     * recent task it stole from some other worker (or a submission).
522     * It also records (in field currentJoin) the task it is currently
523     * actively joining. Method helpStealer uses these markers to try
524     * to find a worker to help (i.e., steal back a task from and
525     * execute it) that could hasten completion of the actively joined
526     * task. Thus, the joiner executes a task that would be on its
527     * own local deque had the to-be-joined task not been stolen. This
528     * is a conservative variant of the approach described in Wagner &
529 dl 1.78 * Calder "Leapfrogging: a portable technique for implementing
530     * efficient futures" SIGPLAN Notices, 1993
531     * (http://portal.acm.org/citation.cfm?id=155354). It differs in
532     * that: (1) We only maintain dependency links across workers upon
533     * steals, rather than use per-task bookkeeping. This sometimes
534 dl 1.90 * requires a linear scan of workQueues array to locate stealers,
535     * but often doesn't because stealers leave hints (that may become
536 dl 1.112 * stale/wrong) of where to locate them. It is only a hint
537     * because a worker might have had multiple steals and the hint
538     * records only one of them (usually the most current). Hinting
539     * isolates cost to when it is needed, rather than adding to
540     * per-task overhead. (2) It is "shallow", ignoring nesting and
541     * potentially cyclic mutual steals. (3) It is intentionally
542 dl 1.78 * racy: field currentJoin is updated only while actively joining,
543     * which means that we miss links in the chain during long-lived
544     * tasks, GC stalls etc (which is OK since blocking in such cases
545     * is usually a good idea). (4) We bound the number of attempts
546 dl 1.200 * to find work using checksums and fall back to suspending the
547 dl 1.90 * worker and if necessary replacing it with another.
548 dl 1.78 *
549 dl 1.200 * Helping actions for CountedCompleters do not require tracking
550     * currentJoins: Method helpComplete takes and executes any task
551 jsr166 1.202 * with the same root as the task being waited on (preferring
552     * local pops to non-local polls). However, this still entails
553     * some traversal of completer chains, so is less efficient than
554     * using CountedCompleters without explicit joins.
555 dl 1.105 *
556 dl 1.200 * Compensation does not aim to keep exactly the target
557     * parallelism number of unblocked threads running at any given
558     * time. Some previous versions of this class employed immediate
559     * compensations for any blocked join. However, in practice, the
560     * vast majority of blockages are transient byproducts of GC and
561     * other JVM or OS activities that are made worse by replacement.
562     * Currently, compensation is attempted only after validating that
563     * all purportedly active threads are processing tasks by checking
564     * field WorkQueue.scanState, which eliminates most false
565     * positives. Also, compensation is bypassed (tolerating fewer
566     * threads) in the most common case in which it is rarely
567     * beneficial: when a worker with an empty queue (thus no
568     * continuation tasks) blocks on a join and there still remain
569 dl 1.208 * enough threads to ensure liveness.
570 dl 1.105 *
571 dl 1.211 * The compensation mechanism may be bounded. Bounds for the
572     * commonPool (see commonMaxSpares) better enable JVMs to cope
573 dl 1.208 * with programming errors and abuse before running out of
574     * resources to do so. In other cases, users may supply factories
575     * that limit thread construction. The effects of bounding in this
576     * pool (like all others) is imprecise. Total worker counts are
577     * decremented when threads deregister, not when they exit and
578     * resources are reclaimed by the JVM and OS. So the number of
579     * simultaneously live threads may transiently exceed bounds.
580 dl 1.205 *
581 dl 1.105 * Common Pool
582     * ===========
583     *
584 jsr166 1.175 * The static common pool always exists after static
585 dl 1.105 * initialization. Since it (or any other created pool) need
586     * never be used, we minimize initial construction overhead and
587     * footprint to the setup of about a dozen fields, with no nested
588     * allocation. Most bootstrapping occurs within method
589 dl 1.200 * externalSubmit during the first submission to the pool.
590 dl 1.105 *
591     * When external threads submit to the common pool, they can
592 dl 1.200 * perform subtask processing (see externalHelpComplete and
593     * related methods) upon joins. This caller-helps policy makes it
594     * sensible to set common pool parallelism level to one (or more)
595     * less than the total number of available cores, or even zero for
596     * pure caller-runs. We do not need to record whether external
597     * submissions are to the common pool -- if not, external help
598     * methods return quickly. These submitters would otherwise be
599     * blocked waiting for completion, so the extra effort (with
600     * liberally sprinkled task status checks) in inapplicable cases
601     * amounts to an odd form of limited spin-wait before blocking in
602     * ForkJoinTask.join.
603 dl 1.105 *
604 dl 1.197 * As a more appropriate default in managed environments, unless
605     * overridden by system properties, we use workers of subclass
606     * InnocuousForkJoinWorkerThread when there is a SecurityManager
607     * present. These workers have no permissions set, do not belong
608     * to any user-defined ThreadGroup, and erase all ThreadLocals
609 dl 1.200 * after executing any top-level task (see WorkQueue.runTask).
610     * The associated mechanics (mainly in ForkJoinWorkerThread) may
611     * be JVM-dependent and must access particular Thread class fields
612     * to achieve this effect.
613 jsr166 1.198 *
614 dl 1.105 * Style notes
615     * ===========
616     *
617 dl 1.200 * Memory ordering relies mainly on Unsafe intrinsics that carry
618     * the further responsibility of explicitly performing null- and
619     * bounds- checks otherwise carried out implicitly by JVMs. This
620     * can be awkward and ugly, but also reflects the need to control
621     * outcomes across the unusual cases that arise in very racy code
622     * with very few invariants. So these explicit checks would exist
623     * in some form anyway. All fields are read into locals before
624     * use, and null-checked if they are references. This is usually
625     * done in a "C"-like style of listing declarations at the heads
626     * of methods or blocks, and using inline assignments on first
627     * encounter. Array bounds-checks are usually performed by
628     * masking with array.length-1, which relies on the invariant that
629     * these arrays are created with positive lengths, which is itself
630     * paranoically checked. Nearly all explicit checks lead to
631     * bypass/return, not exception throws, because they may
632     * legitimately arise due to cancellation/revocation during
633     * shutdown.
634     *
635 dl 1.105 * There is a lot of representation-level coupling among classes
636     * ForkJoinPool, ForkJoinWorkerThread, and ForkJoinTask. The
637     * fields of WorkQueue maintain data structures managed by
638     * ForkJoinPool, so are directly accessed. There is little point
639     * trying to reduce this, since any associated future changes in
640     * representations will need to be accompanied by algorithmic
641     * changes anyway. Several methods intrinsically sprawl because
642 dl 1.200 * they must accumulate sets of consistent reads of fields held in
643     * local variables. There are also other coding oddities
644     * (including several unnecessary-looking hoisted null checks)
645     * that help some methods perform reasonably even when interpreted
646     * (not compiled).
647 dl 1.52 *
648 dl 1.208 * The order of declarations in this file is (with a few exceptions):
649 dl 1.86 * (1) Static utility functions
650     * (2) Nested (static) classes
651     * (3) Static fields
652     * (4) Fields, along with constants used when unpacking some of them
653     * (5) Internal control methods
654     * (6) Callbacks and other support for ForkJoinTask methods
655     * (7) Exported methods
656     * (8) Static block initializing statics in minimally dependent order
657     */
658    
659     // Static utilities
660    
661     /**
662     * If there is a security manager, makes sure caller has
663     * permission to modify threads.
664 jsr166 1.1 */
665 dl 1.86 private static void checkPermission() {
666     SecurityManager security = System.getSecurityManager();
667     if (security != null)
668     security.checkPermission(modifyThreadPermission);
669     }
670    
671     // Nested classes
672 jsr166 1.1
673     /**
674 jsr166 1.8 * Factory for creating new {@link ForkJoinWorkerThread}s.
675     * A {@code ForkJoinWorkerThreadFactory} must be defined and used
676     * for {@code ForkJoinWorkerThread} subclasses that extend base
677     * functionality or initialize threads with different contexts.
678 jsr166 1.1 */
679     public static interface ForkJoinWorkerThreadFactory {
680     /**
681     * Returns a new worker thread operating in the given pool.
682     *
683     * @param pool the pool this thread works in
684 jsr166 1.192 * @return the new worker thread
685 jsr166 1.11 * @throws NullPointerException if the pool is null
686 jsr166 1.1 */
687     public ForkJoinWorkerThread newThread(ForkJoinPool pool);
688     }
689    
690     /**
691     * Default ForkJoinWorkerThreadFactory implementation; creates a
692     * new ForkJoinWorkerThread.
693     */
694 dl 1.112 static final class DefaultForkJoinWorkerThreadFactory
695 jsr166 1.1 implements ForkJoinWorkerThreadFactory {
696 dl 1.112 public final ForkJoinWorkerThread newThread(ForkJoinPool pool) {
697 dl 1.14 return new ForkJoinWorkerThread(pool);
698 jsr166 1.1 }
699     }
700    
701     /**
702 dl 1.86 * Class for artificial tasks that are used to replace the target
703     * of local joins if they are removed from an interior queue slot
704     * in WorkQueue.tryRemoveAndExec. We don't need the proxy to
705     * actually do anything beyond having a unique identity.
706 jsr166 1.1 */
707 dl 1.86 static final class EmptyTask extends ForkJoinTask<Void> {
708 dl 1.105 private static final long serialVersionUID = -7721805057305804111L;
709 dl 1.86 EmptyTask() { status = ForkJoinTask.NORMAL; } // force done
710     public final Void getRawResult() { return null; }
711     public final void setRawResult(Void x) {}
712     public final boolean exec() { return true; }
713 jsr166 1.1 }
714    
715 dl 1.200 // Constants shared across ForkJoinPool and WorkQueue
716    
717     // Bounds
718     static final int SMASK = 0xffff; // short bits == max index
719     static final int MAX_CAP = 0x7fff; // max #workers - 1
720     static final int EVENMASK = 0xfffe; // even short bits
721     static final int SQMASK = 0x007e; // max 64 (even) slots
722    
723     // Masks and units for WorkQueue.scanState and ctl sp subfield
724     static final int SCANNING = 1; // false when running tasks
725     static final int INACTIVE = 1 << 31; // must be negative
726 dl 1.211 static final int SS_SEQ = 1 << 16; // version count
727 dl 1.200
728     // Mode bits for ForkJoinPool.config and WorkQueue.config
729 dl 1.211 static final int MODE_MASK = 0xffff << 16; // top half of int
730 dl 1.200 static final int LIFO_QUEUE = 0;
731     static final int FIFO_QUEUE = 1 << 16;
732     static final int SHARED_QUEUE = 1 << 31; // must be negative
733    
734 dl 1.225 // This version uses array access methods in anticipation of JDK9 support
735     // that should eliminate their need
736    
737     static final ForkJoinTask<?> getAt(ForkJoinTask<?>[] a, int i) {
738     return (ForkJoinTask<?>)U.getObjectVolatile(
739     a, (long)((i << ASHIFT) + ABASE));
740     }
741    
742     static final void setAt(ForkJoinTask<?>[] a, int i, ForkJoinTask<?> x) {
743     U.putOrderedObject(a, (long)((i << ASHIFT) + ABASE), x);
744     }
745    
746     static final boolean casAt(ForkJoinTask<?>[] a, int i,
747     ForkJoinTask<?> c, ForkJoinTask<?> v) {
748     return U.compareAndSwapObject(
749     a, (long)((i << ASHIFT) + ABASE), c, v);
750     }
751    
752     static final ForkJoinTask<?> xchgAt(ForkJoinTask<?>[] a, int i,
753     ForkJoinTask<?> x) {
754     return (ForkJoinTask<?>)U.getAndSetObject(
755     a, (long)((i << ASHIFT) + ABASE), x);
756     }
757    
758 jsr166 1.1 /**
759 dl 1.78 * Queues supporting work-stealing as well as external task
760 jsr166 1.202 * submission. See above for descriptions and algorithms.
761 dl 1.78 * Performance on most platforms is very sensitive to placement of
762     * instances of both WorkQueues and their arrays -- we absolutely
763     * do not want multiple WorkQueue instances or multiple queue
764 dl 1.200 * arrays sharing cache lines. The @Contended annotation alerts
765     * JVMs to try to keep instances apart.
766 dl 1.78 */
767 jsr166 1.171 @sun.misc.Contended
768 dl 1.78 static final class WorkQueue {
769 dl 1.200
770 dl 1.78 /**
771     * Capacity of work-stealing queue array upon initialization.
772 dl 1.90 * Must be a power of two; at least 4, but should be larger to
773     * reduce or eliminate cacheline sharing among queues.
774     * Currently, it is much larger, as a partial workaround for
775     * the fact that JVMs often place arrays in locations that
776     * share GC bookkeeping (especially cardmarks) such that
777     * per-write accesses encounter serious memory contention.
778 dl 1.78 */
779 dl 1.90 static final int INITIAL_QUEUE_CAPACITY = 1 << 13;
780 dl 1.78
781     /**
782     * Maximum size for queue arrays. Must be a power of two less
783     * than or equal to 1 << (31 - width of array entry) to ensure
784     * lack of wraparound of index calculations, but defined to a
785     * value a bit less than this to help users trap runaway
786     * programs before saturating systems.
787     */
788     static final int MAXIMUM_QUEUE_CAPACITY = 1 << 26; // 64M
789    
790 dl 1.200 // Instance fields
791     volatile int scanState; // versioned, <0: inactive; odd:scanning
792     int stackPred; // pool stack (ctl) predecessor
793 dl 1.178 int nsteals; // number of steals
794 dl 1.200 int hint; // randomization and stealer index hint
795     int config; // pool index and mode
796     volatile int qlock; // 1: locked, < 0: terminate; else 0
797 dl 1.78 volatile int base; // index of next slot for poll
798     int top; // index of next slot for push
799     ForkJoinTask<?>[] array; // the elements (initially unallocated)
800 dl 1.90 final ForkJoinPool pool; // the containing pool (may be null)
801 dl 1.78 final ForkJoinWorkerThread owner; // owning thread or null if shared
802     volatile Thread parker; // == owner during call to park; else null
803 dl 1.95 volatile ForkJoinTask<?> currentJoin; // task being joined in awaitJoin
804 dl 1.200 volatile ForkJoinTask<?> currentSteal; // mainly used by helpStealer
805 dl 1.112
806 dl 1.225 // Temporary repeats of array access methods
807    
808     static final ForkJoinTask<?> getAt(ForkJoinTask<?>[] a, int i) {
809     return (ForkJoinTask<?>)U.getObjectVolatile(
810     a, (long)((i << ASHIFT) + ABASE));
811     }
812    
813     static final void setAt(ForkJoinTask<?>[] a, int i, ForkJoinTask<?> x) {
814     U.putOrderedObject(a, (long)((i << ASHIFT) + ABASE), x);
815     }
816    
817     static final boolean casAt(ForkJoinTask<?>[] a, int i,
818     ForkJoinTask<?> c, ForkJoinTask<?> v) {
819     return U.compareAndSwapObject(
820     a, (long)((i << ASHIFT) + ABASE), c, v);
821     }
822    
823     static final ForkJoinTask<?> xchgAt(ForkJoinTask<?>[] a, int i,
824     ForkJoinTask<?> x) {
825     return (ForkJoinTask<?>)U.getAndSetObject(
826     a, (long)((i << ASHIFT) + ABASE), x);
827     }
828    
829 dl 1.200 WorkQueue(ForkJoinPool pool, ForkJoinWorkerThread owner) {
830 dl 1.90 this.pool = pool;
831 dl 1.78 this.owner = owner;
832 dl 1.115 // Place indices in the center of array (that is not yet allocated)
833 dl 1.78 base = top = INITIAL_QUEUE_CAPACITY >>> 1;
834     }
835    
836     /**
837 jsr166 1.220 * Returns an exportable index (used by ForkJoinWorkerThread).
838 dl 1.200 */
839     final int getPoolIndex() {
840     return (config & 0xffff) >>> 1; // ignore odd/even tag bit
841     }
842    
843     /**
844 dl 1.115 * Returns the approximate number of tasks in the queue.
845     */
846     final int queueSize() {
847     int n = base - top; // non-owner callers must read base first
848     return (n >= 0) ? 0 : -n; // ignore transient negative
849     }
850    
851 jsr166 1.180 /**
852 dl 1.115 * Provides a more accurate estimate of whether this queue has
853     * any tasks than does queueSize, by checking whether a
854     * near-empty queue has at least one unclaimed task.
855     */
856     final boolean isEmpty() {
857 dl 1.225 ForkJoinTask<?>[] a; int n, al, s;
858 dl 1.200 return ((n = base - (s = top)) >= 0 ||
859     (n == -1 && // possibly one task
860 dl 1.225 ((a = array) == null || (al = a.length) == 0 ||
861     getAt(a, (al - 1) & (s - 1)) == null)));
862 dl 1.115 }
863    
864     /**
865     * Pushes a task. Call only by owner in unshared queues. (The
866     * shared-queue version is embedded in method externalPush.)
867 dl 1.78 *
868     * @param task the task. Caller must ensure non-null.
869 jsr166 1.146 * @throws RejectedExecutionException if array cannot be resized
870 dl 1.78 */
871 dl 1.90 final void push(ForkJoinTask<?> task) {
872 dl 1.205 ForkJoinTask<?>[] a; ForkJoinPool p;
873 dl 1.225 if ((a = array) != null) { // ignore if queue removed
874 dl 1.224 int b = base, m = a.length - 1, s = top, n;
875 dl 1.225 if (m > 0) { // always true, but check required
876     setAt(a, m & s, task);
877 dl 1.224 U.putOrderedInt(this, QTOP, s + 1);
878     if ((n = s - b) <= 1) {
879     if ((p = pool) != null)
880     p.signalWork(p.workQueues, this);
881     }
882     else if (n >= m)
883     growArray();
884 dl 1.200 }
885 dl 1.78 }
886     }
887    
888 dl 1.178 /**
889 dl 1.112 * Initializes or doubles the capacity of array. Call either
890     * by owner or with lock held -- it is OK for base, but not
891     * top, to move while resizings are in progress.
892     */
893     final ForkJoinTask<?>[] growArray() {
894     ForkJoinTask<?>[] oldA = array;
895     int size = oldA != null ? oldA.length << 1 : INITIAL_QUEUE_CAPACITY;
896 dl 1.225 if (size < INITIAL_QUEUE_CAPACITY || size > MAXIMUM_QUEUE_CAPACITY)
897 dl 1.112 throw new RejectedExecutionException("Queue capacity exceeded");
898     int oldMask, t, b;
899     ForkJoinTask<?>[] a = array = new ForkJoinTask<?>[size];
900 dl 1.225 if (oldA != null && (oldMask = oldA.length - 1) > 0 &&
901 dl 1.112 (t = top) - (b = base) > 0) {
902     int mask = size - 1;
903 dl 1.200 do { // emulate poll from old array, push to new array
904 dl 1.112 ForkJoinTask<?> x;
905 dl 1.225 int oldj = b & oldMask, j = b & mask;
906     if ((x = getAt(oldA, oldj)) != null &&
907     casAt(oldA, oldj, x, null))
908     setAt(a, j, x);
909 dl 1.112 } while (++b != t);
910 dl 1.78 }
911 dl 1.112 return a;
912 dl 1.78 }
913    
914     /**
915 dl 1.90 * Takes next task, if one exists, in LIFO order. Call only
916 dl 1.102 * by owner in unshared queues.
917 dl 1.90 */
918     final ForkJoinTask<?> pop() {
919 dl 1.225 ForkJoinTask<?>[] a; ForkJoinTask<?> t; int al;
920     if ((a = array) != null && (al = a.length) > 0) {
921 dl 1.90 for (int s; (s = top - 1) - base >= 0;) {
922 dl 1.225 int j = (al - 1) & s;
923     if ((t = getAt(a, j)) == null)
924 dl 1.90 break;
925 dl 1.225 if (casAt(a, j, t, null)) {
926 dl 1.200 U.putOrderedInt(this, QTOP, s);
927 dl 1.90 return t;
928     }
929     }
930     }
931     return null;
932     }
933    
934     /**
935     * Takes a task in FIFO order if b is base of queue and a task
936     * can be claimed without contention. Specialized versions
937 dl 1.200 * appear in ForkJoinPool methods scan and helpStealer.
938 dl 1.78 */
939 dl 1.90 final ForkJoinTask<?> pollAt(int b) {
940 dl 1.178 ForkJoinTask<?> t; ForkJoinTask<?>[] a;
941 dl 1.90 if ((a = array) != null) {
942 dl 1.225 int al = a.length, j = (al - 1) & b;
943     if (al > 0 && (t = getAt(a, j)) != null &&
944     base == b && casAt(a, j, t, null)) {
945 dl 1.200 base = b + 1;
946 dl 1.78 return t;
947     }
948     }
949     return null;
950     }
951    
952     /**
953 dl 1.90 * Takes next task, if one exists, in FIFO order.
954 dl 1.78 */
955 dl 1.90 final ForkJoinTask<?> poll() {
956 dl 1.225 ForkJoinTask<?>[] a; int b, al, j;
957     while ((b = base) - top < 0 && (a = array) != null &&
958     (al = a.length) > 0) {
959     ForkJoinTask<?> t = getAt(a, j = (al - 1) & b);
960 dl 1.200 if (base == b) {
961     if (t != null) {
962 dl 1.225 if (casAt(a, j, t, null)) {
963 dl 1.200 base = b + 1;
964     return t;
965     }
966 dl 1.78 }
967 dl 1.200 else if (b + 1 == top) // now empty
968 dl 1.90 break;
969     }
970 dl 1.78 }
971     return null;
972     }
973    
974     /**
975     * Takes next task, if one exists, in order specified by mode.
976     */
977     final ForkJoinTask<?> nextLocalTask() {
978 dl 1.200 return (config & FIFO_QUEUE) == 0 ? pop() : poll();
979 dl 1.78 }
980    
981     /**
982     * Returns next task, if one exists, in order specified by mode.
983     */
984     final ForkJoinTask<?> peek() {
985 dl 1.225 ForkJoinTask<?>[] a = array; int al;
986     if (a != null && (al = a.length) > 0) {
987     int i = (config & FIFO_QUEUE) == 0 ? top - 1 : base;
988     return getAt(a, (al - 1) & i);
989     }
990     return null;
991 dl 1.78 }
992    
993     /**
994     * Pops the given task only if it is at the current top.
995 dl 1.105 * (A shared version is available only via FJP.tryExternalUnpush)
996 dl 1.200 */
997 dl 1.78 final boolean tryUnpush(ForkJoinTask<?> t) {
998 dl 1.224 ForkJoinTask<?>[] a;
999     if ((a = array) != null) {
1000 dl 1.225 int b = base, al = a.length, s = top;
1001     if (s != b && al > 0 &&
1002     casAt(a, (al - 1) & (s - 1), t, null)) {
1003 dl 1.224 U.putOrderedInt(this, QTOP, s - 1);
1004     return true;
1005     }
1006 dl 1.78 }
1007     return false;
1008     }
1009    
1010     /**
1011 jsr166 1.84 * Removes and cancels all known tasks, ignoring any exceptions.
1012 dl 1.78 */
1013     final void cancelAll() {
1014 dl 1.200 ForkJoinTask<?> t;
1015     if ((t = currentJoin) != null) {
1016     currentJoin = null;
1017     ForkJoinTask.cancelIgnoringExceptions(t);
1018     }
1019     if ((t = currentSteal) != null) {
1020     currentSteal = null;
1021     ForkJoinTask.cancelIgnoringExceptions(t);
1022     }
1023     while ((t = poll()) != null)
1024 dl 1.78 ForkJoinTask.cancelIgnoringExceptions(t);
1025     }
1026    
1027 dl 1.104 // Specialized execution methods
1028 dl 1.78
1029     /**
1030 dl 1.178 * Polls and runs tasks until empty.
1031 dl 1.78 */
1032 dl 1.178 final void pollAndExecAll() {
1033     for (ForkJoinTask<?> t; (t = poll()) != null;)
1034     t.doExec();
1035 dl 1.94 }
1036    
1037     /**
1038 dl 1.225 * Pops and runs tasks until empty.
1039     */
1040     final void popAndExecAll() {
1041     ForkJoinTask<?>[] a; ForkJoinTask<?> t;
1042     while ((a = array) != null) {
1043     int b = base, al = a.length, s = top, i = (al - 1) & (s - 1);
1044     if (b != s && al > 0 &&
1045     (t = xchgAt(a, i, null)) != null) {
1046     U.putOrderedInt(this, QTOP, s - 1);
1047     t.doExec();
1048 dl 1.200 }
1049     else
1050 dl 1.225 break;
1051 dl 1.200 }
1052     }
1053    
1054     /**
1055 jsr166 1.213 * Executes the given task and any remaining local tasks.
1056 dl 1.94 */
1057 dl 1.178 final void runTask(ForkJoinTask<?> task) {
1058 dl 1.200 if (task != null) {
1059     scanState &= ~SCANNING; // mark as busy
1060     (currentSteal = task).doExec();
1061     U.putOrderedObject(this, QCURRENTSTEAL, null); // release for GC
1062 dl 1.225 if ((config & FIFO_QUEUE) != 0)
1063     pollAndExecAll();
1064     else
1065     popAndExecAll();
1066 dl 1.200 ForkJoinWorkerThread thread = owner;
1067 dl 1.215 if (++nsteals < 0) // collect on overflow
1068     transferStealCount(pool);
1069 dl 1.200 scanState |= SCANNING;
1070     if (thread != null)
1071 dl 1.197 thread.afterTopLevelExec();
1072 dl 1.178 }
1073 dl 1.94 }
1074    
1075     /**
1076 dl 1.215 * Adds steal count to pool stealCounter if it exists, and resets.
1077     */
1078     final void transferStealCount(ForkJoinPool p) {
1079     AtomicLong sc;
1080     if (p != null && (sc = p.stealCounter) != null) {
1081     int s = nsteals;
1082     nsteals = 0; // if negative, correct for overflow
1083     sc.getAndAdd((long)(s < 0 ? Integer.MAX_VALUE : s));
1084     }
1085     }
1086    
1087     /**
1088 dl 1.105 * If present, removes from queue and executes the given task,
1089 jsr166 1.213 * or any other cancelled task. Used only by awaitJoin.
1090 dl 1.94 *
1091 jsr166 1.213 * @return true if queue empty and task not known to be done
1092 dl 1.94 */
1093 dl 1.105 final boolean tryRemoveAndExec(ForkJoinTask<?> task) {
1094 dl 1.225 ForkJoinTask<?>[] a; int al, s, b, n;
1095     if ((a = array) != null && (al = a.length) > 0 && task != null) {
1096 dl 1.200 while ((n = (s = top) - (b = base)) > 0) {
1097     for (ForkJoinTask<?> t;;) { // traverse from s to b
1098 dl 1.225 int j = --s & (al - 1);
1099     if ((t = getAt(a, j)) == null)
1100 dl 1.200 return s + 1 == top; // shorter than expected
1101     else if (t == task) {
1102     boolean removed = false;
1103     if (s + 1 == top) { // pop
1104 dl 1.225 if (casAt(a, j, task, null)) {
1105 dl 1.200 U.putOrderedInt(this, QTOP, s);
1106     removed = true;
1107     }
1108     }
1109     else if (base == b) // replace with proxy
1110 dl 1.225 removed = casAt(a, j, task, new EmptyTask());
1111 dl 1.200 if (removed)
1112     task.doExec();
1113     break;
1114 dl 1.90 }
1115 dl 1.200 else if (t.status < 0 && s + 1 == top) {
1116 dl 1.225 if (casAt(a, j, t, null))
1117 dl 1.200 U.putOrderedInt(this, QTOP, s);
1118     break; // was cancelled
1119 dl 1.104 }
1120 dl 1.200 if (--n == 0)
1121     return false;
1122 dl 1.104 }
1123 dl 1.200 if (task.status < 0)
1124     return false;
1125 dl 1.104 }
1126     }
1127 dl 1.200 return true;
1128 dl 1.104 }
1129    
1130     /**
1131 dl 1.200 * Pops task if in the same CC computation as the given task,
1132     * in either shared or owned mode. Used only by helpComplete.
1133 dl 1.78 */
1134 dl 1.200 final CountedCompleter<?> popCC(CountedCompleter<?> task, int mode) {
1135 dl 1.225 ForkJoinTask<?>[] a; ForkJoinTask<?> o;
1136     if ((a = array) != null) {
1137     int b = base, al = a.length, s = top, i = (al - 1) & (s - 1);
1138     if (b != s && al > 0 &&
1139     ((o = a[i]) instanceof CountedCompleter)) {
1140 dl 1.200 CountedCompleter<?> t = (CountedCompleter<?>)o;
1141     for (CountedCompleter<?> r = t;;) {
1142     if (r == task) {
1143     if (mode < 0) { // must lock
1144     if (U.compareAndSwapInt(this, QLOCK, 0, 1)) {
1145     if (top == s && array == a &&
1146 dl 1.225 casAt(a, i, t, null)) {
1147 dl 1.200 U.putOrderedInt(this, QTOP, s - 1);
1148     U.putOrderedInt(this, QLOCK, 0);
1149     return t;
1150     }
1151 dl 1.209 U.compareAndSwapInt(this, QLOCK, 1, 0);
1152 dl 1.178 }
1153     }
1154 dl 1.225 else if (casAt(a, i, t, null)) {
1155 dl 1.200 U.putOrderedInt(this, QTOP, s - 1);
1156     return t;
1157     }
1158     break;
1159 dl 1.178 }
1160 dl 1.200 else if ((r = r.completer) == null) // try parent
1161 dl 1.178 break;
1162     }
1163 dl 1.94 }
1164 dl 1.78 }
1165 dl 1.200 return null;
1166 dl 1.78 }
1167    
1168     /**
1169 dl 1.200 * Steals and runs a task in the same CC computation as the
1170     * given task if one exists and can be taken without
1171     * contention. Otherwise returns a checksum/control value for
1172     * use by method helpComplete.
1173     *
1174     * @return 1 if successful, 2 if retryable (lost to another
1175     * stealer), -1 if non-empty but no matching task found, else
1176     * the base index, forced negative.
1177     */
1178     final int pollAndExecCC(CountedCompleter<?> task) {
1179 dl 1.225 int b, h, j, al; ForkJoinTask<?>[] a; Object o;
1180     if ((b = base) - top >= 0 || (a = array) == null ||
1181     (al = a.length) <= 0)
1182 dl 1.200 h = b | Integer.MIN_VALUE; // to sense movement on re-poll
1183 dl 1.225 else if ((o = getAt(a, j = (al - 1) & b)) == null)
1184     h = 2; // retryable
1185     else if (!(o instanceof CountedCompleter))
1186     h = -1; // unmatchable
1187 dl 1.200 else {
1188 dl 1.225 CountedCompleter<?> t = (CountedCompleter<?>)o;
1189     for (CountedCompleter<?> r = t;;) {
1190     if (r == task) {
1191     if (base == b && casAt(a, j, t, null)) {
1192     base = b + 1;
1193     t.doExec();
1194     h = 1; // success
1195 dl 1.200 }
1196 dl 1.225 else
1197     h = 2; // lost CAS
1198     break;
1199     }
1200     else if ((r = r.completer) == null) {
1201     h = -1; // unmatched
1202     break;
1203 dl 1.178 }
1204     }
1205 dl 1.78 }
1206 dl 1.200 return h;
1207 dl 1.78 }
1208    
1209     /**
1210 dl 1.86 * Returns true if owned and not known to be blocked.
1211     */
1212     final boolean isApparentlyUnblocked() {
1213     Thread wt; Thread.State s;
1214 dl 1.200 return (scanState >= 0 &&
1215 dl 1.86 (wt = owner) != null &&
1216     (s = wt.getState()) != Thread.State.BLOCKED &&
1217     s != Thread.State.WAITING &&
1218     s != Thread.State.TIMED_WAITING);
1219     }
1220    
1221 dl 1.211 // Unsafe mechanics. Note that some are (and must be) the same as in FJP
1222 jsr166 1.233 private static final sun.misc.Unsafe U = sun.misc.Unsafe.getUnsafe();
1223 dl 1.200 private static final int ABASE;
1224     private static final int ASHIFT;
1225     private static final long QTOP;
1226 dl 1.105 private static final long QLOCK;
1227 dl 1.200 private static final long QCURRENTSTEAL;
1228 dl 1.78 static {
1229     try {
1230 dl 1.200 QTOP = U.objectFieldOffset
1231 jsr166 1.233 (WorkQueue.class.getDeclaredField("top"));
1232 dl 1.105 QLOCK = U.objectFieldOffset
1233 jsr166 1.233 (WorkQueue.class.getDeclaredField("qlock"));
1234 dl 1.200 QCURRENTSTEAL = U.objectFieldOffset
1235 jsr166 1.233 (WorkQueue.class.getDeclaredField("currentSteal"));
1236    
1237     ABASE = U.arrayBaseOffset(ForkJoinTask[].class);
1238     int scale = U.arrayIndexScale(ForkJoinTask[].class);
1239 jsr166 1.142 if ((scale & (scale - 1)) != 0)
1240 jsr166 1.232 throw new Error("array index scale not a power of two");
1241 jsr166 1.142 ASHIFT = 31 - Integer.numberOfLeadingZeros(scale);
1242 jsr166 1.231 } catch (ReflectiveOperationException e) {
1243 dl 1.78 throw new Error(e);
1244     }
1245     }
1246     }
1247 dl 1.14
1248 dl 1.112 // static fields (initialized in static initializer below)
1249    
1250     /**
1251     * Creates a new ForkJoinWorkerThread. This factory is used unless
1252     * overridden in ForkJoinPool constructors.
1253     */
1254     public static final ForkJoinWorkerThreadFactory
1255     defaultForkJoinWorkerThreadFactory;
1256    
1257 jsr166 1.1 /**
1258 dl 1.115 * Permission required for callers of methods that may start or
1259     * kill threads.
1260     */
1261     private static final RuntimePermission modifyThreadPermission;
1262    
1263     /**
1264 dl 1.101 * Common (static) pool. Non-null for public use unless a static
1265 dl 1.105 * construction exception, but internal usages null-check on use
1266     * to paranoically avoid potential initialization circularities
1267     * as well as to simplify generated code.
1268 dl 1.101 */
1269 dl 1.134 static final ForkJoinPool common;
1270 dl 1.101
1271     /**
1272 dl 1.160 * Common pool parallelism. To allow simpler use and management
1273     * when common pool threads are disabled, we allow the underlying
1274 dl 1.185 * common.parallelism field to be zero, but in that case still report
1275 dl 1.160 * parallelism as 1 to reflect resulting caller-runs mechanics.
1276 dl 1.90 */
1277 dl 1.134 static final int commonParallelism;
1278 dl 1.90
1279     /**
1280 dl 1.208 * Limit on spare thread construction in tryCompensate.
1281     */
1282     private static int commonMaxSpares;
1283    
1284     /**
1285 dl 1.105 * Sequence number for creating workerNamePrefix.
1286 dl 1.86 */
1287 dl 1.105 private static int poolNumberSequence;
1288 dl 1.86
1289 jsr166 1.1 /**
1290 jsr166 1.132 * Returns the next sequence number. We don't expect this to
1291     * ever contend, so use simple builtin sync.
1292 dl 1.83 */
1293 dl 1.105 private static final synchronized int nextPoolId() {
1294     return ++poolNumberSequence;
1295     }
1296 dl 1.86
1297 dl 1.200 // static configuration constants
1298 dl 1.86
1299     /**
1300 dl 1.105 * Initial timeout value (in nanoseconds) for the thread
1301     * triggering quiescence to park waiting for new work. On timeout,
1302     * the thread will instead try to shrink the number of
1303     * workers. The value should be large enough to avoid overly
1304     * aggressive shrinkage during most transient stalls (long GCs
1305     * etc).
1306 dl 1.86 */
1307 dl 1.208 private static final long IDLE_TIMEOUT = 2000L * 1000L * 1000L; // 2sec
1308 dl 1.86
1309     /**
1310 dl 1.120 * Tolerance for idle timeouts, to cope with timer undershoots
1311     */
1312 dl 1.208 private static final long TIMEOUT_SLOP = 20L * 1000L * 1000L; // 20ms
1313 dl 1.200
1314     /**
1315 dl 1.208 * The initial value for commonMaxSpares during static
1316     * initialization unless overridden using System property
1317     * "java.util.concurrent.ForkJoinPool.common.maximumSpares". The
1318     * default value is far in excess of normal requirements, but also
1319 dl 1.200 * far short of MAX_CAP and typical OS thread limits, so allows
1320     * JVMs to catch misuse/abuse before running out of resources
1321     * needed to do so.
1322     */
1323 dl 1.208 private static final int DEFAULT_COMMON_MAX_SPARES = 256;
1324 dl 1.120
1325     /**
1326 dl 1.200 * Number of times to spin-wait before blocking. The spins (in
1327     * awaitRunStateLock and awaitWork) currently use randomized
1328     * spins. If/when MWAIT-like intrinsics becomes available, they
1329     * may allow quieter spinning. The value of SPINS must be a power
1330     * of two, at least 4. The current value causes spinning for a
1331 dl 1.211 * small fraction of typical context-switch times, well worthwhile
1332     * given the typical likelihoods that blocking is not necessary.
1333 dl 1.90 */
1334 jsr166 1.230 private static final int SPINS = 1 << 11;
1335 dl 1.90
1336     /**
1337     * Increment for seed generators. See class ThreadLocal for
1338     * explanation.
1339     */
1340 dl 1.193 private static final int SEED_INCREMENT = 0x9e3779b9;
1341 dl 1.83
1342 jsr166 1.163 /*
1343 dl 1.200 * Bits and masks for field ctl, packed with 4 16 bit subfields:
1344     * AC: Number of active running workers minus target parallelism
1345     * TC: Number of total workers minus target parallelism
1346     * SS: version count and status of top waiting thread
1347     * ID: poolIndex of top of Treiber stack of waiters
1348     *
1349     * When convenient, we can extract the lower 32 stack top bits
1350     * (including version bits) as sp=(int)ctl. The offsets of counts
1351     * by the target parallelism and the positionings of fields makes
1352     * it possible to perform the most common checks via sign tests of
1353     * fields: When ac is negative, there are not enough active
1354     * workers, when tc is negative, there are not enough total
1355     * workers. When sp is non-zero, there are waiting workers. To
1356     * deal with possibly negative fields, we use casts in and out of
1357     * "short" and/or signed shifts to maintain signedness.
1358     *
1359     * Because it occupies uppermost bits, we can add one active count
1360     * using getAndAddLong of AC_UNIT, rather than CAS, when returning
1361     * from a blocked join. Other updates entail multiple subfields
1362     * and masking, requiring CAS.
1363     */
1364    
1365     // Lower and upper word masks
1366     private static final long SP_MASK = 0xffffffffL;
1367     private static final long UC_MASK = ~SP_MASK;
1368 dl 1.86
1369 dl 1.200 // Active counts
1370 dl 1.86 private static final int AC_SHIFT = 48;
1371 dl 1.200 private static final long AC_UNIT = 0x0001L << AC_SHIFT;
1372     private static final long AC_MASK = 0xffffL << AC_SHIFT;
1373    
1374     // Total counts
1375 dl 1.86 private static final int TC_SHIFT = 32;
1376 dl 1.200 private static final long TC_UNIT = 0x0001L << TC_SHIFT;
1377     private static final long TC_MASK = 0xffffL << TC_SHIFT;
1378     private static final long ADD_WORKER = 0x0001L << (TC_SHIFT + 15); // sign
1379    
1380 dl 1.205 // runState bits: SHUTDOWN must be negative, others arbitrary powers of two
1381 dl 1.200 private static final int RSLOCK = 1;
1382     private static final int RSIGNAL = 1 << 1;
1383     private static final int STARTED = 1 << 2;
1384 dl 1.205 private static final int STOP = 1 << 29;
1385     private static final int TERMINATED = 1 << 30;
1386     private static final int SHUTDOWN = 1 << 31;
1387 dl 1.86
1388     // Instance fields
1389 dl 1.200 volatile long ctl; // main pool control
1390     volatile int runState; // lockable status
1391     final int config; // parallelism, mode
1392     int indexSeed; // to generate worker index
1393     volatile WorkQueue[] workQueues; // main registry
1394 dl 1.112 final ForkJoinWorkerThreadFactory factory;
1395 dl 1.200 final UncaughtExceptionHandler ueh; // per-worker UEH
1396     final String workerNamePrefix; // to create worker name string
1397 dl 1.215 volatile AtomicLong stealCounter; // also used as sync monitor
1398 dl 1.101
1399 jsr166 1.145 /**
1400 jsr166 1.213 * Acquires the runState lock; returns current (locked) runState.
1401 dl 1.105 */
1402 dl 1.200 private int lockRunState() {
1403     int rs;
1404     return ((((rs = runState) & RSLOCK) != 0 ||
1405     !U.compareAndSwapInt(this, RUNSTATE, rs, rs |= RSLOCK)) ?
1406     awaitRunStateLock() : rs);
1407     }
1408    
1409     /**
1410 dl 1.215 * Spins and/or blocks until runstate lock is available. See
1411     * above for explanation.
1412 dl 1.200 */
1413     private int awaitRunStateLock() {
1414 dl 1.215 Object lock;
1415 dl 1.210 boolean wasInterrupted = false;
1416     for (int spins = SPINS, r = 0, rs, ns;;) {
1417 dl 1.200 if (((rs = runState) & RSLOCK) == 0) {
1418 dl 1.210 if (U.compareAndSwapInt(this, RUNSTATE, rs, ns = rs | RSLOCK)) {
1419     if (wasInterrupted) {
1420     try {
1421     Thread.currentThread().interrupt();
1422     } catch (SecurityException ignore) {
1423     }
1424     }
1425     return ns;
1426     }
1427 dl 1.200 }
1428     else if (r == 0)
1429     r = ThreadLocalRandom.nextSecondarySeed();
1430     else if (spins > 0) {
1431     r ^= r << 6; r ^= r >>> 21; r ^= r << 7; // xorshift
1432     if (r >= 0)
1433 dl 1.101 --spins;
1434     }
1435 dl 1.215 else if ((rs & STARTED) == 0 || (lock = stealCounter) == null)
1436     Thread.yield(); // initialization race
1437 dl 1.200 else if (U.compareAndSwapInt(this, RUNSTATE, rs, rs | RSIGNAL)) {
1438 dl 1.215 synchronized (lock) {
1439 dl 1.200 if ((runState & RSIGNAL) != 0) {
1440 dl 1.101 try {
1441 dl 1.215 lock.wait();
1442 dl 1.101 } catch (InterruptedException ie) {
1443 dl 1.210 if (!(Thread.currentThread() instanceof
1444     ForkJoinWorkerThread))
1445     wasInterrupted = true;
1446 dl 1.101 }
1447     }
1448     else
1449 dl 1.215 lock.notifyAll();
1450 dl 1.101 }
1451     }
1452     }
1453     }
1454 dl 1.78
1455 jsr166 1.1 /**
1456 dl 1.200 * Unlocks and sets runState to newRunState.
1457     *
1458     * @param oldRunState a value returned from lockRunState
1459     * @param newRunState the next value (must have lock bit clear).
1460 jsr166 1.1 */
1461 dl 1.200 private void unlockRunState(int oldRunState, int newRunState) {
1462     if (!U.compareAndSwapInt(this, RUNSTATE, oldRunState, newRunState)) {
1463 dl 1.215 Object lock = stealCounter;
1464 dl 1.200 runState = newRunState; // clears RSIGNAL bit
1465 dl 1.215 if (lock != null)
1466     synchronized (lock) { lock.notifyAll(); }
1467 dl 1.200 }
1468 dl 1.78 }
1469 jsr166 1.1
1470 dl 1.200 // Creating, registering and deregistering workers
1471    
1472 dl 1.112 /**
1473 dl 1.200 * Tries to construct and start one worker. Assumes that total
1474     * count has already been incremented as a reservation. Invokes
1475     * deregisterWorker on any failure.
1476     *
1477     * @return true if successful
1478 dl 1.115 */
1479 dl 1.200 private boolean createWorker() {
1480     ForkJoinWorkerThreadFactory fac = factory;
1481     Throwable ex = null;
1482     ForkJoinWorkerThread wt = null;
1483     try {
1484     if (fac != null && (wt = fac.newThread(this)) != null) {
1485     wt.start();
1486     return true;
1487 dl 1.115 }
1488 dl 1.200 } catch (Throwable rex) {
1489     ex = rex;
1490 dl 1.112 }
1491 dl 1.200 deregisterWorker(wt, ex);
1492     return false;
1493 dl 1.112 }
1494    
1495 dl 1.200 /**
1496     * Tries to add one worker, incrementing ctl counts before doing
1497     * so, relying on createWorker to back out on failure.
1498     *
1499     * @param c incoming ctl value, with total count negative and no
1500     * idle workers. On CAS failure, c is refreshed and retried if
1501 jsr166 1.202 * this holds (otherwise, a new worker is not needed).
1502 dl 1.200 */
1503     private void tryAddWorker(long c) {
1504     boolean add = false;
1505     do {
1506     long nc = ((AC_MASK & (c + AC_UNIT)) |
1507     (TC_MASK & (c + TC_UNIT)));
1508     if (ctl == c) {
1509     int rs, stop; // check if terminating
1510     if ((stop = (rs = lockRunState()) & STOP) == 0)
1511     add = U.compareAndSwapLong(this, CTL, c, nc);
1512     unlockRunState(rs, rs & ~RSLOCK);
1513     if (stop != 0)
1514     break;
1515     if (add) {
1516     createWorker();
1517     break;
1518     }
1519     }
1520     } while (((c = ctl) & ADD_WORKER) != 0L && (int)c == 0);
1521     }
1522 dl 1.112
1523     /**
1524 dl 1.200 * Callback from ForkJoinWorkerThread constructor to establish and
1525     * record its WorkQueue.
1526 dl 1.112 *
1527     * @param wt the worker thread
1528 dl 1.115 * @return the worker's queue
1529 dl 1.112 */
1530 dl 1.115 final WorkQueue registerWorker(ForkJoinWorkerThread wt) {
1531 dl 1.200 UncaughtExceptionHandler handler;
1532     wt.setDaemon(true); // configure thread
1533 dl 1.115 if ((handler = ueh) != null)
1534     wt.setUncaughtExceptionHandler(handler);
1535 dl 1.200 WorkQueue w = new WorkQueue(this, wt);
1536     int i = 0; // assign a pool index
1537     int mode = config & MODE_MASK;
1538     int rs = lockRunState();
1539 dl 1.115 try {
1540 dl 1.200 WorkQueue[] ws; int n; // skip if no array
1541     if ((ws = workQueues) != null && (n = ws.length) > 0) {
1542     int s = indexSeed += SEED_INCREMENT; // unlikely to collide
1543     int m = n - 1;
1544     i = ((s << 1) | 1) & m; // odd-numbered indices
1545     if (ws[i] != null) { // collision
1546     int probes = 0; // step by approx half n
1547 dl 1.115 int step = (n <= 4) ? 2 : ((n >>> 1) & EVENMASK) + 2;
1548 dl 1.200 while (ws[i = (i + step) & m] != null) {
1549 dl 1.115 if (++probes >= n) {
1550     workQueues = ws = Arrays.copyOf(ws, n <<= 1);
1551     m = n - 1;
1552     probes = 0;
1553 dl 1.94 }
1554     }
1555     }
1556 dl 1.200 w.hint = s; // use as random seed
1557     w.config = i | mode;
1558     w.scanState = i; // publication fence
1559     ws[i] = w;
1560 dl 1.78 }
1561 dl 1.115 } finally {
1562 dl 1.200 unlockRunState(rs, rs & ~RSLOCK);
1563 dl 1.78 }
1564 dl 1.200 wt.setName(workerNamePrefix.concat(Integer.toString(i >>> 1)));
1565 dl 1.115 return w;
1566 dl 1.78 }
1567 dl 1.19
1568 jsr166 1.1 /**
1569 dl 1.86 * Final callback from terminating worker, as well as upon failure
1570 dl 1.105 * to construct or start a worker. Removes record of worker from
1571     * array, and adjusts counts. If pool is shutting down, tries to
1572     * complete termination.
1573 dl 1.78 *
1574 jsr166 1.151 * @param wt the worker thread, or null if construction failed
1575 dl 1.78 * @param ex the exception causing failure, or null if none
1576 dl 1.45 */
1577 dl 1.78 final void deregisterWorker(ForkJoinWorkerThread wt, Throwable ex) {
1578     WorkQueue w = null;
1579     if (wt != null && (w = wt.workQueue) != null) {
1580 dl 1.200 WorkQueue[] ws; // remove index from array
1581     int idx = w.config & SMASK;
1582     int rs = lockRunState();
1583     if ((ws = workQueues) != null && ws.length > idx && ws[idx] == w)
1584     ws[idx] = null;
1585     unlockRunState(rs, rs & ~RSLOCK);
1586     }
1587     long c; // decrement counts
1588     do {} while (!U.compareAndSwapLong
1589     (this, CTL, c = ctl, ((AC_MASK & (c - AC_UNIT)) |
1590     (TC_MASK & (c - TC_UNIT)) |
1591     (SP_MASK & c))));
1592     if (w != null) {
1593     w.qlock = -1; // ensure set
1594 dl 1.215 w.transferStealCount(this);
1595 dl 1.200 w.cancelAll(); // cancel remaining tasks
1596 dl 1.78 }
1597 dl 1.209 for (;;) { // possibly replace
1598 dl 1.205 WorkQueue[] ws; int m, sp;
1599 dl 1.209 if (tryTerminate(false, false) || w == null || w.array == null ||
1600     (runState & STOP) != 0 || (ws = workQueues) == null ||
1601     (m = ws.length - 1) < 0) // already terminating
1602     break;
1603     if ((sp = (int)(c = ctl)) != 0) { // wake up replacement
1604     if (tryRelease(c, ws[sp & m], AC_UNIT))
1605 dl 1.205 break;
1606 dl 1.120 }
1607 dl 1.209 else if (ex != null && (c & ADD_WORKER) != 0L) {
1608     tryAddWorker(c); // create replacement
1609     break;
1610     }
1611     else // don't need replacement
1612     break;
1613 dl 1.78 }
1614 dl 1.200 if (ex == null) // help clean on way out
1615 dl 1.120 ForkJoinTask.helpExpungeStaleExceptions();
1616 dl 1.200 else // rethrow
1617 dl 1.104 ForkJoinTask.rethrow(ex);
1618 dl 1.78 }
1619 dl 1.52
1620 dl 1.200 // Signalling
1621 dl 1.19
1622     /**
1623 dl 1.115 * Tries to create or activate a worker if too few are active.
1624     *
1625 dl 1.178 * @param ws the worker array to use to find signallees
1626 dl 1.200 * @param q a WorkQueue --if non-null, don't retry if now empty
1627 dl 1.105 */
1628 dl 1.178 final void signalWork(WorkQueue[] ws, WorkQueue q) {
1629 dl 1.200 long c; int sp, i; WorkQueue v; Thread p;
1630 dl 1.211 while ((c = ctl) < 0L) { // too few active
1631 dl 1.200 if ((sp = (int)c) == 0) { // no idle workers
1632     if ((c & ADD_WORKER) != 0L) // too few workers
1633     tryAddWorker(c);
1634     break;
1635     }
1636     if (ws == null) // unstarted/terminated
1637 dl 1.174 break;
1638 dl 1.200 if (ws.length <= (i = sp & SMASK)) // terminated
1639 dl 1.115 break;
1640 dl 1.200 if ((v = ws[i]) == null) // terminating
1641 dl 1.174 break;
1642 dl 1.200 int vs = (sp + SS_SEQ) & ~INACTIVE; // next scanState
1643     int d = sp - v.scanState; // screen CAS
1644     long nc = (UC_MASK & (c + AC_UNIT)) | (SP_MASK & v.stackPred);
1645     if (d == 0 && U.compareAndSwapLong(this, CTL, c, nc)) {
1646     v.scanState = vs; // activate v
1647     if ((p = v.parker) != null)
1648 dl 1.174 U.unpark(p);
1649     break;
1650     }
1651 dl 1.205 if (q != null && q.base == q.top) // no more work
1652 dl 1.174 break;
1653 dl 1.52 }
1654 dl 1.14 }
1655    
1656 dl 1.200 /**
1657     * Signals and releases worker v if it is top of idle worker
1658     * stack. This performs a one-shot version of signalWork only if
1659     * there is (apparently) at least one idle worker.
1660     *
1661     * @param c incoming ctl value
1662     * @param v if non-null, a worker
1663     * @param inc the increment to active count (zero when compensating)
1664     * @return true if successful
1665     */
1666     private boolean tryRelease(long c, WorkQueue v, long inc) {
1667     int sp = (int)c, vs = (sp + SS_SEQ) & ~INACTIVE; Thread p;
1668 dl 1.211 if (v != null && v.scanState == sp) { // v is at top of stack
1669 dl 1.200 long nc = (UC_MASK & (c + inc)) | (SP_MASK & v.stackPred);
1670     if (U.compareAndSwapLong(this, CTL, c, nc)) {
1671     v.scanState = vs;
1672     if ((p = v.parker) != null)
1673     U.unpark(p);
1674     return true;
1675     }
1676     }
1677     return false;
1678     }
1679    
1680 dl 1.90 // Scanning for tasks
1681    
1682 dl 1.14 /**
1683 dl 1.90 * Top-level runloop for workers, called by ForkJoinWorkerThread.run.
1684 dl 1.14 */
1685 dl 1.90 final void runWorker(WorkQueue w) {
1686 dl 1.200 w.growArray(); // allocate queue
1687     int seed = w.hint; // initially holds randomization hint
1688     int r = (seed == 0) ? 1 : seed; // avoid 0 for xorShift
1689     for (ForkJoinTask<?> t;;) {
1690     if ((t = scan(w, r)) != null)
1691     w.runTask(t);
1692     else if (!awaitWork(w, r))
1693     break;
1694 dl 1.178 r ^= r << 13; r ^= r >>> 17; r ^= r << 5; // xorshift
1695     }
1696 dl 1.14 }
1697    
1698     /**
1699 dl 1.200 * Scans for and tries to steal a top-level task. Scans start at a
1700 jsr166 1.202 * random location, randomly moving on apparent contention,
1701 dl 1.200 * otherwise continuing linearly until reaching two consecutive
1702     * empty passes over all queues with the same checksum (summing
1703     * each base index of each queue, that moves on each steal), at
1704     * which point the worker tries to inactivate and then re-scans,
1705     * attempting to re-activate (itself or some other worker) if
1706     * finding a task; otherwise returning null to await work. Scans
1707     * otherwise touch as little memory as possible, to reduce
1708     * disruption on other scanning threads.
1709 dl 1.78 *
1710     * @param w the worker (via its WorkQueue)
1711 dl 1.178 * @param r a random seed
1712 dl 1.200 * @return a task, or null if none found
1713 dl 1.78 */
1714 dl 1.200 private ForkJoinTask<?> scan(WorkQueue w, int r) {
1715 dl 1.115 WorkQueue[] ws; int m;
1716 dl 1.200 if ((ws = workQueues) != null && (m = ws.length - 1) > 0 && w != null) {
1717     int ss = w.scanState; // initially non-negative
1718     for (int origin = r & m, k = origin, oldSum = 0, checkSum = 0;;) {
1719 dl 1.225 WorkQueue q; ForkJoinTask<?> t; int al, i, n; long c;
1720 dl 1.200 if ((q = ws[k]) != null) {
1721 dl 1.225 int b = q.base; ForkJoinTask<?>[] a = q.array;
1722     if ((n = b - q.top) < 0 && a != null &&
1723     (al = a.length) > 0) { // non-empty
1724     if ((t = getAt(a, i = (al - 1) & b)) != null &&
1725 dl 1.200 q.base == b) {
1726     if (ss >= 0) {
1727 dl 1.225 if (casAt(a, i, t, null)) {
1728 dl 1.200 q.base = b + 1;
1729     if (n < -1) // signal others
1730     signalWork(ws, q);
1731     return t;
1732     }
1733     }
1734     else if (oldSum == 0 && // try to activate
1735     w.scanState < 0)
1736     tryRelease(c = ctl, ws[m & (int)c], AC_UNIT);
1737 dl 1.178 }
1738 dl 1.200 if (ss < 0) // refresh
1739     ss = w.scanState;
1740     r ^= r << 1; r ^= r >>> 3; r ^= r << 10;
1741     origin = k = r & m; // move and rescan
1742     oldSum = checkSum = 0;
1743     continue;
1744     }
1745     checkSum += b;
1746     }
1747     if ((k = (k + 1) & m) == origin) { // continue until stable
1748     if ((ss >= 0 || (ss == (ss = w.scanState))) &&
1749     oldSum == (oldSum = checkSum)) {
1750 dl 1.210 if (ss < 0 || w.qlock < 0) // already inactive
1751 dl 1.200 break;
1752     int ns = ss | INACTIVE; // try to inactivate
1753     long nc = ((SP_MASK & ns) |
1754     (UC_MASK & ((c = ctl) - AC_UNIT)));
1755     w.stackPred = (int)c; // hold prev stack top
1756     U.putInt(w, QSCANSTATE, ns);
1757     if (U.compareAndSwapLong(this, CTL, c, nc))
1758     ss = ns;
1759     else
1760     w.scanState = ss; // back out
1761 dl 1.174 }
1762 dl 1.200 checkSum = 0;
1763 dl 1.115 }
1764     }
1765 dl 1.52 }
1766 dl 1.200 return null;
1767 dl 1.14 }
1768    
1769     /**
1770 dl 1.200 * Possibly blocks worker w waiting for a task to steal, or
1771     * returns false if the worker should terminate. If inactivating
1772     * w has caused the pool to become quiescent, checks for pool
1773 dl 1.178 * termination, and, so long as this is not the only worker, waits
1774 dl 1.200 * for up to a given duration. On timeout, if ctl has not
1775     * changed, terminates the worker, which will in turn wake up
1776 dl 1.178 * another worker to possibly repeat this process.
1777 dl 1.52 *
1778 dl 1.78 * @param w the calling worker
1779 jsr166 1.221 * @param r a random seed (for spins)
1780 dl 1.200 * @return false if the worker should terminate
1781 dl 1.14 */
1782 dl 1.200 private boolean awaitWork(WorkQueue w, int r) {
1783     if (w == null || w.qlock < 0) // w is terminating
1784     return false;
1785     for (int pred = w.stackPred, spins = SPINS, ss;;) {
1786     if ((ss = w.scanState) >= 0)
1787     break;
1788     else if (spins > 0) {
1789     r ^= r << 6; r ^= r >>> 21; r ^= r << 7;
1790     if (r >= 0 && --spins == 0) { // randomize spins
1791 dl 1.215 WorkQueue v; WorkQueue[] ws; int s, j; AtomicLong sc;
1792 dl 1.200 if (pred != 0 && (ws = workQueues) != null &&
1793     (j = pred & SMASK) < ws.length &&
1794     (v = ws[j]) != null && // see if pred parking
1795     (v.parker == null || v.scanState >= 0))
1796 jsr166 1.202 spins = SPINS; // continue spinning
1797 dl 1.200 }
1798 dl 1.177 }
1799 dl 1.200 else if (w.qlock < 0) // recheck after spins
1800     return false;
1801     else if (!Thread.interrupted()) {
1802     long c, prevctl, parkTime, deadline;
1803     int ac = (int)((c = ctl) >> AC_SHIFT) + (config & SMASK);
1804 dl 1.210 if ((ac <= 0 && tryTerminate(false, false)) ||
1805     (runState & STOP) != 0) // pool terminating
1806 dl 1.200 return false;
1807     if (ac <= 0 && ss == (int)c) { // is last waiter
1808     prevctl = (UC_MASK & (c + AC_UNIT)) | (SP_MASK & pred);
1809 dl 1.205 int t = (short)(c >>> TC_SHIFT); // shrink excess spares
1810     if (t > 2 && U.compareAndSwapLong(this, CTL, c, prevctl))
1811 dl 1.208 return false; // else use timed wait
1812 dl 1.205 parkTime = IDLE_TIMEOUT * ((t >= 0) ? 1 : 1 - t);
1813 dl 1.178 deadline = System.nanoTime() + parkTime - TIMEOUT_SLOP;
1814     }
1815     else
1816 dl 1.200 prevctl = parkTime = deadline = 0L;
1817     Thread wt = Thread.currentThread();
1818     U.putObject(wt, PARKBLOCKER, this); // emulate LockSupport
1819     w.parker = wt;
1820     if (w.scanState < 0 && ctl == c) // recheck before park
1821     U.park(false, parkTime);
1822     U.putOrderedObject(w, QPARKER, null);
1823     U.putObject(wt, PARKBLOCKER, null);
1824     if (w.scanState >= 0)
1825     break;
1826     if (parkTime != 0L && ctl == c &&
1827     deadline - System.nanoTime() <= 0L &&
1828     U.compareAndSwapLong(this, CTL, c, prevctl))
1829     return false; // shrink pool
1830 dl 1.120 }
1831     }
1832 dl 1.200 return true;
1833 dl 1.178 }
1834    
1835 dl 1.200 // Joining tasks
1836    
1837 dl 1.178 /**
1838 dl 1.200 * Tries to steal and run tasks within the target's computation.
1839     * Uses a variant of the top-level algorithm, restricted to tasks
1840     * with the given task as ancestor: It prefers taking and running
1841     * eligible tasks popped from the worker's own queue (via
1842     * popCC). Otherwise it scans others, randomly moving on
1843     * contention or execution, deciding to give up based on a
1844     * checksum (via return codes frob pollAndExecCC). The maxTasks
1845     * argument supports external usages; internal calls use zero,
1846     * allowing unbounded steps (external calls trap non-positive
1847     * values).
1848     *
1849     * @param w caller
1850 jsr166 1.202 * @param maxTasks if non-zero, the maximum number of other tasks to run
1851 dl 1.200 * @return task status on exit
1852     */
1853     final int helpComplete(WorkQueue w, CountedCompleter<?> task,
1854     int maxTasks) {
1855     WorkQueue[] ws; int s = 0, m;
1856 dl 1.225 if ((ws = workQueues) != null && (m = ws.length - 1) > 0 &&
1857 dl 1.200 task != null && w != null) {
1858     int mode = w.config; // for popCC
1859     int r = w.hint ^ w.top; // arbitrary seed for origin
1860     int origin = r & m; // first queue to scan
1861     int h = 1; // 1:ran, >1:contended, <0:hash
1862     for (int k = origin, oldSum = 0, checkSum = 0;;) {
1863     CountedCompleter<?> p; WorkQueue q;
1864     if ((s = task.status) < 0)
1865     break;
1866     if (h == 1 && (p = w.popCC(task, mode)) != null) {
1867     p.doExec(); // run local task
1868     if (maxTasks != 0 && --maxTasks == 0)
1869     break;
1870     origin = k; // reset
1871     oldSum = checkSum = 0;
1872     }
1873     else { // poll other queues
1874     if ((q = ws[k]) == null)
1875     h = 0;
1876     else if ((h = q.pollAndExecCC(task)) < 0)
1877     checkSum += h;
1878     if (h > 0) {
1879     if (h == 1 && maxTasks != 0 && --maxTasks == 0)
1880     break;
1881     r ^= r << 13; r ^= r >>> 17; r ^= r << 5; // xorshift
1882     origin = k = r & m; // move and restart
1883     oldSum = checkSum = 0;
1884     }
1885     else if ((k = (k + 1) & m) == origin) {
1886     if (oldSum == (oldSum = checkSum))
1887     break;
1888     checkSum = 0;
1889     }
1890     }
1891 dl 1.178 }
1892     }
1893 dl 1.200 return s;
1894 dl 1.120 }
1895    
1896     /**
1897 dl 1.78 * Tries to locate and execute tasks for a stealer of the given
1898     * task, or in turn one of its stealers, Traces currentSteal ->
1899     * currentJoin links looking for a thread working on a descendant
1900     * of the given task and with a non-empty queue to steal back and
1901     * execute tasks from. The first call to this method upon a
1902     * waiting join will often entail scanning/search, (which is OK
1903     * because the joiner has nothing better to do), but this method
1904 dl 1.200 * leaves hints in workers to speed up subsequent calls.
1905 dl 1.78 *
1906 dl 1.200 * @param w caller
1907 dl 1.78 * @param task the task to join
1908     */
1909 dl 1.200 private void helpStealer(WorkQueue w, ForkJoinTask<?> task) {
1910     WorkQueue[] ws = workQueues;
1911     int oldSum = 0, checkSum, m;
1912 dl 1.225 if (ws != null && (m = ws.length - 1) > 0 && w != null &&
1913 dl 1.200 task != null) {
1914     do { // restart point
1915     checkSum = 0; // for stability check
1916     ForkJoinTask<?> subtask;
1917     WorkQueue j = w, v; // v is subtask stealer
1918     descent: for (subtask = task; subtask.status >= 0; ) {
1919     for (int h = j.hint | 1, k = 0, i; ; k += 2) {
1920     if (k > m) // can't find stealer
1921     break descent;
1922     if ((v = ws[i = (h + k) & m]) != null) {
1923     if (v.currentSteal == subtask) {
1924     j.hint = i;
1925 dl 1.95 break;
1926     }
1927 dl 1.200 checkSum += v.base;
1928 dl 1.78 }
1929     }
1930 dl 1.200 for (;;) { // help v or descend
1931 dl 1.225 ForkJoinTask<?>[] a; int b, al, i;
1932 dl 1.200 checkSum += (b = v.base);
1933     ForkJoinTask<?> next = v.currentJoin;
1934     if (subtask.status < 0 || j.currentJoin != subtask ||
1935     v.currentSteal != subtask) // stale
1936     break descent;
1937 dl 1.224 if (b - v.top >= 0 || (a = v.array) == null ||
1938 dl 1.225 (al = a.length) <= 0) {
1939 dl 1.200 if ((subtask = next) == null)
1940     break descent;
1941     j = v;
1942     break;
1943 dl 1.95 }
1944 dl 1.225 ForkJoinTask<?> t = getAt(a, i = (al - 1) & b);
1945 dl 1.200 if (v.base == b) {
1946     if (t == null) // stale
1947     break descent;
1948 dl 1.225 if (casAt(a, i, t, null)) {
1949 dl 1.200 v.base = b + 1;
1950     ForkJoinTask<?> ps = w.currentSteal;
1951 dl 1.205 int top = w.top;
1952     do {
1953     U.putOrderedObject(w, QCURRENTSTEAL, t);
1954     t.doExec(); // clear local tasks too
1955     } while (task.status >= 0 &&
1956     w.top != top &&
1957     (t = w.pop()) != null);
1958 dl 1.200 U.putOrderedObject(w, QCURRENTSTEAL, ps);
1959 dl 1.205 if (w.base != w.top)
1960 dl 1.200 return; // can't further help
1961 dl 1.95 }
1962 dl 1.78 }
1963 dl 1.52 }
1964 dl 1.19 }
1965 dl 1.200 } while (task.status >= 0 && oldSum != (oldSum = checkSum));
1966 dl 1.14 }
1967 dl 1.22 }
1968    
1969 dl 1.52 /**
1970 dl 1.200 * Tries to decrement active count (sometimes implicitly) and
1971     * possibly release or create a compensating worker in preparation
1972     * for blocking. Returns false (retryable by caller), on
1973 dl 1.208 * contention, detected staleness, instability, or termination.
1974 dl 1.105 *
1975 dl 1.200 * @param w caller
1976 dl 1.19 */
1977 dl 1.200 private boolean tryCompensate(WorkQueue w) {
1978     boolean canBlock;
1979     WorkQueue[] ws; long c; int m, pc, sp;
1980     if (w == null || w.qlock < 0 || // caller terminating
1981     (ws = workQueues) == null || (m = ws.length - 1) <= 0 ||
1982     (pc = config & SMASK) == 0) // parallelism disabled
1983     canBlock = false;
1984     else if ((sp = (int)(c = ctl)) != 0) // release idle worker
1985     canBlock = tryRelease(c, ws[sp & m], 0L);
1986     else {
1987     int ac = (int)(c >> AC_SHIFT) + pc;
1988     int tc = (short)(c >> TC_SHIFT) + pc;
1989     int nbusy = 0; // validate saturation
1990     for (int i = 0; i <= m; ++i) { // two passes of odd indices
1991     WorkQueue v;
1992     if ((v = ws[((i << 1) | 1) & m]) != null) {
1993     if ((v.scanState & SCANNING) != 0)
1994 dl 1.190 break;
1995 dl 1.200 ++nbusy;
1996 dl 1.178 }
1997 dl 1.52 }
1998 dl 1.200 if (nbusy != (tc << 1) || ctl != c)
1999     canBlock = false; // unstable or stale
2000     else if (tc >= pc && ac > 1 && w.isEmpty()) {
2001     long nc = ((AC_MASK & (c - AC_UNIT)) |
2002     (~AC_MASK & c)); // uncompensated
2003     canBlock = U.compareAndSwapLong(this, CTL, c, nc);
2004 dl 1.105 }
2005 dl 1.208 else if (tc >= MAX_CAP ||
2006     (this == common && tc >= pc + commonMaxSpares))
2007 dl 1.200 throw new RejectedExecutionException(
2008     "Thread limit exceeded replacing blocked worker");
2009     else { // similar to tryAddWorker
2010     boolean add = false; int rs; // CAS within lock
2011     long nc = ((AC_MASK & c) |
2012     (TC_MASK & (c + TC_UNIT)));
2013     if (((rs = lockRunState()) & STOP) == 0)
2014     add = U.compareAndSwapLong(this, CTL, c, nc);
2015     unlockRunState(rs, rs & ~RSLOCK);
2016     canBlock = add && createWorker(); // throws on exception
2017 dl 1.90 }
2018     }
2019 dl 1.200 return canBlock;
2020 dl 1.90 }
2021    
2022     /**
2023 dl 1.200 * Helps and/or blocks until the given task is done or timeout.
2024 dl 1.90 *
2025 dl 1.200 * @param w caller
2026 dl 1.90 * @param task the task
2027 dl 1.219 * @param deadline for timed waits, if nonzero
2028 dl 1.90 * @return task status on exit
2029     */
2030 dl 1.200 final int awaitJoin(WorkQueue w, ForkJoinTask<?> task, long deadline) {
2031 dl 1.105 int s = 0;
2032 dl 1.200 if (task != null && w != null) {
2033     ForkJoinTask<?> prevJoin = w.currentJoin;
2034     U.putOrderedObject(w, QCURRENTJOIN, task);
2035     CountedCompleter<?> cc = (task instanceof CountedCompleter) ?
2036     (CountedCompleter<?>)task : null;
2037     for (;;) {
2038     if ((s = task.status) < 0)
2039     break;
2040     if (cc != null)
2041     helpComplete(w, cc, 0);
2042     else if (w.base == w.top || w.tryRemoveAndExec(task))
2043     helpStealer(w, task);
2044     if ((s = task.status) < 0)
2045     break;
2046     long ms, ns;
2047     if (deadline == 0L)
2048     ms = 0L;
2049     else if ((ns = deadline - System.nanoTime()) <= 0L)
2050     break;
2051     else if ((ms = TimeUnit.NANOSECONDS.toMillis(ns)) <= 0L)
2052     ms = 1L;
2053     if (tryCompensate(w)) {
2054     task.internalWait(ms);
2055     U.getAndAddLong(this, CTL, AC_UNIT);
2056 dl 1.90 }
2057     }
2058 dl 1.200 U.putOrderedObject(w, QCURRENTJOIN, prevJoin);
2059 dl 1.90 }
2060 dl 1.94 return s;
2061 dl 1.90 }
2062    
2063 dl 1.200 // Specialized scanning
2064 dl 1.90
2065     /**
2066     * Returns a (probably) non-empty steal queue, if one is found
2067 dl 1.131 * during a scan, else null. This method must be retried by
2068     * caller if, by the time it tries to use the queue, it is empty.
2069 dl 1.78 */
2070 dl 1.178 private WorkQueue findNonEmptyStealQueue() {
2071 dl 1.211 WorkQueue[] ws; int m; // one-shot version of scan loop
2072     int r = ThreadLocalRandom.nextSecondarySeed();
2073 dl 1.225 if ((ws = workQueues) != null && (m = ws.length - 1) > 0) {
2074 dl 1.211 for (int origin = r & m, k = origin, oldSum = 0, checkSum = 0;;) {
2075     WorkQueue q; int b;
2076     if ((q = ws[k]) != null) {
2077     if ((b = q.base) - q.top < 0)
2078     return q;
2079     checkSum += b;
2080     }
2081     if ((k = (k + 1) & m) == origin) {
2082     if (oldSum == (oldSum = checkSum))
2083     break;
2084     checkSum = 0;
2085 dl 1.52 }
2086     }
2087 dl 1.211 }
2088 dl 1.200 return null;
2089 dl 1.22 }
2090    
2091     /**
2092 dl 1.78 * Runs tasks until {@code isQuiescent()}. We piggyback on
2093     * active count ctl maintenance, but rather than blocking
2094     * when tasks cannot be found, we rescan until all others cannot
2095     * find tasks either.
2096     */
2097     final void helpQuiescePool(WorkQueue w) {
2098 dl 1.211 ForkJoinTask<?> ps = w.currentSteal; // save context
2099 dl 1.78 for (boolean active = true;;) {
2100 dl 1.131 long c; WorkQueue q; ForkJoinTask<?> t; int b;
2101 dl 1.225 if ((w.config & FIFO_QUEUE) != 0)
2102     w.pollAndExecAll(); // run locals before each scan
2103     else
2104     w.popAndExecAll();
2105 dl 1.178 if ((q = findNonEmptyStealQueue()) != null) {
2106 dl 1.78 if (!active) { // re-establish active count
2107     active = true;
2108 dl 1.200 U.getAndAddLong(this, CTL, AC_UNIT);
2109     }
2110     if ((b = q.base) - q.top < 0 && (t = q.pollAt(b)) != null) {
2111     U.putOrderedObject(w, QCURRENTSTEAL, t);
2112     t.doExec();
2113 dl 1.215 if (++w.nsteals < 0)
2114     w.transferStealCount(this);
2115 dl 1.178 }
2116 dl 1.78 }
2117 jsr166 1.194 else if (active) { // decrement active count without queuing
2118 dl 1.200 long nc = (AC_MASK & ((c = ctl) - AC_UNIT)) | (~AC_MASK & c);
2119     if ((int)(nc >> AC_SHIFT) + (config & SMASK) <= 0)
2120 dl 1.185 break; // bypass decrement-then-increment
2121 dl 1.131 if (U.compareAndSwapLong(this, CTL, c, nc))
2122 dl 1.78 active = false;
2123 dl 1.22 }
2124 dl 1.200 else if ((int)((c = ctl) >> AC_SHIFT) + (config & SMASK) <= 0 &&
2125     U.compareAndSwapLong(this, CTL, c, c + AC_UNIT))
2126 dl 1.185 break;
2127 dl 1.22 }
2128 dl 1.211 U.putOrderedObject(w, QCURRENTSTEAL, ps);
2129 dl 1.22 }
2130    
2131     /**
2132 jsr166 1.84 * Gets and removes a local or stolen task for the given worker.
2133 dl 1.78 *
2134     * @return a task, if available
2135 dl 1.22 */
2136 dl 1.78 final ForkJoinTask<?> nextTaskFor(WorkQueue w) {
2137     for (ForkJoinTask<?> t;;) {
2138 dl 1.90 WorkQueue q; int b;
2139 dl 1.78 if ((t = w.nextLocalTask()) != null)
2140     return t;
2141 dl 1.178 if ((q = findNonEmptyStealQueue()) == null)
2142 dl 1.78 return null;
2143 dl 1.172 if ((b = q.base) - q.top < 0 && (t = q.pollAt(b)) != null)
2144 dl 1.78 return t;
2145 dl 1.52 }
2146 dl 1.14 }
2147    
2148     /**
2149 dl 1.105 * Returns a cheap heuristic guide for task partitioning when
2150     * programmers, frameworks, tools, or languages have little or no
2151 jsr166 1.222 * idea about task granularity. In essence, by offering this
2152 dl 1.105 * method, we ask users only about tradeoffs in overhead vs
2153     * expected throughput and its variance, rather than how finely to
2154     * partition tasks.
2155     *
2156     * In a steady state strict (tree-structured) computation, each
2157     * thread makes available for stealing enough tasks for other
2158     * threads to remain active. Inductively, if all threads play by
2159     * the same rules, each thread should make available only a
2160     * constant number of tasks.
2161     *
2162     * The minimum useful constant is just 1. But using a value of 1
2163     * would require immediate replenishment upon each steal to
2164     * maintain enough tasks, which is infeasible. Further,
2165     * partitionings/granularities of offered tasks should minimize
2166     * steal rates, which in general means that threads nearer the top
2167     * of computation tree should generate more than those nearer the
2168     * bottom. In perfect steady state, each thread is at
2169     * approximately the same level of computation tree. However,
2170     * producing extra tasks amortizes the uncertainty of progress and
2171     * diffusion assumptions.
2172     *
2173 jsr166 1.161 * So, users will want to use values larger (but not much larger)
2174 dl 1.105 * than 1 to both smooth over transient shortages and hedge
2175     * against uneven progress; as traded off against the cost of
2176     * extra task overhead. We leave the user to pick a threshold
2177     * value to compare with the results of this call to guide
2178     * decisions, but recommend values such as 3.
2179     *
2180     * When all threads are active, it is on average OK to estimate
2181     * surplus strictly locally. In steady-state, if one thread is
2182     * maintaining say 2 surplus tasks, then so are others. So we can
2183     * just use estimated queue length. However, this strategy alone
2184     * leads to serious mis-estimates in some non-steady-state
2185     * conditions (ramp-up, ramp-down, other stalls). We can detect
2186     * many of these by further considering the number of "idle"
2187     * threads, that are known to have zero queued tasks, so
2188     * compensate by a factor of (#idle/#active) threads.
2189     */
2190     static int getSurplusQueuedTaskCount() {
2191     Thread t; ForkJoinWorkerThread wt; ForkJoinPool pool; WorkQueue q;
2192 jsr166 1.229 if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) {
2193 dl 1.200 int p = (pool = (wt = (ForkJoinWorkerThread)t).pool).
2194     config & SMASK;
2195 dl 1.112 int n = (q = wt.workQueue).top - q.base;
2196 dl 1.105 int a = (int)(pool.ctl >> AC_SHIFT) + p;
2197 dl 1.112 return n - (a > (p >>>= 1) ? 0 :
2198     a > (p >>>= 1) ? 1 :
2199     a > (p >>>= 1) ? 2 :
2200     a > (p >>>= 1) ? 4 :
2201     8);
2202 dl 1.105 }
2203     return 0;
2204 dl 1.100 }
2205    
2206 dl 1.86 // Termination
2207 dl 1.14
2208     /**
2209 dl 1.210 * Possibly initiates and/or completes termination.
2210 dl 1.14 *
2211     * @param now if true, unconditionally terminate, else only
2212 dl 1.78 * if no work and no active workers
2213 jsr166 1.87 * @param enable if true, enable shutdown when next possible
2214 dl 1.14 * @return true if now terminating or terminated
2215 jsr166 1.1 */
2216 dl 1.86 private boolean tryTerminate(boolean now, boolean enable) {
2217 dl 1.200 int rs;
2218     if (this == common) // cannot shut down
2219 dl 1.105 return false;
2220 dl 1.210 if ((rs = runState) >= 0) {
2221 dl 1.131 if (!enable)
2222     return false;
2223 dl 1.210 rs = lockRunState(); // enter SHUTDOWN phase
2224 dl 1.200 unlockRunState(rs, (rs & ~RSLOCK) | SHUTDOWN);
2225     }
2226 dl 1.210
2227 jsr166 1.204 if ((rs & STOP) == 0) {
2228 dl 1.210 if (!now) { // check quiescence
2229 dl 1.211 for (long oldSum = 0L;;) { // repeat until stable
2230 dl 1.210 WorkQueue[] ws; WorkQueue w; int m, b; long c;
2231     long checkSum = ctl;
2232     if ((int)(checkSum >> AC_SHIFT) + (config & SMASK) > 0)
2233     return false; // still active workers
2234 dl 1.209 if ((ws = workQueues) == null || (m = ws.length - 1) <= 0)
2235 dl 1.210 break; // check queues
2236 dl 1.209 for (int i = 0; i <= m; ++i) {
2237     if ((w = ws[i]) != null) {
2238 dl 1.210 if ((b = w.base) != w.top || w.scanState >= 0 ||
2239     w.currentSteal != null) {
2240     tryRelease(c = ctl, ws[m & (int)c], AC_UNIT);
2241 dl 1.211 return false; // arrange for recheck
2242 dl 1.210 }
2243     checkSum += b;
2244 dl 1.209 if ((i & 1) == 0)
2245 dl 1.210 w.qlock = -1; // try to disable external
2246 dl 1.206 }
2247 dl 1.203 }
2248 dl 1.209 if (oldSum == (oldSum = checkSum))
2249 dl 1.210 break;
2250 dl 1.203 }
2251     }
2252 dl 1.210 if ((runState & STOP) == 0) {
2253     rs = lockRunState(); // enter STOP phase
2254     unlockRunState(rs, (rs & ~RSLOCK) | STOP);
2255     }
2256 dl 1.200 }
2257 dl 1.210
2258     int pass = 0; // 3 passes to help terminate
2259     for (long oldSum = 0L;;) { // or until done or stable
2260     WorkQueue[] ws; WorkQueue w; ForkJoinWorkerThread wt; int m;
2261     long checkSum = ctl;
2262     if ((short)(checkSum >>> TC_SHIFT) + (config & SMASK) <= 0 ||
2263     (ws = workQueues) == null || (m = ws.length - 1) <= 0) {
2264     if ((runState & TERMINATED) == 0) {
2265     rs = lockRunState(); // done
2266     unlockRunState(rs, (rs & ~RSLOCK) | TERMINATED);
2267     synchronized (this) { notifyAll(); } // for awaitTermination
2268     }
2269     break;
2270     }
2271     for (int i = 0; i <= m; ++i) {
2272     if ((w = ws[i]) != null) {
2273     checkSum += w.base;
2274     w.qlock = -1; // try to disable
2275     if (pass > 0) {
2276     w.cancelAll(); // clear queue
2277     if (pass > 1 && (wt = w.owner) != null) {
2278     if (!wt.isInterrupted()) {
2279     try { // unblock join
2280     wt.interrupt();
2281     } catch (Throwable ignore) {
2282 dl 1.200 }
2283     }
2284 dl 1.210 if (w.scanState < 0)
2285     U.unpark(wt); // wake up
2286 dl 1.200 }
2287 dl 1.101 }
2288 dl 1.78 }
2289     }
2290 dl 1.210 if (checkSum != oldSum) { // unstable
2291     oldSum = checkSum;
2292     pass = 0;
2293     }
2294     else if (pass > 3 && pass > m) // can't further help
2295     break;
2296     else if (++pass > 1) { // try to dequeue
2297     long c; int j = 0, sp; // bound attempts
2298     while (j++ <= m && (sp = (int)(c = ctl)) != 0)
2299     tryRelease(c, ws[sp & m], AC_UNIT);
2300 dl 1.200 }
2301     }
2302     return true;
2303     }
2304    
2305     // External operations
2306    
2307     /**
2308     * Full version of externalPush, handling uncommon cases, as well
2309     * as performing secondary initialization upon the first
2310     * submission of the first task to the pool. It also detects
2311     * first submission by an external thread and creates a new shared
2312     * queue if the one at index if empty or contended.
2313     *
2314     * @param task the task. Caller must ensure non-null.
2315     */
2316     private void externalSubmit(ForkJoinTask<?> task) {
2317     int r; // initialize caller's probe
2318     if ((r = ThreadLocalRandom.getProbe()) == 0) {
2319     ThreadLocalRandom.localInit();
2320     r = ThreadLocalRandom.getProbe();
2321     }
2322     for (;;) {
2323     WorkQueue[] ws; WorkQueue q; int rs, m, k;
2324     boolean move = false;
2325 dl 1.210 if ((rs = runState) < 0) {
2326     tryTerminate(false, false); // help terminate
2327 dl 1.200 throw new RejectedExecutionException();
2328 dl 1.210 }
2329 dl 1.215 else if ((rs & STARTED) == 0 || // initialize
2330 dl 1.225 ((ws = workQueues) == null || (m = ws.length - 1) <= 0)) {
2331 dl 1.200 int ns = 0;
2332     rs = lockRunState();
2333     try {
2334 dl 1.215 if ((rs & STARTED) == 0) {
2335     U.compareAndSwapObject(this, STEALCOUNTER, null,
2336     new AtomicLong());
2337     // create workQueues array with size a power of two
2338 dl 1.200 int p = config & SMASK; // ensure at least 2 slots
2339     int n = (p > 1) ? p - 1 : 1;
2340     n |= n >>> 1; n |= n >>> 2; n |= n >>> 4;
2341     n |= n >>> 8; n |= n >>> 16; n = (n + 1) << 1;
2342     workQueues = new WorkQueue[n];
2343     ns = STARTED;
2344 dl 1.78 }
2345 dl 1.200 } finally {
2346     unlockRunState(rs, (rs & ~RSLOCK) | ns);
2347 dl 1.52 }
2348     }
2349 dl 1.200 else if ((q = ws[k = r & m & SQMASK]) != null) {
2350     if (q.qlock == 0 && U.compareAndSwapInt(q, QLOCK, 0, 1)) {
2351     ForkJoinTask<?>[] a = q.array;
2352 dl 1.225 int s = q.top;
2353 dl 1.200 boolean submitted = false; // initial submission or resizing
2354     try { // locked version of push
2355 dl 1.225 if ((a != null && a.length > s + 1 - q.base) ||
2356     (a = q.growArray()) != null) {
2357     int al = a.length, j = (al - 1) & s;
2358     if (al > 0) {
2359     setAt(a, j, task);
2360     U.putOrderedInt(q, QTOP, s + 1);
2361     submitted = true;
2362     }
2363 dl 1.86 }
2364 dl 1.200 } finally {
2365 dl 1.209 U.compareAndSwapInt(q, QLOCK, 1, 0);
2366 dl 1.200 }
2367     if (submitted) {
2368     signalWork(ws, q);
2369     return;
2370 dl 1.78 }
2371 dl 1.52 }
2372 dl 1.200 move = true; // move on failure
2373 dl 1.52 }
2374 dl 1.200 else if (((rs = runState) & RSLOCK) == 0) { // create new queue
2375     q = new WorkQueue(this, null);
2376     q.hint = r;
2377     q.config = k | SHARED_QUEUE;
2378 dl 1.210 q.scanState = INACTIVE;
2379 dl 1.200 rs = lockRunState(); // publish index
2380 dl 1.209 if (rs > 0 && (ws = workQueues) != null &&
2381     k < ws.length && ws[k] == null)
2382 dl 1.200 ws[k] = q; // else terminated
2383     unlockRunState(rs, rs & ~RSLOCK);
2384     }
2385     else
2386     move = true; // move if busy
2387     if (move)
2388     r = ThreadLocalRandom.advanceProbe(r);
2389 dl 1.52 }
2390     }
2391    
2392 dl 1.200 /**
2393     * Tries to add the given task to a submission queue at
2394     * submitter's current queue. Only the (vastly) most common path
2395     * is directly handled in this method, while screening for need
2396     * for externalSubmit.
2397     *
2398     * @param task the task. Caller must ensure non-null.
2399     */
2400     final void externalPush(ForkJoinTask<?> task) {
2401     WorkQueue[] ws; WorkQueue q; int m;
2402     int r = ThreadLocalRandom.getProbe();
2403 dl 1.205 int rs = runState;
2404 dl 1.225 if ((ws = workQueues) != null && (m = (ws.length - 1)) > 0 &&
2405 dl 1.205 (q = ws[m & r & SQMASK]) != null && r != 0 && rs > 0 &&
2406 dl 1.200 U.compareAndSwapInt(q, QLOCK, 0, 1)) {
2407 dl 1.224 ForkJoinTask<?>[] a;
2408     if ((a = q.array) != null) {
2409 dl 1.225 int b = q.base, al = a.length, s = q.top;
2410     if (al > 0) {
2411     int am = al - 1, j = am & s, n;
2412     if ((n = s - b) < am) {
2413     setAt(a, j, task);
2414     U.putOrderedInt(q, QTOP, s + 1);
2415     U.putOrderedInt(q, QLOCK, 0);
2416     if (n <= 1)
2417     signalWork(ws, q);
2418     return;
2419     }
2420 dl 1.224 }
2421 dl 1.200 }
2422 dl 1.209 U.compareAndSwapInt(q, QLOCK, 1, 0);
2423 dl 1.200 }
2424     externalSubmit(task);
2425     }
2426 dl 1.105
2427     /**
2428 jsr166 1.237 * Pushes a possibly-external submission.
2429 dl 1.236 */
2430     final <T> ForkJoinTask<T> doSubmit(ForkJoinTask<T> task) {
2431     Thread t; ForkJoinWorkerThread w;
2432     if (task == null)
2433     throw new NullPointerException();
2434     if (((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) &&
2435     (w = (ForkJoinWorkerThread)t).pool == this)
2436     w.workQueue.push(task);
2437 jsr166 1.238 else
2438 dl 1.236 externalPush(task);
2439     return task;
2440     }
2441    
2442     /**
2443 jsr166 1.213 * Returns common pool queue for an external thread.
2444 dl 1.105 */
2445     static WorkQueue commonSubmitterQueue() {
2446 dl 1.200 ForkJoinPool p = common;
2447     int r = ThreadLocalRandom.getProbe();
2448     WorkQueue[] ws; int m;
2449     return (p != null && (ws = p.workQueues) != null &&
2450 dl 1.225 (m = ws.length - 1) > 0) ?
2451 dl 1.200 ws[m & r & SQMASK] : null;
2452 dl 1.105 }
2453    
2454     /**
2455 dl 1.200 * Performs tryUnpush for an external submitter: Finds queue,
2456     * locks if apparently non-empty, validates upon locking, and
2457     * adjusts top. Each check can fail but rarely does.
2458 dl 1.105 */
2459 dl 1.178 final boolean tryExternalUnpush(ForkJoinTask<?> task) {
2460 dl 1.224 WorkQueue[] ws; WorkQueue w; ForkJoinTask<?>[] a; int m;
2461 dl 1.200 int r = ThreadLocalRandom.getProbe();
2462 dl 1.225 if ((ws = workQueues) != null && (m = ws.length - 1) > 0 &&
2463 dl 1.200 (w = ws[m & r & SQMASK]) != null &&
2464 dl 1.224 (a = w.array) != null) {
2465 dl 1.225 int b = w.base, al = a.length, s = w.top;
2466     if (s != b && al > 0 &&
2467     U.compareAndSwapInt(w, QLOCK, 0, 1)) {
2468     int i = (al - 1) & (s - 1);
2469     if (w.top == s && w.array == a && casAt(a, i, task, null)) {
2470 dl 1.200 U.putOrderedInt(w, QTOP, s - 1);
2471     U.putOrderedInt(w, QLOCK, 0);
2472     return true;
2473 dl 1.115 }
2474 dl 1.209 U.compareAndSwapInt(w, QLOCK, 1, 0);
2475 dl 1.105 }
2476     }
2477 dl 1.200 return false;
2478 dl 1.105 }
2479    
2480 dl 1.200 /**
2481 jsr166 1.213 * Performs helpComplete for an external submitter.
2482 dl 1.200 */
2483 dl 1.190 final int externalHelpComplete(CountedCompleter<?> task, int maxTasks) {
2484 dl 1.200 WorkQueue[] ws; int n;
2485     int r = ThreadLocalRandom.getProbe();
2486     return ((ws = workQueues) == null || (n = ws.length) == 0) ? 0 :
2487     helpComplete(ws[(n - 1) & r & SQMASK], task, maxTasks);
2488 dl 1.105 }
2489    
2490 dl 1.52 // Exported methods
2491 jsr166 1.1
2492     // Constructors
2493    
2494     /**
2495 jsr166 1.9 * Creates a {@code ForkJoinPool} with parallelism equal to {@link
2496 dl 1.18 * java.lang.Runtime#availableProcessors}, using the {@linkplain
2497     * #defaultForkJoinWorkerThreadFactory default thread factory},
2498     * no UncaughtExceptionHandler, and non-async LIFO processing mode.
2499 jsr166 1.1 *
2500     * @throws SecurityException if a security manager exists and
2501     * the caller is not permitted to modify threads
2502     * because it does not hold {@link
2503     * java.lang.RuntimePermission}{@code ("modifyThread")}
2504     */
2505     public ForkJoinPool() {
2506 jsr166 1.148 this(Math.min(MAX_CAP, Runtime.getRuntime().availableProcessors()),
2507     defaultForkJoinWorkerThreadFactory, null, false);
2508 jsr166 1.1 }
2509    
2510     /**
2511 jsr166 1.9 * Creates a {@code ForkJoinPool} with the indicated parallelism
2512 dl 1.18 * level, the {@linkplain
2513     * #defaultForkJoinWorkerThreadFactory default thread factory},
2514     * no UncaughtExceptionHandler, and non-async LIFO processing mode.
2515 jsr166 1.1 *
2516 jsr166 1.9 * @param parallelism the parallelism level
2517 jsr166 1.1 * @throws IllegalArgumentException if parallelism less than or
2518 jsr166 1.11 * equal to zero, or greater than implementation limit
2519 jsr166 1.1 * @throws SecurityException if a security manager exists and
2520     * the caller is not permitted to modify threads
2521     * because it does not hold {@link
2522     * java.lang.RuntimePermission}{@code ("modifyThread")}
2523     */
2524     public ForkJoinPool(int parallelism) {
2525 dl 1.18 this(parallelism, defaultForkJoinWorkerThreadFactory, null, false);
2526 jsr166 1.1 }
2527    
2528     /**
2529 dl 1.18 * Creates a {@code ForkJoinPool} with the given parameters.
2530 jsr166 1.1 *
2531 dl 1.18 * @param parallelism the parallelism level. For default value,
2532     * use {@link java.lang.Runtime#availableProcessors}.
2533     * @param factory the factory for creating new threads. For default value,
2534     * use {@link #defaultForkJoinWorkerThreadFactory}.
2535 dl 1.19 * @param handler the handler for internal worker threads that
2536     * terminate due to unrecoverable errors encountered while executing
2537 jsr166 1.31 * tasks. For default value, use {@code null}.
2538 dl 1.19 * @param asyncMode if true,
2539 dl 1.18 * establishes local first-in-first-out scheduling mode for forked
2540     * tasks that are never joined. This mode may be more appropriate
2541     * than default locally stack-based mode in applications in which
2542     * worker threads only process event-style asynchronous tasks.
2543 jsr166 1.31 * For default value, use {@code false}.
2544 jsr166 1.1 * @throws IllegalArgumentException if parallelism less than or
2545 jsr166 1.11 * equal to zero, or greater than implementation limit
2546     * @throws NullPointerException if the factory is null
2547 jsr166 1.1 * @throws SecurityException if a security manager exists and
2548     * the caller is not permitted to modify threads
2549     * because it does not hold {@link
2550     * java.lang.RuntimePermission}{@code ("modifyThread")}
2551     */
2552 dl 1.19 public ForkJoinPool(int parallelism,
2553 dl 1.18 ForkJoinWorkerThreadFactory factory,
2554 jsr166 1.156 UncaughtExceptionHandler handler,
2555 dl 1.18 boolean asyncMode) {
2556 dl 1.152 this(checkParallelism(parallelism),
2557     checkFactory(factory),
2558     handler,
2559 jsr166 1.201 asyncMode ? FIFO_QUEUE : LIFO_QUEUE,
2560 dl 1.152 "ForkJoinPool-" + nextPoolId() + "-worker-");
2561 dl 1.14 checkPermission();
2562 dl 1.152 }
2563    
2564     private static int checkParallelism(int parallelism) {
2565     if (parallelism <= 0 || parallelism > MAX_CAP)
2566     throw new IllegalArgumentException();
2567     return parallelism;
2568     }
2569    
2570     private static ForkJoinWorkerThreadFactory checkFactory
2571     (ForkJoinWorkerThreadFactory factory) {
2572 dl 1.14 if (factory == null)
2573     throw new NullPointerException();
2574 dl 1.152 return factory;
2575     }
2576    
2577     /**
2578     * Creates a {@code ForkJoinPool} with the given parameters, without
2579     * any security checks or parameter validation. Invoked directly by
2580     * makeCommonPool.
2581     */
2582     private ForkJoinPool(int parallelism,
2583     ForkJoinWorkerThreadFactory factory,
2584 jsr166 1.156 UncaughtExceptionHandler handler,
2585 dl 1.185 int mode,
2586 dl 1.152 String workerNamePrefix) {
2587     this.workerNamePrefix = workerNamePrefix;
2588 jsr166 1.1 this.factory = factory;
2589 dl 1.18 this.ueh = handler;
2590 dl 1.200 this.config = (parallelism & SMASK) | mode;
2591 dl 1.52 long np = (long)(-parallelism); // offset ctl counts
2592     this.ctl = ((np << AC_SHIFT) & AC_MASK) | ((np << TC_SHIFT) & TC_MASK);
2593 dl 1.101 }
2594    
2595     /**
2596 dl 1.128 * Returns the common pool instance. This pool is statically
2597 dl 1.134 * constructed; its run state is unaffected by attempts to {@link
2598     * #shutdown} or {@link #shutdownNow}. However this pool and any
2599     * ongoing processing are automatically terminated upon program
2600     * {@link System#exit}. Any program that relies on asynchronous
2601     * task processing to complete before program termination should
2602 jsr166 1.158 * invoke {@code commonPool().}{@link #awaitQuiescence awaitQuiescence},
2603     * before exit.
2604 dl 1.100 *
2605     * @return the common pool instance
2606 jsr166 1.138 * @since 1.8
2607 dl 1.100 */
2608     public static ForkJoinPool commonPool() {
2609 dl 1.134 // assert common != null : "static init error";
2610     return common;
2611 dl 1.100 }
2612    
2613 jsr166 1.1 // Execution methods
2614    
2615     /**
2616     * Performs the given task, returning its result upon completion.
2617 dl 1.52 * If the computation encounters an unchecked Exception or Error,
2618     * it is rethrown as the outcome of this invocation. Rethrown
2619     * exceptions behave in the same way as regular exceptions, but,
2620     * when possible, contain stack traces (as displayed for example
2621     * using {@code ex.printStackTrace()}) of both the current thread
2622     * as well as the thread actually encountering the exception;
2623     * minimally only the latter.
2624 jsr166 1.1 *
2625     * @param task the task
2626 jsr166 1.191 * @param <T> the type of the task's result
2627 jsr166 1.1 * @return the task's result
2628 jsr166 1.11 * @throws NullPointerException if the task is null
2629     * @throws RejectedExecutionException if the task cannot be
2630     * scheduled for execution
2631 jsr166 1.1 */
2632     public <T> T invoke(ForkJoinTask<T> task) {
2633 dl 1.90 if (task == null)
2634     throw new NullPointerException();
2635 dl 1.236 doSubmit(task);
2636 dl 1.78 return task.join();
2637 jsr166 1.1 }
2638    
2639     /**
2640     * Arranges for (asynchronous) execution of the given task.
2641     *
2642     * @param task the task
2643 jsr166 1.11 * @throws NullPointerException if the task is null
2644     * @throws RejectedExecutionException if the task cannot be
2645     * scheduled for execution
2646 jsr166 1.1 */
2647 jsr166 1.8 public void execute(ForkJoinTask<?> task) {
2648 dl 1.236 doSubmit(task);
2649 jsr166 1.1 }
2650    
2651     // AbstractExecutorService methods
2652    
2653 jsr166 1.11 /**
2654     * @throws NullPointerException if the task is null
2655     * @throws RejectedExecutionException if the task cannot be
2656     * scheduled for execution
2657     */
2658 jsr166 1.1 public void execute(Runnable task) {
2659 dl 1.41 if (task == null)
2660     throw new NullPointerException();
2661 jsr166 1.2 ForkJoinTask<?> job;
2662 jsr166 1.3 if (task instanceof ForkJoinTask<?>) // avoid re-wrap
2663     job = (ForkJoinTask<?>) task;
2664 jsr166 1.2 else
2665 dl 1.152 job = new ForkJoinTask.RunnableExecuteAction(task);
2666 dl 1.236 doSubmit(job);
2667 jsr166 1.1 }
2668    
2669 jsr166 1.11 /**
2670 dl 1.18 * Submits a ForkJoinTask for execution.
2671     *
2672     * @param task the task to submit
2673 jsr166 1.191 * @param <T> the type of the task's result
2674 dl 1.18 * @return the task
2675     * @throws NullPointerException if the task is null
2676     * @throws RejectedExecutionException if the task cannot be
2677     * scheduled for execution
2678     */
2679     public <T> ForkJoinTask<T> submit(ForkJoinTask<T> task) {
2680 dl 1.236 return doSubmit(task);
2681 dl 1.18 }
2682    
2683     /**
2684 jsr166 1.11 * @throws NullPointerException if the task is null
2685     * @throws RejectedExecutionException if the task cannot be
2686     * scheduled for execution
2687     */
2688 jsr166 1.1 public <T> ForkJoinTask<T> submit(Callable<T> task) {
2689 dl 1.236 return doSubmit(new ForkJoinTask.AdaptedCallable<T>(task));
2690 jsr166 1.1 }
2691    
2692 jsr166 1.11 /**
2693     * @throws NullPointerException if the task is null
2694     * @throws RejectedExecutionException if the task cannot be
2695     * scheduled for execution
2696     */
2697 jsr166 1.1 public <T> ForkJoinTask<T> submit(Runnable task, T result) {
2698 dl 1.236 return doSubmit(new ForkJoinTask.AdaptedRunnable<T>(task, result));
2699 jsr166 1.1 }
2700    
2701 jsr166 1.11 /**
2702     * @throws NullPointerException if the task is null
2703     * @throws RejectedExecutionException if the task cannot be
2704     * scheduled for execution
2705     */
2706 jsr166 1.1 public ForkJoinTask<?> submit(Runnable task) {
2707 dl 1.41 if (task == null)
2708     throw new NullPointerException();
2709 jsr166 1.2 ForkJoinTask<?> job;
2710 jsr166 1.3 if (task instanceof ForkJoinTask<?>) // avoid re-wrap
2711     job = (ForkJoinTask<?>) task;
2712 jsr166 1.2 else
2713 dl 1.90 job = new ForkJoinTask.AdaptedRunnableAction(task);
2714 dl 1.236 return doSubmit(job);
2715 jsr166 1.1 }
2716    
2717     /**
2718 jsr166 1.11 * @throws NullPointerException {@inheritDoc}
2719     * @throws RejectedExecutionException {@inheritDoc}
2720     */
2721 jsr166 1.1 public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) {
2722 dl 1.86 // In previous versions of this class, this method constructed
2723     // a task to run ForkJoinTask.invokeAll, but now external
2724     // invocation of multiple tasks is at least as efficient.
2725 jsr166 1.199 ArrayList<Future<T>> futures = new ArrayList<>(tasks.size());
2726 jsr166 1.1
2727 dl 1.86 try {
2728     for (Callable<T> t : tasks) {
2729 dl 1.90 ForkJoinTask<T> f = new ForkJoinTask.AdaptedCallable<T>(t);
2730 jsr166 1.144 futures.add(f);
2731 dl 1.236 doSubmit(f);
2732 dl 1.86 }
2733 jsr166 1.143 for (int i = 0, size = futures.size(); i < size; i++)
2734     ((ForkJoinTask<?>)futures.get(i)).quietlyJoin();
2735 dl 1.86 return futures;
2736 jsr166 1.226 } catch (Throwable t) {
2737     for (int i = 0, size = futures.size(); i < size; i++)
2738     futures.get(i).cancel(false);
2739     throw t;
2740 jsr166 1.1 }
2741     }
2742    
2743     /**
2744     * Returns the factory used for constructing new workers.
2745     *
2746     * @return the factory used for constructing new workers
2747     */
2748     public ForkJoinWorkerThreadFactory getFactory() {
2749     return factory;
2750     }
2751    
2752     /**
2753     * Returns the handler for internal worker threads that terminate
2754     * due to unrecoverable errors encountered while executing tasks.
2755     *
2756 jsr166 1.4 * @return the handler, or {@code null} if none
2757 jsr166 1.1 */
2758 jsr166 1.156 public UncaughtExceptionHandler getUncaughtExceptionHandler() {
2759 dl 1.14 return ueh;
2760 jsr166 1.1 }
2761    
2762     /**
2763 jsr166 1.9 * Returns the targeted parallelism level of this pool.
2764 jsr166 1.1 *
2765 jsr166 1.9 * @return the targeted parallelism level of this pool
2766 jsr166 1.1 */
2767     public int getParallelism() {
2768 dl 1.185 int par;
2769 dl 1.200 return ((par = config & SMASK) > 0) ? par : 1;
2770 jsr166 1.1 }
2771    
2772     /**
2773 dl 1.100 * Returns the targeted parallelism level of the common pool.
2774     *
2775     * @return the targeted parallelism level of the common pool
2776 jsr166 1.138 * @since 1.8
2777 dl 1.100 */
2778     public static int getCommonPoolParallelism() {
2779 dl 1.134 return commonParallelism;
2780 dl 1.100 }
2781    
2782     /**
2783 jsr166 1.1 * Returns the number of worker threads that have started but not
2784 jsr166 1.34 * yet terminated. The result returned by this method may differ
2785 jsr166 1.4 * from {@link #getParallelism} when threads are created to
2786 jsr166 1.1 * maintain parallelism when others are cooperatively blocked.
2787     *
2788     * @return the number of worker threads
2789     */
2790     public int getPoolSize() {
2791 dl 1.200 return (config & SMASK) + (short)(ctl >>> TC_SHIFT);
2792 jsr166 1.1 }
2793    
2794     /**
2795 jsr166 1.4 * Returns {@code true} if this pool uses local first-in-first-out
2796 jsr166 1.1 * scheduling mode for forked tasks that are never joined.
2797     *
2798 jsr166 1.4 * @return {@code true} if this pool uses async mode
2799 jsr166 1.1 */
2800     public boolean getAsyncMode() {
2801 dl 1.200 return (config & FIFO_QUEUE) != 0;
2802 jsr166 1.1 }
2803    
2804     /**
2805     * Returns an estimate of the number of worker threads that are
2806     * not blocked waiting to join tasks or for other managed
2807 dl 1.14 * synchronization. This method may overestimate the
2808     * number of running threads.
2809 jsr166 1.1 *
2810     * @return the number of worker threads
2811     */
2812     public int getRunningThreadCount() {
2813 dl 1.78 int rc = 0;
2814     WorkQueue[] ws; WorkQueue w;
2815     if ((ws = workQueues) != null) {
2816 dl 1.86 for (int i = 1; i < ws.length; i += 2) {
2817     if ((w = ws[i]) != null && w.isApparentlyUnblocked())
2818 dl 1.78 ++rc;
2819     }
2820     }
2821     return rc;
2822 jsr166 1.1 }
2823    
2824     /**
2825     * Returns an estimate of the number of threads that are currently
2826     * stealing or executing tasks. This method may overestimate the
2827     * number of active threads.
2828     *
2829     * @return the number of active threads
2830     */
2831     public int getActiveThreadCount() {
2832 dl 1.200 int r = (config & SMASK) + (int)(ctl >> AC_SHIFT);
2833 jsr166 1.63 return (r <= 0) ? 0 : r; // suppress momentarily negative values
2834 jsr166 1.1 }
2835    
2836     /**
2837 jsr166 1.4 * Returns {@code true} if all worker threads are currently idle.
2838     * An idle worker is one that cannot obtain a task to execute
2839     * because none are available to steal from other threads, and
2840     * there are no pending submissions to the pool. This method is
2841     * conservative; it might not return {@code true} immediately upon
2842     * idleness of all threads, but will eventually become true if
2843     * threads remain inactive.
2844 jsr166 1.1 *
2845 jsr166 1.4 * @return {@code true} if all threads are currently idle
2846 jsr166 1.1 */
2847     public boolean isQuiescent() {
2848 dl 1.200 return (config & SMASK) + (int)(ctl >> AC_SHIFT) <= 0;
2849 jsr166 1.1 }
2850    
2851     /**
2852     * Returns an estimate of the total number of tasks stolen from
2853     * one thread's work queue by another. The reported value
2854     * underestimates the actual total number of steals when the pool
2855     * is not quiescent. This value may be useful for monitoring and
2856     * tuning fork/join programs: in general, steal counts should be
2857     * high enough to keep threads busy, but low enough to avoid
2858     * overhead and contention across threads.
2859     *
2860     * @return the number of steals
2861     */
2862     public long getStealCount() {
2863 dl 1.215 AtomicLong sc = stealCounter;
2864     long count = (sc == null) ? 0L : sc.get();
2865 dl 1.78 WorkQueue[] ws; WorkQueue w;
2866     if ((ws = workQueues) != null) {
2867 dl 1.86 for (int i = 1; i < ws.length; i += 2) {
2868 dl 1.78 if ((w = ws[i]) != null)
2869 dl 1.105 count += w.nsteals;
2870 dl 1.78 }
2871     }
2872     return count;
2873 jsr166 1.1 }
2874    
2875     /**
2876     * Returns an estimate of the total number of tasks currently held
2877     * in queues by worker threads (but not including tasks submitted
2878     * to the pool that have not begun executing). This value is only
2879     * an approximation, obtained by iterating across all threads in
2880     * the pool. This method may be useful for tuning task
2881     * granularities.
2882     *
2883     * @return the number of queued tasks
2884     */
2885     public long getQueuedTaskCount() {
2886     long count = 0;
2887 dl 1.78 WorkQueue[] ws; WorkQueue w;
2888     if ((ws = workQueues) != null) {
2889 dl 1.86 for (int i = 1; i < ws.length; i += 2) {
2890 dl 1.78 if ((w = ws[i]) != null)
2891     count += w.queueSize();
2892     }
2893 dl 1.52 }
2894 jsr166 1.1 return count;
2895     }
2896    
2897     /**
2898 jsr166 1.8 * Returns an estimate of the number of tasks submitted to this
2899 dl 1.55 * pool that have not yet begun executing. This method may take
2900 dl 1.52 * time proportional to the number of submissions.
2901 jsr166 1.1 *
2902     * @return the number of queued submissions
2903     */
2904     public int getQueuedSubmissionCount() {
2905 dl 1.78 int count = 0;
2906     WorkQueue[] ws; WorkQueue w;
2907     if ((ws = workQueues) != null) {
2908 dl 1.86 for (int i = 0; i < ws.length; i += 2) {
2909 dl 1.78 if ((w = ws[i]) != null)
2910     count += w.queueSize();
2911     }
2912     }
2913     return count;
2914 jsr166 1.1 }
2915    
2916     /**
2917 jsr166 1.4 * Returns {@code true} if there are any tasks submitted to this
2918     * pool that have not yet begun executing.
2919 jsr166 1.1 *
2920     * @return {@code true} if there are any queued submissions
2921     */
2922     public boolean hasQueuedSubmissions() {
2923 dl 1.78 WorkQueue[] ws; WorkQueue w;
2924     if ((ws = workQueues) != null) {
2925 dl 1.86 for (int i = 0; i < ws.length; i += 2) {
2926 dl 1.115 if ((w = ws[i]) != null && !w.isEmpty())
2927 dl 1.78 return true;
2928     }
2929     }
2930     return false;
2931 jsr166 1.1 }
2932    
2933     /**
2934     * Removes and returns the next unexecuted submission if one is
2935     * available. This method may be useful in extensions to this
2936     * class that re-assign work in systems with multiple pools.
2937     *
2938 jsr166 1.4 * @return the next submission, or {@code null} if none
2939 jsr166 1.1 */
2940     protected ForkJoinTask<?> pollSubmission() {
2941 dl 1.78 WorkQueue[] ws; WorkQueue w; ForkJoinTask<?> t;
2942     if ((ws = workQueues) != null) {
2943 dl 1.86 for (int i = 0; i < ws.length; i += 2) {
2944 dl 1.78 if ((w = ws[i]) != null && (t = w.poll()) != null)
2945     return t;
2946 dl 1.52 }
2947     }
2948     return null;
2949 jsr166 1.1 }
2950    
2951     /**
2952     * Removes all available unexecuted submitted and forked tasks
2953     * from scheduling queues and adds them to the given collection,
2954     * without altering their execution status. These may include
2955 jsr166 1.8 * artificially generated or wrapped tasks. This method is
2956     * designed to be invoked only when the pool is known to be
2957 jsr166 1.1 * quiescent. Invocations at other times may not remove all
2958     * tasks. A failure encountered while attempting to add elements
2959     * to collection {@code c} may result in elements being in
2960     * neither, either or both collections when the associated
2961     * exception is thrown. The behavior of this operation is
2962     * undefined if the specified collection is modified while the
2963     * operation is in progress.
2964     *
2965     * @param c the collection to transfer elements into
2966     * @return the number of elements transferred
2967     */
2968 jsr166 1.5 protected int drainTasksTo(Collection<? super ForkJoinTask<?>> c) {
2969 dl 1.52 int count = 0;
2970 dl 1.78 WorkQueue[] ws; WorkQueue w; ForkJoinTask<?> t;
2971     if ((ws = workQueues) != null) {
2972 dl 1.86 for (int i = 0; i < ws.length; ++i) {
2973 dl 1.78 if ((w = ws[i]) != null) {
2974     while ((t = w.poll()) != null) {
2975     c.add(t);
2976     ++count;
2977     }
2978     }
2979 dl 1.52 }
2980     }
2981 dl 1.18 return count;
2982     }
2983    
2984     /**
2985 jsr166 1.1 * Returns a string identifying this pool, as well as its state,
2986     * including indications of run state, parallelism level, and
2987     * worker and task counts.
2988     *
2989     * @return a string identifying this pool, as well as its state
2990     */
2991     public String toString() {
2992 dl 1.86 // Use a single pass through workQueues to collect counts
2993     long qt = 0L, qs = 0L; int rc = 0;
2994 dl 1.215 AtomicLong sc = stealCounter;
2995     long st = (sc == null) ? 0L : sc.get();
2996 dl 1.86 long c = ctl;
2997     WorkQueue[] ws; WorkQueue w;
2998     if ((ws = workQueues) != null) {
2999     for (int i = 0; i < ws.length; ++i) {
3000     if ((w = ws[i]) != null) {
3001     int size = w.queueSize();
3002     if ((i & 1) == 0)
3003     qs += size;
3004     else {
3005     qt += size;
3006 dl 1.105 st += w.nsteals;
3007 dl 1.86 if (w.isApparentlyUnblocked())
3008     ++rc;
3009     }
3010     }
3011     }
3012     }
3013 dl 1.200 int pc = (config & SMASK);
3014 dl 1.52 int tc = pc + (short)(c >>> TC_SHIFT);
3015 dl 1.78 int ac = pc + (int)(c >> AC_SHIFT);
3016     if (ac < 0) // ignore transient negative
3017     ac = 0;
3018 dl 1.200 int rs = runState;
3019     String level = ((rs & TERMINATED) != 0 ? "Terminated" :
3020     (rs & STOP) != 0 ? "Terminating" :
3021     (rs & SHUTDOWN) != 0 ? "Shutting down" :
3022     "Running");
3023 jsr166 1.1 return super.toString() +
3024 dl 1.52 "[" + level +
3025 dl 1.14 ", parallelism = " + pc +
3026     ", size = " + tc +
3027     ", active = " + ac +
3028     ", running = " + rc +
3029 jsr166 1.1 ", steals = " + st +
3030     ", tasks = " + qt +
3031     ", submissions = " + qs +
3032     "]";
3033     }
3034    
3035     /**
3036 dl 1.100 * Possibly initiates an orderly shutdown in which previously
3037     * submitted tasks are executed, but no new tasks will be
3038     * accepted. Invocation has no effect on execution state if this
3039 jsr166 1.137 * is the {@link #commonPool()}, and no additional effect if
3040 dl 1.100 * already shut down. Tasks that are in the process of being
3041     * submitted concurrently during the course of this method may or
3042     * may not be rejected.
3043 jsr166 1.1 *
3044     * @throws SecurityException if a security manager exists and
3045     * the caller is not permitted to modify threads
3046     * because it does not hold {@link
3047     * java.lang.RuntimePermission}{@code ("modifyThread")}
3048     */
3049     public void shutdown() {
3050     checkPermission();
3051 dl 1.105 tryTerminate(false, true);
3052 jsr166 1.1 }
3053    
3054     /**
3055 dl 1.100 * Possibly attempts to cancel and/or stop all tasks, and reject
3056     * all subsequently submitted tasks. Invocation has no effect on
3057 jsr166 1.137 * execution state if this is the {@link #commonPool()}, and no
3058 dl 1.100 * additional effect if already shut down. Otherwise, tasks that
3059     * are in the process of being submitted or executed concurrently
3060     * during the course of this method may or may not be
3061     * rejected. This method cancels both existing and unexecuted
3062     * tasks, in order to permit termination in the presence of task
3063     * dependencies. So the method always returns an empty list
3064     * (unlike the case for some other Executors).
3065 jsr166 1.1 *
3066     * @return an empty list
3067     * @throws SecurityException if a security manager exists and
3068     * the caller is not permitted to modify threads
3069     * because it does not hold {@link
3070     * java.lang.RuntimePermission}{@code ("modifyThread")}
3071     */
3072     public List<Runnable> shutdownNow() {
3073     checkPermission();
3074 dl 1.105 tryTerminate(true, true);
3075 jsr166 1.1 return Collections.emptyList();
3076     }
3077    
3078     /**
3079     * Returns {@code true} if all tasks have completed following shut down.
3080     *
3081     * @return {@code true} if all tasks have completed following shut down
3082     */
3083     public boolean isTerminated() {
3084 dl 1.200 return (runState & TERMINATED) != 0;
3085 jsr166 1.1 }
3086    
3087     /**
3088     * Returns {@code true} if the process of termination has
3089 jsr166 1.9 * commenced but not yet completed. This method may be useful for
3090     * debugging. A return of {@code true} reported a sufficient
3091     * period after shutdown may indicate that submitted tasks have
3092 jsr166 1.119 * ignored or suppressed interruption, or are waiting for I/O,
3093 dl 1.49 * causing this executor not to properly terminate. (See the
3094     * advisory notes for class {@link ForkJoinTask} stating that
3095     * tasks should not normally entail blocking operations. But if
3096     * they do, they must abort them on interrupt.)
3097 jsr166 1.1 *
3098 jsr166 1.9 * @return {@code true} if terminating but not yet terminated
3099 jsr166 1.1 */
3100     public boolean isTerminating() {
3101 dl 1.200 int rs = runState;
3102     return (rs & STOP) != 0 && (rs & TERMINATED) == 0;
3103 jsr166 1.1 }
3104    
3105     /**
3106     * Returns {@code true} if this pool has been shut down.
3107     *
3108     * @return {@code true} if this pool has been shut down
3109     */
3110     public boolean isShutdown() {
3111 dl 1.200 return (runState & SHUTDOWN) != 0;
3112 jsr166 1.9 }
3113    
3114     /**
3115 dl 1.105 * Blocks until all tasks have completed execution after a
3116     * shutdown request, or the timeout occurs, or the current thread
3117 dl 1.134 * is interrupted, whichever happens first. Because the {@link
3118     * #commonPool()} never terminates until program shutdown, when
3119     * applied to the common pool, this method is equivalent to {@link
3120 jsr166 1.158 * #awaitQuiescence(long, TimeUnit)} but always returns {@code false}.
3121 jsr166 1.1 *
3122     * @param timeout the maximum time to wait
3123     * @param unit the time unit of the timeout argument
3124     * @return {@code true} if this executor terminated and
3125     * {@code false} if the timeout elapsed before termination
3126     * @throws InterruptedException if interrupted while waiting
3127     */
3128     public boolean awaitTermination(long timeout, TimeUnit unit)
3129     throws InterruptedException {
3130 dl 1.134 if (Thread.interrupted())
3131     throw new InterruptedException();
3132     if (this == common) {
3133     awaitQuiescence(timeout, unit);
3134     return false;
3135     }
3136 dl 1.52 long nanos = unit.toNanos(timeout);
3137 dl 1.101 if (isTerminated())
3138     return true;
3139 dl 1.183 if (nanos <= 0L)
3140     return false;
3141     long deadline = System.nanoTime() + nanos;
3142 jsr166 1.103 synchronized (this) {
3143 jsr166 1.184 for (;;) {
3144 dl 1.183 if (isTerminated())
3145     return true;
3146     if (nanos <= 0L)
3147     return false;
3148     long millis = TimeUnit.NANOSECONDS.toMillis(nanos);
3149     wait(millis > 0L ? millis : 1L);
3150     nanos = deadline - System.nanoTime();
3151 dl 1.52 }
3152 dl 1.18 }
3153 jsr166 1.1 }
3154    
3155     /**
3156 dl 1.134 * If called by a ForkJoinTask operating in this pool, equivalent
3157     * in effect to {@link ForkJoinTask#helpQuiesce}. Otherwise,
3158     * waits and/or attempts to assist performing tasks until this
3159     * pool {@link #isQuiescent} or the indicated timeout elapses.
3160     *
3161     * @param timeout the maximum time to wait
3162     * @param unit the time unit of the timeout argument
3163     * @return {@code true} if quiescent; {@code false} if the
3164     * timeout elapsed.
3165     */
3166     public boolean awaitQuiescence(long timeout, TimeUnit unit) {
3167     long nanos = unit.toNanos(timeout);
3168     ForkJoinWorkerThread wt;
3169     Thread thread = Thread.currentThread();
3170     if ((thread instanceof ForkJoinWorkerThread) &&
3171     (wt = (ForkJoinWorkerThread)thread).pool == this) {
3172     helpQuiescePool(wt.workQueue);
3173     return true;
3174     }
3175     long startTime = System.nanoTime();
3176     WorkQueue[] ws;
3177     int r = 0, m;
3178     boolean found = true;
3179     while (!isQuiescent() && (ws = workQueues) != null &&
3180 dl 1.225 (m = ws.length - 1) > 0) {
3181 dl 1.134 if (!found) {
3182     if ((System.nanoTime() - startTime) > nanos)
3183     return false;
3184     Thread.yield(); // cannot block
3185     }
3186     found = false;
3187     for (int j = (m + 1) << 2; j >= 0; --j) {
3188 dl 1.200 ForkJoinTask<?> t; WorkQueue q; int b, k;
3189     if ((k = r++ & m) <= m && k >= 0 && (q = ws[k]) != null &&
3190     (b = q.base) - q.top < 0) {
3191 dl 1.134 found = true;
3192 dl 1.172 if ((t = q.pollAt(b)) != null)
3193 dl 1.134 t.doExec();
3194     break;
3195     }
3196     }
3197     }
3198     return true;
3199     }
3200    
3201     /**
3202     * Waits and/or attempts to assist performing tasks indefinitely
3203 jsr166 1.141 * until the {@link #commonPool()} {@link #isQuiescent}.
3204 dl 1.134 */
3205 dl 1.136 static void quiesceCommonPool() {
3206 dl 1.134 common.awaitQuiescence(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
3207     }
3208    
3209     /**
3210 jsr166 1.1 * Interface for extending managed parallelism for tasks running
3211 jsr166 1.8 * in {@link ForkJoinPool}s.
3212     *
3213 dl 1.19 * <p>A {@code ManagedBlocker} provides two methods. Method
3214 jsr166 1.218 * {@link #isReleasable} must return {@code true} if blocking is
3215     * not necessary. Method {@link #block} blocks the current thread
3216 dl 1.19 * if necessary (perhaps internally invoking {@code isReleasable}
3217 dl 1.54 * before actually blocking). These actions are performed by any
3218 jsr166 1.157 * thread invoking {@link ForkJoinPool#managedBlock(ManagedBlocker)}.
3219     * The unusual methods in this API accommodate synchronizers that
3220     * may, but don't usually, block for long periods. Similarly, they
3221 dl 1.54 * allow more efficient internal handling of cases in which
3222     * additional workers may be, but usually are not, needed to
3223     * ensure sufficient parallelism. Toward this end,
3224     * implementations of method {@code isReleasable} must be amenable
3225     * to repeated invocation.
3226 jsr166 1.1 *
3227     * <p>For example, here is a ManagedBlocker based on a
3228     * ReentrantLock:
3229 jsr166 1.239 * <pre> {@code
3230 jsr166 1.1 * class ManagedLocker implements ManagedBlocker {
3231     * final ReentrantLock lock;
3232     * boolean hasLock = false;
3233     * ManagedLocker(ReentrantLock lock) { this.lock = lock; }
3234     * public boolean block() {
3235     * if (!hasLock)
3236     * lock.lock();
3237     * return true;
3238     * }
3239     * public boolean isReleasable() {
3240     * return hasLock || (hasLock = lock.tryLock());
3241     * }
3242     * }}</pre>
3243 dl 1.19 *
3244     * <p>Here is a class that possibly blocks waiting for an
3245     * item on a given queue:
3246 jsr166 1.239 * <pre> {@code
3247 dl 1.19 * class QueueTaker<E> implements ManagedBlocker {
3248     * final BlockingQueue<E> queue;
3249     * volatile E item = null;
3250     * QueueTaker(BlockingQueue<E> q) { this.queue = q; }
3251     * public boolean block() throws InterruptedException {
3252     * if (item == null)
3253 dl 1.23 * item = queue.take();
3254 dl 1.19 * return true;
3255     * }
3256     * public boolean isReleasable() {
3257 dl 1.23 * return item != null || (item = queue.poll()) != null;
3258 dl 1.19 * }
3259     * public E getItem() { // call after pool.managedBlock completes
3260     * return item;
3261     * }
3262     * }}</pre>
3263 jsr166 1.1 */
3264     public static interface ManagedBlocker {
3265     /**
3266     * Possibly blocks the current thread, for example waiting for
3267     * a lock or condition.
3268     *
3269 jsr166 1.4 * @return {@code true} if no additional blocking is necessary
3270     * (i.e., if isReleasable would return true)
3271 jsr166 1.1 * @throws InterruptedException if interrupted while waiting
3272     * (the method is not required to do so, but is allowed to)
3273     */
3274     boolean block() throws InterruptedException;
3275    
3276     /**
3277 jsr166 1.4 * Returns {@code true} if blocking is unnecessary.
3278 jsr166 1.154 * @return {@code true} if blocking is unnecessary
3279 jsr166 1.1 */
3280     boolean isReleasable();
3281     }
3282    
3283     /**
3284 jsr166 1.217 * Runs the given possibly blocking task. When {@linkplain
3285     * ForkJoinTask#inForkJoinPool() running in a ForkJoinPool}, this
3286     * method possibly arranges for a spare thread to be activated if
3287     * necessary to ensure sufficient parallelism while the current
3288     * thread is blocked in {@link ManagedBlocker#block blocker.block()}.
3289 jsr166 1.1 *
3290 jsr166 1.217 * <p>This method repeatedly calls {@code blocker.isReleasable()} and
3291     * {@code blocker.block()} until either method returns {@code true}.
3292     * Every call to {@code blocker.block()} is preceded by a call to
3293     * {@code blocker.isReleasable()} that returned {@code false}.
3294     *
3295     * <p>If not running in a ForkJoinPool, this method is
3296 jsr166 1.8 * behaviorally equivalent to
3297 jsr166 1.239 * <pre> {@code
3298 jsr166 1.1 * while (!blocker.isReleasable())
3299     * if (blocker.block())
3300 jsr166 1.217 * break;}</pre>
3301 jsr166 1.8 *
3302 jsr166 1.217 * If running in a ForkJoinPool, the pool may first be expanded to
3303     * ensure sufficient parallelism available during the call to
3304     * {@code blocker.block()}.
3305 jsr166 1.1 *
3306 jsr166 1.217 * @param blocker the blocker task
3307     * @throws InterruptedException if {@code blocker.block()} did so
3308 jsr166 1.1 */
3309 dl 1.18 public static void managedBlock(ManagedBlocker blocker)
3310 jsr166 1.1 throws InterruptedException {
3311 dl 1.200 ForkJoinPool p;
3312     ForkJoinWorkerThread wt;
3313 jsr166 1.1 Thread t = Thread.currentThread();
3314 dl 1.200 if ((t instanceof ForkJoinWorkerThread) &&
3315     (p = (wt = (ForkJoinWorkerThread)t).pool) != null) {
3316     WorkQueue w = wt.workQueue;
3317 dl 1.172 while (!blocker.isReleasable()) {
3318 dl 1.200 if (p.tryCompensate(w)) {
3319 dl 1.105 try {
3320     do {} while (!blocker.isReleasable() &&
3321     !blocker.block());
3322     } finally {
3323 dl 1.200 U.getAndAddLong(p, CTL, AC_UNIT);
3324 dl 1.105 }
3325     break;
3326 dl 1.78 }
3327     }
3328 dl 1.18 }
3329 dl 1.105 else {
3330     do {} while (!blocker.isReleasable() &&
3331     !blocker.block());
3332     }
3333 jsr166 1.1 }
3334    
3335 jsr166 1.7 // AbstractExecutorService overrides. These rely on undocumented
3336     // fact that ForkJoinTask.adapt returns ForkJoinTasks that also
3337     // implement RunnableFuture.
3338 jsr166 1.1
3339     protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
3340 dl 1.90 return new ForkJoinTask.AdaptedRunnable<T>(runnable, value);
3341 jsr166 1.1 }
3342    
3343     protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
3344 dl 1.90 return new ForkJoinTask.AdaptedCallable<T>(callable);
3345 jsr166 1.1 }
3346    
3347     // Unsafe mechanics
3348 jsr166 1.233 private static final sun.misc.Unsafe U = sun.misc.Unsafe.getUnsafe();
3349 dl 1.200 private static final int ABASE;
3350     private static final int ASHIFT;
3351 dl 1.78 private static final long CTL;
3352 dl 1.211 private static final long RUNSTATE;
3353 dl 1.215 private static final long STEALCOUNTER;
3354 dl 1.78 private static final long PARKBLOCKER;
3355 dl 1.200 private static final long QTOP;
3356 dl 1.105 private static final long QLOCK;
3357 dl 1.200 private static final long QSCANSTATE;
3358     private static final long QPARKER;
3359     private static final long QCURRENTSTEAL;
3360     private static final long QCURRENTJOIN;
3361 dl 1.52
3362     static {
3363 jsr166 1.3 try {
3364 dl 1.78 CTL = U.objectFieldOffset
3365 jsr166 1.233 (ForkJoinPool.class.getDeclaredField("ctl"));
3366 dl 1.211 RUNSTATE = U.objectFieldOffset
3367 jsr166 1.233 (ForkJoinPool.class.getDeclaredField("runState"));
3368 dl 1.215 STEALCOUNTER = U.objectFieldOffset
3369 jsr166 1.233 (ForkJoinPool.class.getDeclaredField("stealCounter"));
3370    
3371 dl 1.78 PARKBLOCKER = U.objectFieldOffset
3372 jsr166 1.233 (Thread.class.getDeclaredField("parkBlocker"));
3373    
3374 dl 1.200 QTOP = U.objectFieldOffset
3375 jsr166 1.233 (WorkQueue.class.getDeclaredField("top"));
3376 dl 1.105 QLOCK = U.objectFieldOffset
3377 jsr166 1.233 (WorkQueue.class.getDeclaredField("qlock"));
3378 dl 1.200 QSCANSTATE = U.objectFieldOffset
3379 jsr166 1.233 (WorkQueue.class.getDeclaredField("scanState"));
3380 dl 1.200 QPARKER = U.objectFieldOffset
3381 jsr166 1.233 (WorkQueue.class.getDeclaredField("parker"));
3382 dl 1.200 QCURRENTSTEAL = U.objectFieldOffset
3383 jsr166 1.233 (WorkQueue.class.getDeclaredField("currentSteal"));
3384 dl 1.200 QCURRENTJOIN = U.objectFieldOffset
3385 jsr166 1.233 (WorkQueue.class.getDeclaredField("currentJoin"));
3386    
3387     ABASE = U.arrayBaseOffset(ForkJoinTask[].class);
3388     int scale = U.arrayIndexScale(ForkJoinTask[].class);
3389 jsr166 1.142 if ((scale & (scale - 1)) != 0)
3390 jsr166 1.232 throw new Error("array index scale not a power of two");
3391 jsr166 1.142 ASHIFT = 31 - Integer.numberOfLeadingZeros(scale);
3392 jsr166 1.231 } catch (ReflectiveOperationException e) {
3393 dl 1.52 throw new Error(e);
3394     }
3395 dl 1.105
3396 dl 1.208 commonMaxSpares = DEFAULT_COMMON_MAX_SPARES;
3397 dl 1.152 defaultForkJoinWorkerThreadFactory =
3398 dl 1.112 new DefaultForkJoinWorkerThreadFactory();
3399 dl 1.115 modifyThreadPermission = new RuntimePermission("modifyThread");
3400    
3401 dl 1.152 common = java.security.AccessController.doPrivileged
3402     (new java.security.PrivilegedAction<ForkJoinPool>() {
3403     public ForkJoinPool run() { return makeCommonPool(); }});
3404 dl 1.200 int par = common.config & SMASK; // report 1 even if threads disabled
3405 dl 1.160 commonParallelism = par > 0 ? par : 1;
3406 dl 1.152 }
3407 dl 1.112
3408 dl 1.152 /**
3409     * Creates and returns the common pool, respecting user settings
3410     * specified via system properties.
3411     */
3412     private static ForkJoinPool makeCommonPool() {
3413 dl 1.160 int parallelism = -1;
3414 dl 1.197 ForkJoinWorkerThreadFactory factory = null;
3415 jsr166 1.156 UncaughtExceptionHandler handler = null;
3416 jsr166 1.189 try { // ignore exceptions in accessing/parsing properties
3417 dl 1.112 String pp = System.getProperty
3418     ("java.util.concurrent.ForkJoinPool.common.parallelism");
3419 dl 1.152 String fp = System.getProperty
3420     ("java.util.concurrent.ForkJoinPool.common.threadFactory");
3421 dl 1.112 String hp = System.getProperty
3422     ("java.util.concurrent.ForkJoinPool.common.exceptionHandler");
3423 dl 1.208 String mp = System.getProperty
3424     ("java.util.concurrent.ForkJoinPool.common.maximumSpares");
3425 dl 1.152 if (pp != null)
3426     parallelism = Integer.parseInt(pp);
3427 dl 1.112 if (fp != null)
3428 dl 1.152 factory = ((ForkJoinWorkerThreadFactory)ClassLoader.
3429     getSystemClassLoader().loadClass(fp).newInstance());
3430 dl 1.112 if (hp != null)
3431 jsr166 1.156 handler = ((UncaughtExceptionHandler)ClassLoader.
3432 dl 1.112 getSystemClassLoader().loadClass(hp).newInstance());
3433 dl 1.208 if (mp != null)
3434     commonMaxSpares = Integer.parseInt(mp);
3435 dl 1.112 } catch (Exception ignore) {
3436     }
3437 dl 1.197 if (factory == null) {
3438     if (System.getSecurityManager() == null)
3439     factory = defaultForkJoinWorkerThreadFactory;
3440     else // use security-managed default
3441     factory = new InnocuousForkJoinWorkerThreadFactory();
3442     }
3443 dl 1.167 if (parallelism < 0 && // default 1 less than #cores
3444 dl 1.193 (parallelism = Runtime.getRuntime().availableProcessors() - 1) <= 0)
3445     parallelism = 1;
3446 dl 1.152 if (parallelism > MAX_CAP)
3447     parallelism = MAX_CAP;
3448 dl 1.185 return new ForkJoinPool(parallelism, factory, handler, LIFO_QUEUE,
3449 dl 1.152 "ForkJoinPool.commonPool-worker-");
3450 jsr166 1.3 }
3451 dl 1.52
3452 dl 1.197 /**
3453     * Factory for innocuous worker threads
3454     */
3455     static final class InnocuousForkJoinWorkerThreadFactory
3456     implements ForkJoinWorkerThreadFactory {
3457    
3458     /**
3459     * An ACC to restrict permissions for the factory itself.
3460     * The constructed workers have no permissions set.
3461     */
3462     private static final AccessControlContext innocuousAcc;
3463     static {
3464     Permissions innocuousPerms = new Permissions();
3465     innocuousPerms.add(modifyThreadPermission);
3466     innocuousPerms.add(new RuntimePermission(
3467     "enableContextClassLoaderOverride"));
3468     innocuousPerms.add(new RuntimePermission(
3469     "modifyThreadGroup"));
3470     innocuousAcc = new AccessControlContext(new ProtectionDomain[] {
3471     new ProtectionDomain(null, innocuousPerms)
3472     });
3473     }
3474    
3475     public final ForkJoinWorkerThread newThread(ForkJoinPool pool) {
3476 jsr166 1.227 return java.security.AccessController.doPrivileged(
3477     new java.security.PrivilegedAction<ForkJoinWorkerThread>() {
3478 dl 1.197 public ForkJoinWorkerThread run() {
3479     return new ForkJoinWorkerThread.
3480     InnocuousForkJoinWorkerThread(pool);
3481     }}, innocuousAcc);
3482     }
3483     }
3484    
3485 jsr166 1.1 }