ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinPool.java
Revision: 1.296
Committed: Sat Oct 24 15:53:53 2015 UTC (8 years, 7 months ago) by jsr166
Branch: MAIN
Changes since 1.295: +2 -1 lines
Log Message:
document ForkJoinWorkerThreadFactory#newThread null return

File Contents

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