ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jsr166e/ForkJoinPool.java
Revision: 1.58
Committed: Wed Jun 19 14:55:40 2013 UTC (10 years, 11 months ago) by dl
Branch: MAIN
Changes since 1.57: +670 -757 lines
Log Message:
Sync with jdk8 versions

File Contents

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