ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinPool.java
Revision: 1.205
Committed: Tue Jul 8 14:17:09 2014 UTC (9 years, 11 months ago) by dl
Branch: MAIN
Changes since 1.204: +76 -58 lines
Log Message:
Compatibility with previous versions; more aggressive spare cleanup

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