ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinPool.java
Revision: 1.394
Committed: Fri Feb 5 15:20:03 2021 UTC (3 years, 4 months ago) by dl
Branch: MAIN
Changes since 1.393: +34 -15 lines
Log Message:
Handle more cases for parallelism-0 and async shutdown

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