ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinPool.java
Revision: 1.219
Committed: Thu Aug 28 18:41:29 2014 UTC (9 years, 9 months ago) by dl
Branch: MAIN
Changes since 1.218: +1 -10 lines
Log Message:
Minor cleanups

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