ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinPool.java
Revision: 1.196
Committed: Mon Dec 9 17:00:23 2013 UTC (10 years, 5 months ago) by jsr166
Branch: MAIN
Changes since 1.195: +1 -2 lines
Log Message:
use the one true code snippet style

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