ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinPool.java
Revision: 1.187
Committed: Thu May 23 01:10:42 2013 UTC (11 years ago) by jsr166
Branch: MAIN
Changes since 1.186: +3 -3 lines
Log Message:
whitespace

File Contents

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