ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinPool.java
Revision: 1.199
Committed: Sun May 25 02:33:45 2014 UTC (10 years ago) by jsr166
Branch: MAIN
Changes since 1.198: +1 -1 lines
Log Message:
time to start using diamond <>

File Contents

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