ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jdk7/java/util/concurrent/ForkJoinPool.java
Revision: 1.26
Committed: Fri Feb 27 07:03:36 2015 UTC (9 years, 3 months ago) by jsr166
Branch: MAIN
Changes since 1.25: +0 -8 lines
Log Message:
delete unused imports

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