ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinPool.java
Revision: 1.156
Committed: Mon Feb 11 07:30:56 2013 UTC (11 years, 4 months ago) by jsr166
Branch: MAIN
Changes since 1.155: +13 -12 lines
Log Message:
import Thread.UncaughtExceptionHandler

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