ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinPool.java
Revision: 1.243
Committed: Wed Jul 22 18:50:10 2015 UTC (8 years, 10 months ago) by dl
Branch: MAIN
Changes since 1.242: +911 -953 lines
Log Message:
Initial candidate with improved async support

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