ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinPool.java
Revision: 1.349
Committed: Mon Apr 9 20:22:25 2018 UTC (6 years, 1 month ago) by jsr166
Branch: MAIN
Changes since 1.348: +3 -3 lines
Log Message:
typo

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