ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinPool.java
Revision: 1.155
Committed: Mon Feb 11 07:16:59 2013 UTC (11 years, 4 months ago) by jsr166
Branch: MAIN
Changes since 1.154: +7 -6 lines
Log Message:
improve common pool javadoc

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