ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinPool.java
Revision: 1.208
Committed: Wed Jul 9 15:30:36 2014 UTC (9 years, 11 months ago) by dl
Branch: MAIN
Changes since 1.207: +51 -30 lines
Log Message:
Allow max spares as System property

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