ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinPool.java
Revision: 1.378
Committed: Wed Aug 12 00:06:58 2020 UTC (3 years, 9 months ago) by jsr166
Branch: MAIN
Changes since 1.377: +0 -1 lines
Log Message:
fix errorprone [RemoveUnusedImports]

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 jsr166 1.1 * <p><b>Implementation notes</b>: This implementation restricts the
141     * 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    
766     public final ForkJoinWorkerThread newThread(ForkJoinPool pool) {
767     return AccessController.doPrivileged(
768     new PrivilegedAction<>() {
769     public ForkJoinWorkerThread run() {
770     return new ForkJoinWorkerThread(null, pool, true, false);
771     }},
772     ACC);
773     }
774     }
775    
776     /**
777     * Factory for InnocuousForkJoinWorkerThread. Support requires
778     * that we break quite a lot of encapsulation (some via helper
779     * methods in ThreadLocalRandom) to access and set Thread fields.
780     */
781     static final class InnocuousForkJoinWorkerThreadFactory
782 jsr166 1.1 implements ForkJoinWorkerThreadFactory {
783 dl 1.355 // ACC for access to the factory
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     new PrivilegedAction<>() {
794     public ForkJoinWorkerThread run() {
795 dl 1.355 return new ForkJoinWorkerThread.
796     InnocuousForkJoinWorkerThread(pool); }},
797 jsr166 1.331 ACC);
798 jsr166 1.1 }
799     }
800    
801 dl 1.200 // Constants shared across ForkJoinPool and WorkQueue
802    
803     // Bounds
804 dl 1.300 static final int SWIDTH = 16; // width of short
805 dl 1.200 static final int SMASK = 0xffff; // short bits == max index
806     static final int MAX_CAP = 0x7fff; // max #workers - 1
807    
808 dl 1.300 // Masks and units for WorkQueue.phase and ctl sp subfield
809 dl 1.243 static final int UNSIGNALLED = 1 << 31; // must be negative
810 dl 1.211 static final int SS_SEQ = 1 << 16; // version count
811 dl 1.200
812 dl 1.355 // Mode bits and sentinels, some also used in WorkQueue fields
813 dl 1.300 static final int FIFO = 1 << 16; // fifo queue or access mode
814 dl 1.355 static final int SRC = 1 << 17; // set for valid queue ids
815     static final int INNOCUOUS = 1 << 18; // set for Innocuous workers
816     static final int QUIET = 1 << 19; // quiescing phase or source
817     static final int SHUTDOWN = 1 << 24;
818     static final int TERMINATED = 1 << 25;
819 dl 1.300 static final int STOP = 1 << 31; // must be negative
820 dl 1.373 static final int UNCOMPENSATE = 1 << 16; // tryCompensate return
821 dl 1.300
822     /**
823 dl 1.355 * Initial capacity of work-stealing queue array. Must be a power
824     * of two, at least 2. See above.
825 dl 1.253 */
826 dl 1.355 static final int INITIAL_QUEUE_CAPACITY = 1 << 8;
827 dl 1.253
828     /**
829 dl 1.78 * Queues supporting work-stealing as well as external task
830 jsr166 1.202 * submission. See above for descriptions and algorithms.
831 dl 1.78 */
832     static final class WorkQueue {
833 dl 1.355 volatile int phase; // versioned, negative if inactive
834     int stackPred; // pool stack (ctl) predecessor link
835     int config; // index, mode, ORed with SRC after init
836 dl 1.345 int base; // index of next slot for poll
837     ForkJoinTask<?>[] array; // the queued tasks; power of 2 size
838 dl 1.78 final ForkJoinWorkerThread owner; // owning thread or null if shared
839 dl 1.112
840 dl 1.355 // segregate fields frequently updated but not read by scans or steals
841     @jdk.internal.vm.annotation.Contended("w")
842     int top; // index of next slot for push
843     @jdk.internal.vm.annotation.Contended("w")
844     volatile int source; // source queue id, lock, or sentinel
845     @jdk.internal.vm.annotation.Contended("w")
846     int nsteals; // number of steals from other queues
847    
848     // Support for atomic operations
849     private static final VarHandle QA; // for array slots
850     private static final VarHandle SOURCE;
851     private static final VarHandle BASE;
852     static final ForkJoinTask<?> getSlot(ForkJoinTask<?>[] a, int i) {
853     return (ForkJoinTask<?>)QA.getAcquire(a, i);
854     }
855     static final ForkJoinTask<?> getAndClearSlot(ForkJoinTask<?>[] a,
856     int i) {
857     return (ForkJoinTask<?>)QA.getAndSet(a, i, null);
858     }
859     static final void setSlotVolatile(ForkJoinTask<?>[] a, int i,
860     ForkJoinTask<?> v) {
861     QA.setVolatile(a, i, v);
862     }
863     static final boolean casSlotToNull(ForkJoinTask<?>[] a, int i,
864     ForkJoinTask<?> c) {
865     return QA.weakCompareAndSet(a, i, c, null);
866     }
867     final boolean tryLock() {
868     return SOURCE.compareAndSet(this, 0, 1);
869     }
870     final void setBaseOpaque(int b) {
871     BASE.setOpaque(this, b);
872 dl 1.78 }
873    
874     /**
875 dl 1.355 * Constructor used by ForkJoinWorkerThreads. Most fields
876     * are initialized upon thread start, in pool.registerWorker.
877 dl 1.345 */
878 dl 1.355 WorkQueue(ForkJoinWorkerThread owner, boolean isInnocuous) {
879     this.config = (isInnocuous) ? INNOCUOUS : 0;
880     this.owner = owner;
881 dl 1.345 }
882    
883 dl 1.355 /**
884     * Constructor used for external queues.
885     */
886     WorkQueue(int config) {
887     array = new ForkJoinTask<?>[INITIAL_QUEUE_CAPACITY];
888     this.config = config;
889     owner = null;
890     phase = -1;
891 dl 1.345 }
892    
893     /**
894 jsr166 1.220 * Returns an exportable index (used by ForkJoinWorkerThread).
895 dl 1.200 */
896     final int getPoolIndex() {
897 dl 1.355 return (config & 0xffff) >>> 1; // ignore odd/even tag bit
898 dl 1.200 }
899    
900     /**
901 dl 1.115 * Returns the approximate number of tasks in the queue.
902     */
903     final int queueSize() {
904 dl 1.355 VarHandle.acquireFence(); // ensure fresh reads by external callers
905     int n = top - base;
906     return (n < 0) ? 0 : n; // ignore transient negative
907 dl 1.115 }
908    
909 jsr166 1.180 /**
910 dl 1.366 * Provides a more conservative estimate of whether this queue
911     * has any tasks than does queueSize.
912 dl 1.115 */
913     final boolean isEmpty() {
914 dl 1.366 return !((source != 0 && owner == null) || top - base > 0);
915 dl 1.115 }
916    
917     /**
918 dl 1.256 * Pushes a task. Call only by owner in unshared queues.
919 dl 1.78 *
920     * @param task the task. Caller must ensure non-null.
921 dl 1.355 * @param pool (no-op if null)
922 jsr166 1.146 * @throws RejectedExecutionException if array cannot be resized
923 dl 1.78 */
924 dl 1.355 final void push(ForkJoinTask<?> task, ForkJoinPool pool) {
925     ForkJoinTask<?>[] a = array;
926     int s = top++, d = s - base, cap, m; // skip insert if disabled
927     if (a != null && pool != null && (cap = a.length) > 0) {
928     setSlotVolatile(a, (m = cap - 1) & s, task);
929 dl 1.353 if (d == m)
930 dl 1.355 growArray();
931     if (d == m || a[m & (s - 1)] == null)
932     pool.signalWork(); // signal if was empty or resized
933 dl 1.78 }
934     }
935    
936 dl 1.178 /**
937 dl 1.355 * Pushes task to a shared queue with lock already held, and unlocks.
938     *
939     * @return true if caller should signal work
940 dl 1.112 */
941 dl 1.345 final boolean lockedPush(ForkJoinTask<?> task) {
942 dl 1.355 ForkJoinTask<?>[] a = array;
943     int s = top++, d = s - base, cap, m;
944     if (a != null && (cap = a.length) > 0) {
945     a[(m = cap - 1) & s] = task;
946 dl 1.353 if (d == m)
947 dl 1.355 growArray();
948     source = 0; // unlock
949     if (d == m || a[m & (s - 1)] == null)
950     return true;
951 dl 1.345 }
952 dl 1.355 return false;
953 dl 1.78 }
954    
955     /**
956 dl 1.355 * Doubles the capacity of array. Called by owner or with lock
957     * held after pre-incrementing top, which is reverted on
958     * allocation failure.
959     */
960     final void growArray() {
961     ForkJoinTask<?>[] oldArray = array, newArray;
962     int s = top - 1, oldCap, newCap;
963     if (oldArray != null && (oldCap = oldArray.length) > 0 &&
964     (newCap = oldCap << 1) > 0) { // skip if disabled
965     try {
966     newArray = new ForkJoinTask<?>[newCap];
967     } catch (Throwable ex) {
968     top = s;
969     if (owner == null)
970     source = 0; // unlock
971     throw new RejectedExecutionException(
972     "Queue capacity exceeded");
973     }
974     int newMask = newCap - 1, oldMask = oldCap - 1;
975     for (int k = oldCap; k > 0; --k, --s) {
976     ForkJoinTask<?> x; // poll old, push to new
977     if ((x = getAndClearSlot(oldArray, s & oldMask)) == null)
978     break; // others already taken
979     newArray[s & newMask] = x;
980 dl 1.78 }
981 dl 1.355 VarHandle.releaseFence(); // fill before publish
982     array = newArray;
983 dl 1.78 }
984     }
985    
986 dl 1.355 // Variants of pop
987 dl 1.78
988     /**
989 dl 1.355 * Pops and returns task, or null if empty. Called only by owner.
990 dl 1.78 */
991 dl 1.355 private ForkJoinTask<?> pop() {
992 dl 1.345 ForkJoinTask<?> t = null;
993 dl 1.355 int s = top, cap; ForkJoinTask<?>[] a;
994     if ((a = array) != null && (cap = a.length) > 0 && base != s-- &&
995     (t = getAndClearSlot(a, (cap - 1) & s)) != null)
996     top = s;
997 dl 1.345 return t;
998 dl 1.78 }
999    
1000     /**
1001 dl 1.355 * Pops the given task for owner only if it is at the current top.
1002 dl 1.78 */
1003 dl 1.373 final boolean tryUnpush(ForkJoinTask<?> task) {
1004     int s = top, cap, k; ForkJoinTask<?>[] a;
1005     if ((a = array) != null && (cap = a.length) > 0 && base != s-- &&
1006     casSlotToNull(a, (cap - 1) & s, task)) {
1007     top = s;
1008     return true;
1009     }
1010     return false;
1011     }
1012    
1013     /**
1014     * Locking version of tryUnpush.
1015     */
1016     final boolean externalTryUnpush(ForkJoinTask<?> task) {
1017 dl 1.355 boolean taken = false;
1018     int s = top, cap, k; ForkJoinTask<?>[] a;
1019 dl 1.365 if ((a = array) != null && (cap = a.length) > 0 &&
1020 dl 1.373 a[k = (cap - 1) & (s - 1)] == task && tryLock()) {
1021     if (top == s && array == a &&
1022     (taken = casSlotToNull(a, k, task)))
1023     top = s - 1;
1024     source = 0; // release lock
1025 dl 1.355 }
1026     return taken;
1027 dl 1.345 }
1028    
1029     /**
1030 dl 1.365 * Deep form of tryUnpush: Traverses from top and removes task if
1031 dl 1.355 * present, shifting others to fill gap.
1032     */
1033 dl 1.365 final boolean tryRemove(ForkJoinTask<?> task, boolean owned) {
1034     boolean taken = false;
1035     int p = top, cap; ForkJoinTask<?>[] a; ForkJoinTask<?> t;
1036 dl 1.355 if ((a = array) != null && task != null && (cap = a.length) > 0) {
1037 dl 1.365 int m = cap - 1, s = p - 1, d = p - base;
1038     for (int i = s, k; d > 0; --i, --d) {
1039 dl 1.355 if ((t = a[k = i & m]) == task) {
1040 dl 1.365 if (owned || tryLock()) {
1041     if ((owned || (array == a && top == p)) &&
1042     (taken = casSlotToNull(a, k, t))) {
1043     for (int j = i; j != s; ) // shift down
1044     a[j & m] = getAndClearSlot(a, ++j & m);
1045     top = s;
1046     }
1047     if (!owned)
1048     source = 0;
1049     }
1050     break;
1051 dl 1.355 }
1052     }
1053 dl 1.78 }
1054 dl 1.365 return taken;
1055 dl 1.78 }
1056    
1057 dl 1.355 // variants of poll
1058    
1059 dl 1.78 /**
1060 dl 1.355 * Tries once to poll next task in FIFO order, failing on
1061     * inconsistency or contention.
1062 dl 1.78 */
1063 dl 1.355 final ForkJoinTask<?> tryPoll() {
1064     int cap, b, k; ForkJoinTask<?>[] a;
1065     if ((a = array) != null && (cap = a.length) > 0) {
1066     ForkJoinTask<?> t = getSlot(a, k = (cap - 1) & (b = base));
1067     if (base == b++ && t != null && casSlotToNull(a, k, t)) {
1068     setBaseOpaque(b);
1069     return t;
1070     }
1071     }
1072     return null;
1073 dl 1.78 }
1074    
1075     /**
1076 dl 1.355 * Takes next task, if one exists, in order specified by mode.
1077 dl 1.345 */
1078 dl 1.355 final ForkJoinTask<?> nextLocalTask(int cfg) {
1079     ForkJoinTask<?> t = null;
1080     int s = top, cap; ForkJoinTask<?>[] a;
1081     if ((a = array) != null && (cap = a.length) > 0) {
1082     for (int b, d;;) {
1083     if ((d = s - (b = base)) <= 0)
1084     break;
1085     if (d == 1 || (cfg & FIFO) == 0) {
1086     if ((t = getAndClearSlot(a, --s & (cap - 1))) != null)
1087     top = s;
1088     break;
1089 dl 1.353 }
1090 dl 1.355 if ((t = getAndClearSlot(a, b++ & (cap - 1))) != null) {
1091     setBaseOpaque(b);
1092 jsr166 1.352 break;
1093 dl 1.355 }
1094 jsr166 1.344 }
1095 dl 1.253 }
1096 dl 1.355 return t;
1097     }
1098    
1099     /**
1100     * Takes next task, if one exists, using configured mode.
1101     */
1102     final ForkJoinTask<?> nextLocalTask() {
1103     return nextLocalTask(config);
1104     }
1105    
1106     /**
1107     * Returns next task, if one exists, in order specified by mode.
1108     */
1109     final ForkJoinTask<?> peek() {
1110     VarHandle.acquireFence();
1111     int cap; ForkJoinTask<?>[] a;
1112     return ((a = array) != null && (cap = a.length) > 0) ?
1113     a[(cap - 1) & ((config & FIFO) != 0 ? base : top - 1)] : null;
1114 dl 1.253 }
1115    
1116 dl 1.355 // specialized execution methods
1117    
1118 dl 1.253 /**
1119 dl 1.355 * Runs the given (stolen) task if nonnull, as well as
1120     * remaining local tasks and/or others available from the
1121     * given queue.
1122 dl 1.94 */
1123 dl 1.355 final void topLevelExec(ForkJoinTask<?> task, WorkQueue q) {
1124     int cfg = config, nstolen = 1;
1125     while (task != null) {
1126     task.doExec();
1127     if ((task = nextLocalTask(cfg)) == null &&
1128     q != null && (task = q.tryPoll()) != null)
1129     ++nstolen;
1130 dl 1.215 }
1131 dl 1.355 nsteals += nstolen;
1132     source = 0;
1133     if ((cfg & INNOCUOUS) != 0)
1134     ThreadLocalRandom.eraseThreadLocals(Thread.currentThread());
1135 dl 1.215 }
1136    
1137     /**
1138 dl 1.345 * Tries to pop and run tasks within the target's computation
1139     * until done, not found, or limit exceeded.
1140 dl 1.94 *
1141 dl 1.300 * @param task root of CountedCompleter computation
1142 dl 1.355 * @param owned true if owned by a ForkJoinWorkerThread
1143 dl 1.300 * @param limit max runs, or zero for no limit
1144 jsr166 1.363 * @return task status on exit
1145 dl 1.300 */
1146 dl 1.365 final int helpComplete(ForkJoinTask<?> task, boolean owned, int limit) {
1147 dl 1.355 int status = 0, cap, k, p, s; ForkJoinTask<?>[] a; ForkJoinTask<?> t;
1148     while (task != null && (status = task.status) >= 0 &&
1149     (a = array) != null && (cap = a.length) > 0 &&
1150     (t = a[k = (cap - 1) & (s = (p = top) - 1)])
1151     instanceof CountedCompleter) {
1152     CountedCompleter<?> f = (CountedCompleter<?>)t;
1153     boolean taken = false;
1154     for (;;) { // exec if root task is a completer of t
1155     if (f == task) {
1156     if (owned) {
1157     if ((taken = casSlotToNull(a, k, t)))
1158     top = s;
1159     }
1160     else if (tryLock()) {
1161     if (top == p && array == a &&
1162     (taken = casSlotToNull(a, k, t)))
1163     top = s;
1164     source = 0;
1165 dl 1.243 }
1166 dl 1.355 break;
1167 dl 1.104 }
1168 dl 1.355 else if ((f = f.completer) == null)
1169 dl 1.300 break;
1170 dl 1.104 }
1171 dl 1.355 if (!taken)
1172     break;
1173     t.doExec();
1174     if (limit != 0 && --limit == 0)
1175     break;
1176 dl 1.104 }
1177 dl 1.300 return status;
1178     }
1179    
1180 jsr166 1.344 /**
1181 dl 1.345 * Tries to poll and run AsynchronousCompletionTasks until
1182 dl 1.355 * none found or blocker is released.
1183 dl 1.345 *
1184     * @param blocker the blocker
1185 jsr166 1.344 */
1186 dl 1.345 final void helpAsyncBlocker(ManagedBlocker blocker) {
1187 dl 1.355 int cap, b, d, k; ForkJoinTask<?>[] a; ForkJoinTask<?> t;
1188     while (blocker != null && (d = top - (b = base)) > 0 &&
1189     (a = array) != null && (cap = a.length) > 0 &&
1190     (((t = getSlot(a, k = (cap - 1) & b)) == null && d > 1) ||
1191     t instanceof
1192     CompletableFuture.AsynchronousCompletionTask) &&
1193     !blocker.isReleasable()) {
1194     if (t != null && base == b++ && casSlotToNull(a, k, t)) {
1195     setBaseOpaque(b);
1196     t.doExec();
1197 dl 1.178 }
1198 dl 1.78 }
1199     }
1200    
1201 dl 1.355 // misc
1202    
1203     /** AccessControlContext for innocuous workers, created on 1st use. */
1204     private static AccessControlContext INNOCUOUS_ACC;
1205    
1206     /**
1207     * Initializes (upon registration) InnocuousForkJoinWorkerThreads.
1208     */
1209     final void initializeInnocuousWorker() {
1210     AccessControlContext acc; // racy construction OK
1211     if ((acc = INNOCUOUS_ACC) == null)
1212     INNOCUOUS_ACC = acc = new AccessControlContext(
1213     new ProtectionDomain[] { new ProtectionDomain(null, null) });
1214     Thread t = Thread.currentThread();
1215     ThreadLocalRandom.setInheritedAccessControlContext(t, acc);
1216     ThreadLocalRandom.eraseThreadLocals(t);
1217     }
1218    
1219 dl 1.78 /**
1220 dl 1.373 * Returns true if owned by a worker thread and not known to be blocked.
1221 dl 1.86 */
1222     final boolean isApparentlyUnblocked() {
1223     Thread wt; Thread.State s;
1224 dl 1.300 return ((wt = owner) != null &&
1225 dl 1.86 (s = wt.getState()) != Thread.State.BLOCKED &&
1226     s != Thread.State.WAITING &&
1227     s != Thread.State.TIMED_WAITING);
1228     }
1229    
1230 dl 1.78 static {
1231     try {
1232 dl 1.355 QA = MethodHandles.arrayElementVarHandle(ForkJoinTask[].class);
1233 dl 1.314 MethodHandles.Lookup l = MethodHandles.lookup();
1234 dl 1.355 SOURCE = l.findVarHandle(WorkQueue.class, "source", int.class);
1235 dl 1.345 BASE = l.findVarHandle(WorkQueue.class, "base", int.class);
1236 jsr166 1.231 } catch (ReflectiveOperationException e) {
1237 jsr166 1.347 throw new ExceptionInInitializerError(e);
1238 dl 1.78 }
1239     }
1240     }
1241 dl 1.14
1242 dl 1.112 // static fields (initialized in static initializer below)
1243    
1244     /**
1245     * Creates a new ForkJoinWorkerThread. This factory is used unless
1246     * overridden in ForkJoinPool constructors.
1247     */
1248     public static final ForkJoinWorkerThreadFactory
1249     defaultForkJoinWorkerThreadFactory;
1250    
1251 jsr166 1.1 /**
1252 dl 1.115 * Permission required for callers of methods that may start or
1253 dl 1.300 * kill threads.
1254 dl 1.115 */
1255 jsr166 1.276 static final RuntimePermission modifyThreadPermission;
1256 dl 1.115
1257     /**
1258 dl 1.101 * Common (static) pool. Non-null for public use unless a static
1259 dl 1.105 * construction exception, but internal usages null-check on use
1260     * to paranoically avoid potential initialization circularities
1261     * as well as to simplify generated code.
1262 dl 1.101 */
1263 dl 1.134 static final ForkJoinPool common;
1264 dl 1.101
1265     /**
1266 dl 1.160 * Common pool parallelism. To allow simpler use and management
1267     * when common pool threads are disabled, we allow the underlying
1268 dl 1.185 * common.parallelism field to be zero, but in that case still report
1269 dl 1.160 * parallelism as 1 to reflect resulting caller-runs mechanics.
1270 dl 1.90 */
1271 jsr166 1.274 static final int COMMON_PARALLELISM;
1272 dl 1.90
1273     /**
1274 dl 1.208 * Limit on spare thread construction in tryCompensate.
1275     */
1276 jsr166 1.273 private static final int COMMON_MAX_SPARES;
1277 dl 1.208
1278     /**
1279 dl 1.355 * Sequence number for creating worker names
1280 dl 1.83 */
1281 dl 1.355 private static volatile int poolIds;
1282 dl 1.86
1283 dl 1.200 // static configuration constants
1284 dl 1.86
1285     /**
1286 dl 1.300 * Default idle timeout value (in milliseconds) for the thread
1287     * triggering quiescence to park waiting for new work
1288 dl 1.86 */
1289 jsr166 1.326 private static final long DEFAULT_KEEPALIVE = 60_000L;
1290 dl 1.86
1291     /**
1292 dl 1.300 * Undershoot tolerance for idle timeouts
1293 dl 1.120 */
1294 dl 1.300 private static final long TIMEOUT_SLOP = 20L;
1295 dl 1.200
1296     /**
1297 jsr166 1.273 * The default value for COMMON_MAX_SPARES. Overridable using the
1298     * "java.util.concurrent.ForkJoinPool.common.maximumSpares" system
1299     * property. The default value is far in excess of normal
1300     * requirements, but also far short of MAX_CAP and typical OS
1301     * thread limits, so allows JVMs to catch misuse/abuse before
1302     * running out of resources needed to do so.
1303 dl 1.200 */
1304 dl 1.208 private static final int DEFAULT_COMMON_MAX_SPARES = 256;
1305 dl 1.120
1306 jsr166 1.163 /*
1307 dl 1.200 * Bits and masks for field ctl, packed with 4 16 bit subfields:
1308 dl 1.300 * RC: Number of released (unqueued) workers minus target parallelism
1309 dl 1.200 * TC: Number of total workers minus target parallelism
1310     * SS: version count and status of top waiting thread
1311     * ID: poolIndex of top of Treiber stack of waiters
1312     *
1313     * When convenient, we can extract the lower 32 stack top bits
1314     * (including version bits) as sp=(int)ctl. The offsets of counts
1315     * by the target parallelism and the positionings of fields makes
1316     * it possible to perform the most common checks via sign tests of
1317 dl 1.300 * fields: When ac is negative, there are not enough unqueued
1318 dl 1.200 * workers, when tc is negative, there are not enough total
1319     * workers. When sp is non-zero, there are waiting workers. To
1320     * deal with possibly negative fields, we use casts in and out of
1321     * "short" and/or signed shifts to maintain signedness.
1322     *
1323 dl 1.355 * Because it occupies uppermost bits, we can add one release
1324     * count using getAndAdd of RC_UNIT, rather than CAS, when
1325     * returning from a blocked join. Other updates entail multiple
1326     * subfields and masking, requiring CAS.
1327 dl 1.300 *
1328     * The limits packed in field "bounds" are also offset by the
1329     * parallelism level to make them comparable to the ctl rc and tc
1330     * fields.
1331 dl 1.200 */
1332    
1333     // Lower and upper word masks
1334     private static final long SP_MASK = 0xffffffffL;
1335     private static final long UC_MASK = ~SP_MASK;
1336 dl 1.86
1337 dl 1.300 // Release counts
1338     private static final int RC_SHIFT = 48;
1339     private static final long RC_UNIT = 0x0001L << RC_SHIFT;
1340     private static final long RC_MASK = 0xffffL << RC_SHIFT;
1341 dl 1.200
1342     // Total counts
1343 dl 1.86 private static final int TC_SHIFT = 32;
1344 dl 1.200 private static final long TC_UNIT = 0x0001L << TC_SHIFT;
1345     private static final long TC_MASK = 0xffffL << TC_SHIFT;
1346     private static final long ADD_WORKER = 0x0001L << (TC_SHIFT + 15); // sign
1347    
1348 dl 1.300 // Instance fields
1349 dl 1.86
1350 dl 1.355 final long keepAlive; // milliseconds before dropping if idle
1351 dl 1.300 volatile long stealCount; // collects worker nsteals
1352 dl 1.355 int scanRover; // advances across pollScan calls
1353     volatile int threadIds; // for worker thread names
1354 dl 1.300 final int bounds; // min, max threads packed as shorts
1355     volatile int mode; // parallelism, runstate, queue mode
1356 dl 1.355 WorkQueue[] queues; // main registry
1357     final ReentrantLock registrationLock;
1358     Condition termination; // lazily constructed
1359     final String workerNamePrefix; // null for common pool
1360 dl 1.112 final ForkJoinWorkerThreadFactory factory;
1361 dl 1.200 final UncaughtExceptionHandler ueh; // per-worker UEH
1362 dl 1.307 final Predicate<? super ForkJoinPool> saturate;
1363 dl 1.101
1364 dl 1.308 @jdk.internal.vm.annotation.Contended("fjpctl") // segregate
1365     volatile long ctl; // main pool control
1366 jsr166 1.309
1367 dl 1.355 // Support for atomic operations
1368     private static final VarHandle CTL;
1369     private static final VarHandle MODE;
1370     private static final VarHandle THREADIDS;
1371     private static final VarHandle POOLIDS;
1372     private boolean compareAndSetCtl(long c, long v) {
1373     return CTL.compareAndSet(this, c, v);
1374     }
1375     private long compareAndExchangeCtl(long c, long v) {
1376     return (long)CTL.compareAndExchange(this, c, v);
1377     }
1378     private long getAndAddCtl(long v) {
1379     return (long)CTL.getAndAdd(this, v);
1380     }
1381     private int getAndBitwiseOrMode(int v) {
1382     return (int)MODE.getAndBitwiseOr(this, v);
1383     }
1384     private int getAndAddThreadIds(int x) {
1385     return (int)THREADIDS.getAndAdd(this, x);
1386     }
1387     private static int getAndAddPoolIds(int x) {
1388     return (int)POOLIDS.getAndAdd(x);
1389     }
1390    
1391 dl 1.200 // Creating, registering and deregistering workers
1392    
1393 dl 1.112 /**
1394 dl 1.200 * Tries to construct and start one worker. Assumes that total
1395     * count has already been incremented as a reservation. Invokes
1396     * deregisterWorker on any failure.
1397     *
1398     * @return true if successful
1399 dl 1.115 */
1400 dl 1.300 private boolean createWorker() {
1401 dl 1.200 ForkJoinWorkerThreadFactory fac = factory;
1402     Throwable ex = null;
1403     ForkJoinWorkerThread wt = null;
1404     try {
1405 dl 1.367 if (fac != null && (wt = fac.newThread(this)) != null) {
1406 dl 1.200 wt.start();
1407     return true;
1408 dl 1.115 }
1409 dl 1.200 } catch (Throwable rex) {
1410     ex = rex;
1411 dl 1.112 }
1412 dl 1.200 deregisterWorker(wt, ex);
1413     return false;
1414 dl 1.112 }
1415    
1416 dl 1.200 /**
1417 jsr166 1.360 * Provides a name for ForkJoinWorkerThread constructor.
1418 dl 1.200 */
1419 dl 1.355 final String nextWorkerThreadName() {
1420     String prefix = workerNamePrefix;
1421     int tid = getAndAddThreadIds(1) + 1;
1422     if (prefix == null) // commonPool has no prefix
1423     prefix = "ForkJoinPool.commonPool-worker-";
1424     return prefix.concat(Integer.toString(tid));
1425 dl 1.200 }
1426 dl 1.112
1427     /**
1428 dl 1.355 * Finishes initializing and records owned queue.
1429     *
1430     * @param w caller's WorkQueue
1431     */
1432     final void registerWorker(WorkQueue w) {
1433     ReentrantLock lock = registrationLock;
1434     ThreadLocalRandom.localInit();
1435     int seed = ThreadLocalRandom.getProbe();
1436     if (w != null && lock != null) {
1437     int modebits = (mode & FIFO) | w.config;
1438     w.array = new ForkJoinTask<?>[INITIAL_QUEUE_CAPACITY];
1439     w.stackPred = seed; // stash for runWorker
1440     if ((modebits & INNOCUOUS) != 0)
1441     w.initializeInnocuousWorker();
1442     int id = (seed << 1) | 1; // initial index guess
1443     lock.lock();
1444     try {
1445     WorkQueue[] qs; int n; // find queue index
1446     if ((qs = queues) != null && (n = qs.length) > 0) {
1447     int k = n, m = n - 1;
1448     for (; qs[id &= m] != null && k > 0; id -= 2, k -= 2);
1449     if (k == 0)
1450     id = n | 1; // resize below
1451     w.phase = w.config = id | modebits; // now publishable
1452 dl 1.300
1453 dl 1.355 if (id < n)
1454     qs[id] = w;
1455 dl 1.300 else { // expand array
1456 dl 1.355 int an = n << 1, am = an - 1;
1457 dl 1.300 WorkQueue[] as = new WorkQueue[an];
1458 dl 1.355 as[id & am] = w;
1459     for (int j = 1; j < n; j += 2)
1460     as[j] = qs[j];
1461     for (int j = 0; j < n; j += 2) {
1462     WorkQueue q;
1463     if ((q = qs[j]) != null) // shared queues may move
1464     as[q.config & am] = q;
1465 dl 1.94 }
1466 dl 1.355 VarHandle.releaseFence(); // fill before publish
1467     queues = as;
1468 dl 1.94 }
1469     }
1470 dl 1.355 } finally {
1471     lock.unlock();
1472 dl 1.78 }
1473     }
1474     }
1475 dl 1.19
1476 jsr166 1.1 /**
1477 dl 1.86 * Final callback from terminating worker, as well as upon failure
1478 dl 1.105 * to construct or start a worker. Removes record of worker from
1479     * array, and adjusts counts. If pool is shutting down, tries to
1480     * complete termination.
1481 dl 1.78 *
1482 jsr166 1.151 * @param wt the worker thread, or null if construction failed
1483 dl 1.78 * @param ex the exception causing failure, or null if none
1484 dl 1.45 */
1485 dl 1.78 final void deregisterWorker(ForkJoinWorkerThread wt, Throwable ex) {
1486 dl 1.355 ReentrantLock lock = registrationLock;
1487 dl 1.78 WorkQueue w = null;
1488 dl 1.355 int cfg = 0;
1489     if (wt != null && (w = wt.workQueue) != null && lock != null) {
1490     WorkQueue[] qs; int n, i;
1491     cfg = w.config;
1492     long ns = w.nsteals & 0xffffffffL;
1493     lock.lock(); // remove index from array
1494     if ((qs = queues) != null && (n = qs.length) > 0 &&
1495     qs[i = cfg & (n - 1)] == w)
1496     qs[i] = null;
1497     stealCount += ns; // accumulate steals
1498     lock.unlock();
1499     long c = ctl;
1500     if (w.phase != QUIET) // decrement counts
1501     do {} while (c != (c = compareAndExchangeCtl(
1502     c, ((RC_MASK & (c - RC_UNIT)) |
1503     (TC_MASK & (c - TC_UNIT)) |
1504     (SP_MASK & c)))));
1505     else if ((int)c == 0) // was dropped on timeout
1506     cfg = 0; // suppress signal if last
1507     for (ForkJoinTask<?> t; (t = w.pop()) != null; )
1508     ForkJoinTask.cancelIgnoringExceptions(t); // cancel tasks
1509 dl 1.243 }
1510 dl 1.300
1511 dl 1.355 if (!tryTerminate(false, false) && w != null && (cfg & SRC) != 0)
1512     signalWork(); // possibly replace worker
1513     if (ex != null)
1514 dl 1.104 ForkJoinTask.rethrow(ex);
1515 dl 1.78 }
1516 dl 1.52
1517 dl 1.355 /*
1518 dl 1.300 * Tries to create or release a worker if too few are running.
1519 dl 1.105 */
1520 dl 1.355 final void signalWork() {
1521     for (long c = ctl; c < 0L;) {
1522     int sp, i; WorkQueue[] qs; WorkQueue v;
1523     if ((sp = (int)c & ~UNSIGNALLED) == 0) { // no idle workers
1524     if ((c & ADD_WORKER) == 0L) // enough total workers
1525     break;
1526     if (c == (c = compareAndExchangeCtl(
1527     c, ((RC_MASK & (c + RC_UNIT)) |
1528     (TC_MASK & (c + TC_UNIT)))))) {
1529     createWorker();
1530     break;
1531     }
1532 dl 1.200 }
1533 dl 1.355 else if ((qs = queues) == null)
1534 dl 1.243 break; // unstarted/terminated
1535 dl 1.355 else if (qs.length <= (i = sp & SMASK))
1536 dl 1.243 break; // terminated
1537 dl 1.355 else if ((v = qs[i]) == null)
1538 dl 1.243 break; // terminating
1539     else {
1540 dl 1.300 long nc = (v.stackPred & SP_MASK) | (UC_MASK & (c + RC_UNIT));
1541     Thread vt = v.owner;
1542 dl 1.355 if (c == (c = compareAndExchangeCtl(c, nc))) {
1543     v.phase = sp;
1544     LockSupport.unpark(vt); // release idle worker
1545 dl 1.243 break;
1546     }
1547 dl 1.174 }
1548 dl 1.52 }
1549 dl 1.14 }
1550    
1551 dl 1.200 /**
1552 dl 1.355 * Top-level runloop for workers, called by ForkJoinWorkerThread.run.
1553     * See above for explanation.
1554 dl 1.243 *
1555 dl 1.355 * @param w caller's WorkQueue (may be null on failed initialization)
1556 dl 1.243 */
1557 dl 1.355 final void runWorker(WorkQueue w) {
1558     if (w != null) { // skip on failed init
1559     w.config |= SRC; // mark as valid source
1560     int r = w.stackPred, src = 0; // use seed from registerWorker
1561     do {
1562     r ^= r << 13; r ^= r >>> 17; r ^= r << 5; // xorshift
1563     } while ((src = scan(w, src, r)) >= 0 ||
1564     (src = awaitWork(w)) == 0);
1565     }
1566     }
1567    
1568     /**
1569     * Scans for and if found executes top-level tasks: Tries to poll
1570     * each queue starting at a random index with random stride,
1571     * returning source id or retry indicator if contended or
1572     * inconsistent.
1573     *
1574     * @param w caller's WorkQueue
1575     * @param prevSrc the previous queue stolen from in current phase, or 0
1576     * @param r random seed
1577     * @return id of queue if taken, negative if none found, prevSrc for retry
1578     */
1579     private int scan(WorkQueue w, int prevSrc, int r) {
1580     WorkQueue[] qs = queues;
1581     int n = (w == null || qs == null) ? 0 : qs.length;
1582     for (int step = (r >>> 16) | 1, i = n; i > 0; --i, r += step) {
1583     int j, cap, b; WorkQueue q; ForkJoinTask<?>[] a;
1584     if ((q = qs[j = r & (n - 1)]) != null && // poll at qs[j].array[k]
1585     (a = q.array) != null && (cap = a.length) > 0) {
1586     int k = (cap - 1) & (b = q.base), nextBase = b + 1;
1587     int nextIndex = (cap - 1) & nextBase, src = j | SRC;
1588     ForkJoinTask<?> t = WorkQueue.getSlot(a, k);
1589     if (q.base != b) // inconsistent
1590     return prevSrc;
1591     else if (t != null && WorkQueue.casSlotToNull(a, k, t)) {
1592     q.base = nextBase;
1593     ForkJoinTask<?> next = a[nextIndex];
1594     if ((w.source = src) != prevSrc && next != null)
1595     signalWork(); // propagate
1596     w.topLevelExec(t, q);
1597     return src;
1598     }
1599     else if (a[nextIndex] != null) // revisit
1600     return prevSrc;
1601     }
1602     }
1603     return (queues != qs) ? prevSrc: -1; // possibly resized
1604     }
1605    
1606     /**
1607     * Advances worker phase, pushes onto ctl stack, and awaits signal
1608     * or reports termination.
1609     *
1610     * @return negative if terminated, else 0
1611     */
1612     private int awaitWork(WorkQueue w) {
1613     if (w == null)
1614     return -1; // already terminated
1615 dl 1.371 int phase = (w.phase + SS_SEQ) & ~UNSIGNALLED;
1616     w.phase = phase | UNSIGNALLED; // advance phase
1617 dl 1.355 long prevCtl = ctl, c; // enqueue
1618     do {
1619     w.stackPred = (int)prevCtl;
1620     c = ((prevCtl - RC_UNIT) & UC_MASK) | (phase & SP_MASK);
1621     } while (prevCtl != (prevCtl = compareAndExchangeCtl(prevCtl, c)));
1622    
1623 dl 1.373 Thread.interrupted(); // clear status
1624 dl 1.355 LockSupport.setCurrentBlocker(this); // prepare to block (exit also OK)
1625 dl 1.371 long deadline = 0L; // nonzero if possibly quiescent
1626 dl 1.372 int ac = (int)(c >> RC_SHIFT), md;
1627     if ((md = mode) < 0) // pool is terminating
1628     return -1;
1629     else if ((md & SMASK) + ac <= 0) {
1630     boolean checkTermination = (md & SHUTDOWN) != 0;
1631 dl 1.355 if ((deadline = System.currentTimeMillis() + keepAlive) == 0L)
1632     deadline = 1L; // avoid zero
1633     WorkQueue[] qs = queues; // check for racing submission
1634 dl 1.372 int n = (qs == null) ? 0 : qs.length;
1635 dl 1.355 for (int i = 0; i < n; i += 2) {
1636 dl 1.372 WorkQueue q; ForkJoinTask<?>[] a; int cap, b;
1637     if (ctl != c) { // already signalled
1638     checkTermination = false;
1639     break;
1640     }
1641     else if ((q = qs[i]) != null &&
1642     (a = q.array) != null && (cap = a.length) > 0 &&
1643     ((b = q.base) != q.top || a[(cap - 1) & b] != null ||
1644     q.source != 0)) {
1645     if (compareAndSetCtl(c, prevCtl))
1646     w.phase = phase; // self-signal
1647     checkTermination = false;
1648 dl 1.366 break;
1649 dl 1.300 }
1650     }
1651 dl 1.372 if (checkTermination && tryTerminate(false, false))
1652     return -1; // trigger quiescent termination
1653 dl 1.355 }
1654 dl 1.372
1655 dl 1.373 for (boolean alt = false;;) { // await activation or termination
1656     if (w.phase >= 0)
1657     break;
1658 dl 1.372 else if (mode < 0)
1659     return -1;
1660 dl 1.373 else if ((int)(ctl >> RC_SHIFT) > ac)
1661 jsr166 1.376 Thread.onSpinWait(); // signal in progress
1662 dl 1.373 else if (!(alt = !alt)) { // check between park calls
1663     if (!Thread.interrupted() && deadline != 0L &&
1664     deadline - System.currentTimeMillis() <= TIMEOUT_SLOP &&
1665     compareAndSetCtl(c, ((UC_MASK & (c - TC_UNIT)) |
1666     (w.stackPred & SP_MASK)))) {
1667     w.phase = QUIET;
1668     return -1; // drop on timeout
1669     }
1670 dl 1.177 }
1671 dl 1.373 else if (deadline != 0L)
1672     LockSupport.parkUntil(deadline);
1673     else
1674     LockSupport.park();
1675 dl 1.243 }
1676 dl 1.373 LockSupport.setCurrentBlocker(null);
1677     return 0;
1678 dl 1.355 }
1679 dl 1.300
1680 dl 1.366 // Utilities used by ForkJoinTask
1681    
1682     /**
1683     * Returns true if all workers are busy
1684     */
1685     final boolean isSaturated() {
1686     long c;
1687     return (int)((c = ctl) >> RC_SHIFT) >= 0 && ((int)c & ~UNSIGNALLED) == 0;
1688     }
1689    
1690     /**
1691     * Returns true if can start terminating if enabled, or already terminated
1692     */
1693     final boolean canStop() {
1694     outer: for (long oldSum = 0L;;) { // repeat until stable
1695 dl 1.373 int md; WorkQueue[] qs; long c;
1696     if ((qs = queues) == null || ((md = mode) & STOP) != 0)
1697 dl 1.366 return true;
1698 dl 1.373 if ((md & SMASK) + (int)((c = ctl) >> RC_SHIFT) > 0)
1699 dl 1.366 break;
1700 dl 1.373 long checkSum = c;
1701 dl 1.372 for (int i = 1; i < qs.length; i += 2) { // scan submitters
1702 dl 1.373 WorkQueue q; ForkJoinTask<?>[] a; int s = 0, cap;
1703     if ((q = qs[i]) != null && (a = q.array) != null &&
1704     (cap = a.length) > 0 &&
1705     ((s = q.top) != q.base || a[(cap - 1) & s] != null ||
1706     q.source != 0))
1707 dl 1.366 break outer;
1708 dl 1.373 checkSum += (((long)i) << 32) ^ s;
1709 dl 1.366 }
1710 dl 1.367 if (oldSum == (oldSum = checkSum) && queues == qs)
1711 dl 1.366 return true;
1712     }
1713     return (mode & STOP) != 0; // recheck mode on false return
1714     }
1715    
1716 dl 1.355 /**
1717     * Tries to decrement counts (sometimes implicitly) and possibly
1718     * arrange for a compensating worker in preparation for
1719     * blocking. May fail due to interference, in which case -1 is
1720     * returned so caller may retry. A zero return value indicates
1721     * that the caller doesn't need to re-adjust counts when later
1722     * unblocked.
1723     *
1724     * @param c incoming ctl value
1725 dl 1.373 * @return UNCOMPENSATE: block then adjust, 0: block, -1 : retry
1726 dl 1.355 */
1727     private int tryCompensate(long c) {
1728     Predicate<? super ForkJoinPool> sat;
1729     int b = bounds; // counts are signed; centered at parallelism level == 0
1730     int minActive = (short)(b & SMASK),
1731     maxTotal = b >>> SWIDTH,
1732     active = (int)(c >> RC_SHIFT),
1733 dl 1.366 total = (short)(c >>> TC_SHIFT),
1734     sp = (int)c & ~UNSIGNALLED;
1735     if (total >= 0) {
1736     if (sp != 0) { // activate idle worker
1737     WorkQueue[] qs; int n; WorkQueue v;
1738     if ((qs = queues) != null && (n = qs.length) > 0 &&
1739     (v = qs[sp & (n - 1)]) != null) {
1740     Thread vt = v.owner;
1741     long nc = ((long)v.stackPred & SP_MASK) | (UC_MASK & c);
1742     if (compareAndSetCtl(c, nc)) {
1743     v.phase = sp;
1744     LockSupport.unpark(vt);
1745 dl 1.373 return UNCOMPENSATE;
1746 dl 1.366 }
1747 dl 1.355 }
1748 dl 1.366 return -1; // retry
1749     }
1750     else if (active > minActive) { // reduce parallelism
1751     long nc = ((RC_MASK & (c - RC_UNIT)) | (~RC_MASK & c));
1752 dl 1.373 return compareAndSetCtl(c, nc) ? UNCOMPENSATE : -1;
1753 dl 1.355 }
1754     }
1755 dl 1.366 if (total < maxTotal) { // expand pool
1756 dl 1.355 long nc = ((c + TC_UNIT) & TC_MASK) | (c & ~TC_MASK);
1757 dl 1.373 return (!compareAndSetCtl(c, nc) ? -1 :
1758     !createWorker() ? 0 : UNCOMPENSATE);
1759 dl 1.355 }
1760 dl 1.366 else if (!compareAndSetCtl(c, c)) // validate
1761 dl 1.355 return -1;
1762     else if ((sat = saturate) != null && sat.test(this))
1763     return 0;
1764     else
1765     throw new RejectedExecutionException(
1766     "Thread limit exceeded replacing blocked worker");
1767     }
1768    
1769     /**
1770     * Readjusts RC count; called from ForkJoinTask after blocking.
1771     */
1772     final void uncompensate() {
1773     getAndAddCtl(RC_UNIT);
1774 dl 1.243 }
1775    
1776     /**
1777 dl 1.355 * Helps if possible until the given task is done. Scans other
1778     * queues for a task produced by one of w's stealers; returning
1779     * compensated blocking sentinel if none are found.
1780 dl 1.345 *
1781 dl 1.355 * @param task the task
1782     * @param w caller's WorkQueue
1783 dl 1.373 * @return task status on exit, or UNCOMPENSATE for compensated blocking
1784 dl 1.355 */
1785     final int helpJoin(ForkJoinTask<?> task, WorkQueue w) {
1786     int s = 0;
1787     if (task != null && w != null) {
1788     int wsrc = w.source, wid = w.config & SMASK, r = wid + 2;
1789     boolean scan = true;
1790     long c = 0L; // track ctl stability
1791     outer: for (;;) {
1792     if ((s = task.status) < 0)
1793     break;
1794 dl 1.375 else if (scan = !scan) { // previous scan was empty
1795 dl 1.372 if (mode < 0)
1796     ForkJoinTask.cancelIgnoringExceptions(task);
1797 dl 1.375 else if (c == (c = ctl) && (s = tryCompensate(c)) >= 0)
1798 dl 1.355 break; // block
1799     }
1800     else { // scan for subtasks
1801     WorkQueue[] qs = queues;
1802     int n = (qs == null) ? 0 : qs.length, m = n - 1;
1803     for (int i = n; i > 0; i -= 2, r += 2) {
1804     int j; WorkQueue q, x, y; ForkJoinTask<?>[] a;
1805     if ((q = qs[j = r & m]) != null) {
1806     int sq = q.source & SMASK, cap, b;
1807     if ((a = q.array) != null && (cap = a.length) > 0) {
1808     int k = (cap - 1) & (b = q.base);
1809     int nextBase = b + 1, src = j | SRC, sx;
1810     ForkJoinTask<?> t = WorkQueue.getSlot(a, k);
1811     boolean eligible = sq == wid ||
1812     ((x = qs[sq & m]) != null && // indirect
1813     ((sx = (x.source & SMASK)) == wid ||
1814     ((y = qs[sx & m]) != null && // 2-indirect
1815     (y.source & SMASK) == wid)));
1816     if ((s = task.status) < 0)
1817     break outer;
1818     else if ((q.source & SMASK) != sq ||
1819     q.base != b)
1820     scan = true; // inconsistent
1821     else if (t == null)
1822     scan |= (a[nextBase & (cap - 1)] != null ||
1823     q.top != b); // lagging
1824     else if (eligible) {
1825     if (WorkQueue.casSlotToNull(a, k, t)) {
1826     q.base = nextBase;
1827     w.source = src;
1828     t.doExec();
1829     w.source = wsrc;
1830     }
1831     scan = true;
1832     break;
1833     }
1834     }
1835 dl 1.300 }
1836     }
1837     }
1838     }
1839     }
1840 dl 1.355 return s;
1841 dl 1.300 }
1842 dl 1.200
1843 dl 1.305 /**
1844 dl 1.366 * Extra helpJoin steps for CountedCompleters. Scans for and runs
1845     * subtasks of the given root task, returning if none are found.
1846 jsr166 1.356 *
1847 dl 1.355 * @param task root of CountedCompleter computation
1848     * @param w caller's WorkQueue
1849 dl 1.365 * @param owned true if owned by a ForkJoinWorkerThread
1850 dl 1.366 * @return task status on exit
1851 dl 1.305 */
1852 dl 1.365 final int helpComplete(ForkJoinTask<?> task, WorkQueue w, boolean owned) {
1853 dl 1.300 int s = 0;
1854 dl 1.355 if (task != null && w != null) {
1855     int r = w.config;
1856 dl 1.365 boolean scan = true, locals = true;
1857 dl 1.355 long c = 0L;
1858     outer: for (;;) {
1859     if (locals) { // try locals before scanning
1860     if ((s = w.helpComplete(task, owned, 0)) < 0)
1861 dl 1.345 break;
1862 dl 1.355 locals = false;
1863 dl 1.300 }
1864 dl 1.355 else if ((s = task.status) < 0)
1865 dl 1.300 break;
1866 dl 1.375 else if (scan = !scan) {
1867     if (c == (c = ctl))
1868     break;
1869     }
1870 dl 1.355 else { // scan for subtasks
1871     WorkQueue[] qs = queues;
1872     int n = (qs == null) ? 0 : qs.length;
1873     for (int i = n; i > 0; --i, ++r) {
1874     int j, cap, b; WorkQueue q; ForkJoinTask<?>[] a;
1875     boolean eligible = false;
1876     if ((q = qs[j = r & (n - 1)]) != null &&
1877     (a = q.array) != null && (cap = a.length) > 0) {
1878     int k = (cap - 1) & (b = q.base), nextBase = b + 1;
1879     ForkJoinTask<?> t = WorkQueue.getSlot(a, k);
1880     if (t instanceof CountedCompleter) {
1881     CountedCompleter<?> f = (CountedCompleter<?>)t;
1882     do {} while (!(eligible = (f == task)) &&
1883     (f = f.completer) != null);
1884     }
1885     if ((s = task.status) < 0)
1886     break outer;
1887     else if (q.base != b)
1888     scan = true; // inconsistent
1889     else if (t == null)
1890     scan |= (a[nextBase & (cap - 1)] != null ||
1891     q.top != b);
1892     else if (eligible) {
1893     if (WorkQueue.casSlotToNull(a, k, t)) {
1894     q.setBaseOpaque(nextBase);
1895     t.doExec();
1896     locals = true;
1897     }
1898     scan = true;
1899     break;
1900     }
1901     }
1902 dl 1.200 }
1903     }
1904 dl 1.178 }
1905     }
1906 dl 1.200 return s;
1907 dl 1.120 }
1908    
1909     /**
1910 dl 1.355 * Scans for and returns a polled task, if available. Used only
1911     * for untracked polls. Begins scan at an index (scanRover)
1912     * advanced on each call, to avoid systematic unfairness.
1913 dl 1.105 *
1914 dl 1.300 * @param submissionsOnly if true, only scan submission queues
1915 dl 1.19 */
1916 dl 1.300 private ForkJoinTask<?> pollScan(boolean submissionsOnly) {
1917 dl 1.355 VarHandle.acquireFence();
1918     int r = scanRover += 0x61c88647; // Weyl increment; raciness OK
1919     if (submissionsOnly) // even indices only
1920     r &= ~1;
1921     int step = (submissionsOnly) ? 2 : 1;
1922     WorkQueue[] qs; int n;
1923     while ((qs = queues) != null && (n = qs.length) > 0) {
1924     boolean scan = false;
1925     for (int i = 0; i < n; i += step) {
1926     int j, cap, b; WorkQueue q; ForkJoinTask<?>[] a;
1927     if ((q = qs[j = (n - 1) & (r + i)]) != null &&
1928     (a = q.array) != null && (cap = a.length) > 0) {
1929     int k = (cap - 1) & (b = q.base), nextBase = b + 1;
1930     ForkJoinTask<?> t = WorkQueue.getSlot(a, k);
1931     if (q.base != b)
1932     scan = true;
1933     else if (t == null)
1934     scan |= (q.top != b || a[nextBase & (cap - 1)] != null);
1935     else if (!WorkQueue.casSlotToNull(a, k, t))
1936     scan = true;
1937     else {
1938     q.setBaseOpaque(nextBase);
1939     return t;
1940 dl 1.300 }
1941 dl 1.178 }
1942 dl 1.52 }
1943 dl 1.355 if (!scan && queues == qs)
1944     break;
1945 dl 1.90 }
1946 dl 1.300 return null;
1947     }
1948    
1949     /**
1950 dl 1.366 * Runs tasks until {@code isQuiescent()}. Rather than blocking
1951     * when tasks cannot be found, rescans until all others cannot
1952     * find tasks either.
1953     *
1954     * @param nanos max wait time (Long.MAX_VALUE if effectively untimed)
1955     * @param interruptible true if return on interrupt
1956     * @return positive if quiescent, negative if interrupted, else 0
1957     */
1958     final int helpQuiescePool(WorkQueue w, long nanos, boolean interruptible) {
1959     if (w == null)
1960     return 0;
1961     long startTime = System.nanoTime(), parkTime = 0L;
1962     int prevSrc = w.source, wsrc = prevSrc, cfg = w.config, r = cfg + 1;
1963     for (boolean active = true, locals = true;;) {
1964     boolean busy = false, scan = false;
1965     if (locals) { // run local tasks before (re)polling
1966     locals = false;
1967     for (ForkJoinTask<?> u; (u = w.nextLocalTask(cfg)) != null;)
1968     u.doExec();
1969     }
1970     WorkQueue[] qs = queues;
1971     int n = (qs == null) ? 0 : qs.length;
1972     for (int i = n; i > 0; --i, ++r) {
1973     int j, b, cap; WorkQueue q; ForkJoinTask<?>[] a;
1974     if ((q = qs[j = (n - 1) & r]) != null && q != w &&
1975     (a = q.array) != null && (cap = a.length) > 0) {
1976     int k = (cap - 1) & (b = q.base);
1977     int nextBase = b + 1, src = j | SRC;
1978     ForkJoinTask<?> t = WorkQueue.getSlot(a, k);
1979     if (q.base != b)
1980     busy = scan = true;
1981     else if (t != null) {
1982     busy = scan = true;
1983     if (!active) { // increment before taking
1984     active = true;
1985     getAndAddCtl(RC_UNIT);
1986     }
1987     if (WorkQueue.casSlotToNull(a, k, t)) {
1988     q.base = nextBase;
1989     w.source = src;
1990     t.doExec();
1991     w.source = wsrc = prevSrc;
1992     locals = true;
1993     }
1994     break;
1995     }
1996     else if (!busy) {
1997     if (q.top != b || a[nextBase & (cap - 1)] != null)
1998     busy = scan = true;
1999     else if (q.source != QUIET && q.phase >= 0)
2000     busy = true;
2001     }
2002     }
2003     }
2004     VarHandle.acquireFence();
2005     if (!scan && queues == qs) {
2006     boolean interrupted;
2007     if (!busy) {
2008     w.source = prevSrc;
2009     if (!active)
2010     getAndAddCtl(RC_UNIT);
2011     return 1;
2012     }
2013     if (wsrc != QUIET)
2014     w.source = wsrc = QUIET;
2015     if (active) { // decrement
2016     active = false;
2017     parkTime = 0L;
2018     getAndAddCtl(RC_MASK & -RC_UNIT);
2019     }
2020     else if (parkTime == 0L) {
2021     parkTime = 1L << 10; // initially about 1 usec
2022     Thread.yield();
2023     }
2024     else if ((interrupted = interruptible && Thread.interrupted()) ||
2025     System.nanoTime() - startTime > nanos) {
2026     getAndAddCtl(RC_UNIT);
2027     return interrupted ? -1 : 0;
2028     }
2029     else {
2030     LockSupport.parkNanos(this, parkTime);
2031     if (parkTime < nanos >>> 8 && parkTime < 1L << 20)
2032     parkTime <<= 1; // max sleep approx 1 sec or 1% nanos
2033     }
2034     }
2035     }
2036     }
2037    
2038     /**
2039     * Helps quiesce from external caller until done, interrupted, or timeout
2040     *
2041     * @param nanos max wait time (Long.MAX_VALUE if effectively untimed)
2042     * @param interruptible true if return on interrupt
2043     * @return positive if quiescent, negative if interrupted, else 0
2044     */
2045     final int externalHelpQuiescePool(long nanos, boolean interruptible) {
2046     for (long startTime = System.nanoTime(), parkTime = 0L;;) {
2047     ForkJoinTask<?> t;
2048     if ((t = pollScan(false)) != null) {
2049     t.doExec();
2050     parkTime = 0L;
2051     }
2052     else if (canStop())
2053     return 1;
2054     else if (parkTime == 0L) {
2055     parkTime = 1L << 10;
2056     Thread.yield();
2057     }
2058     else if ((System.nanoTime() - startTime) > nanos)
2059     return 0;
2060     else if (interruptible && Thread.interrupted())
2061     return -1;
2062     else {
2063     LockSupport.parkNanos(this, parkTime);
2064     if (parkTime < nanos >>> 8 && parkTime < 1L << 20)
2065     parkTime <<= 1;
2066     }
2067     }
2068     }
2069    
2070     /**
2071 dl 1.300 * Gets and removes a local or stolen task for the given worker.
2072     *
2073     * @return a task, if available
2074     */
2075     final ForkJoinTask<?> nextTaskFor(WorkQueue w) {
2076     ForkJoinTask<?> t;
2077 dl 1.355 if (w == null || (t = w.nextLocalTask(w.config)) == null)
2078 dl 1.345 t = pollScan(false);
2079     return t;
2080 dl 1.90 }
2081    
2082 dl 1.300 // External operations
2083    
2084 dl 1.90 /**
2085 dl 1.355 * Finds and locks a WorkQueue for an external submitter, or
2086     * returns null if shutdown or terminating.
2087 dl 1.90 */
2088 dl 1.355 final WorkQueue submissionQueue() {
2089     int r;
2090 dl 1.300 if ((r = ThreadLocalRandom.getProbe()) == 0) {
2091 dl 1.355 ThreadLocalRandom.localInit(); // initialize caller's probe
2092 dl 1.300 r = ThreadLocalRandom.getProbe();
2093     }
2094 dl 1.355 for (int id = r << 1;;) { // even indices only
2095     int md = mode, n, i; WorkQueue q; ReentrantLock lock;
2096     WorkQueue[] qs = queues;
2097     if ((md & SHUTDOWN) != 0 || qs == null || (n = qs.length) <= 0)
2098     return null;
2099     else if ((q = qs[i = (n - 1) & id]) == null) {
2100     if ((lock = registrationLock) != null) {
2101     WorkQueue w = new WorkQueue(id | SRC);
2102     lock.lock(); // install under lock
2103     if (qs[i] == null)
2104     qs[i] = w; // else lost race; discard
2105     lock.unlock();
2106 dl 1.300 }
2107 dl 1.345 }
2108 dl 1.355 else if (!q.tryLock()) // move and restart
2109     id = (r = ThreadLocalRandom.advanceProbe(r)) << 1;
2110     else
2111     return q;
2112 dl 1.90 }
2113     }
2114    
2115 dl 1.300 /**
2116 dl 1.355 * Adds the given task to an external submission queue, or throws
2117 jsr166 1.361 * exception if shutdown or terminating.
2118 dl 1.355 *
2119     * @param task the task. Caller must ensure non-null.
2120     */
2121     final void externalPush(ForkJoinTask<?> task) {
2122     WorkQueue q;
2123     if ((q = submissionQueue()) == null)
2124     throw new RejectedExecutionException(); // shutdown or disabled
2125     else if (q.lockedPush(task))
2126     signalWork();
2127     }
2128    
2129     /**
2130 dl 1.300 * Pushes a possibly-external submission.
2131     */
2132     private <T> ForkJoinTask<T> externalSubmit(ForkJoinTask<T> task) {
2133 dl 1.355 Thread t; ForkJoinWorkerThread wt; WorkQueue q;
2134 dl 1.300 if (task == null)
2135     throw new NullPointerException();
2136     if (((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) &&
2137 dl 1.355 (q = (wt = (ForkJoinWorkerThread)t).workQueue) != null &&
2138     wt.pool == this)
2139     q.push(task, this);
2140 dl 1.300 else
2141     externalPush(task);
2142     return task;
2143     }
2144    
2145     /**
2146 dl 1.355 * Returns common pool queue for an external thread that has
2147     * possibly ever submitted a common pool task (nonzero probe), or
2148     * null if none.
2149     */
2150     static WorkQueue commonQueue() {
2151     ForkJoinPool p; WorkQueue[] qs;
2152     int r = ThreadLocalRandom.getProbe(), n;
2153     return ((p = common) != null && (qs = p.queues) != null &&
2154     (n = qs.length) > 0 && r != 0) ?
2155     qs[(n - 1) & (r << 1)] : null;
2156 dl 1.300 }
2157 dl 1.90
2158     /**
2159 dl 1.355 * If the given executor is a ForkJoinPool, poll and execute
2160     * AsynchronousCompletionTasks from worker's queue until none are
2161     * available or blocker is released.
2162 dl 1.300 */
2163 dl 1.355 static void helpAsyncBlocker(Executor e, ManagedBlocker blocker) {
2164     WorkQueue w = null; Thread t; ForkJoinWorkerThread wt;
2165     if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) {
2166     if ((wt = (ForkJoinWorkerThread)t).pool == e)
2167     w = wt.workQueue;
2168     }
2169     else if (e == common)
2170     w = commonQueue();
2171     if (w != null)
2172     w.helpAsyncBlocker(blocker);
2173 dl 1.14 }
2174    
2175     /**
2176 dl 1.105 * Returns a cheap heuristic guide for task partitioning when
2177     * programmers, frameworks, tools, or languages have little or no
2178 jsr166 1.222 * idea about task granularity. In essence, by offering this
2179 dl 1.105 * method, we ask users only about tradeoffs in overhead vs
2180     * expected throughput and its variance, rather than how finely to
2181     * partition tasks.
2182     *
2183     * In a steady state strict (tree-structured) computation, each
2184     * thread makes available for stealing enough tasks for other
2185     * threads to remain active. Inductively, if all threads play by
2186     * the same rules, each thread should make available only a
2187     * constant number of tasks.
2188     *
2189     * The minimum useful constant is just 1. But using a value of 1
2190     * would require immediate replenishment upon each steal to
2191     * maintain enough tasks, which is infeasible. Further,
2192     * partitionings/granularities of offered tasks should minimize
2193     * steal rates, which in general means that threads nearer the top
2194     * of computation tree should generate more than those nearer the
2195     * bottom. In perfect steady state, each thread is at
2196     * approximately the same level of computation tree. However,
2197     * producing extra tasks amortizes the uncertainty of progress and
2198     * diffusion assumptions.
2199     *
2200 jsr166 1.161 * So, users will want to use values larger (but not much larger)
2201 dl 1.105 * than 1 to both smooth over transient shortages and hedge
2202     * against uneven progress; as traded off against the cost of
2203     * extra task overhead. We leave the user to pick a threshold
2204     * value to compare with the results of this call to guide
2205     * decisions, but recommend values such as 3.
2206     *
2207     * When all threads are active, it is on average OK to estimate
2208     * surplus strictly locally. In steady-state, if one thread is
2209     * maintaining say 2 surplus tasks, then so are others. So we can
2210     * just use estimated queue length. However, this strategy alone
2211     * leads to serious mis-estimates in some non-steady-state
2212     * conditions (ramp-up, ramp-down, other stalls). We can detect
2213     * many of these by further considering the number of "idle"
2214     * threads, that are known to have zero queued tasks, so
2215     * compensate by a factor of (#idle/#active) threads.
2216     */
2217     static int getSurplusQueuedTaskCount() {
2218     Thread t; ForkJoinWorkerThread wt; ForkJoinPool pool; WorkQueue q;
2219 dl 1.300 if (((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) &&
2220     (pool = (wt = (ForkJoinWorkerThread)t).pool) != null &&
2221     (q = wt.workQueue) != null) {
2222     int p = pool.mode & SMASK;
2223     int a = p + (int)(pool.ctl >> RC_SHIFT);
2224     int n = q.top - q.base;
2225 dl 1.112 return n - (a > (p >>>= 1) ? 0 :
2226     a > (p >>>= 1) ? 1 :
2227     a > (p >>>= 1) ? 2 :
2228     a > (p >>>= 1) ? 4 :
2229     8);
2230 dl 1.105 }
2231     return 0;
2232 dl 1.100 }
2233    
2234 dl 1.300 // Termination
2235 dl 1.14
2236     /**
2237 dl 1.210 * Possibly initiates and/or completes termination.
2238 dl 1.14 *
2239     * @param now if true, unconditionally terminate, else only
2240 dl 1.78 * if no work and no active workers
2241 dl 1.243 * @param enable if true, terminate when next possible
2242 dl 1.300 * @return true if terminating or terminated
2243 jsr166 1.1 */
2244 dl 1.300 private boolean tryTerminate(boolean now, boolean enable) {
2245 dl 1.355 int md; // try to set SHUTDOWN, then STOP, then help terminate
2246     if (((md = mode) & SHUTDOWN) == 0) {
2247     if (!enable)
2248     return false;
2249     md = getAndBitwiseOrMode(SHUTDOWN);
2250     }
2251     if ((md & STOP) == 0) {
2252 dl 1.366 if (!now && !canStop())
2253 dl 1.300 return false;
2254 dl 1.355 md = getAndBitwiseOrMode(STOP);
2255 dl 1.289 }
2256 dl 1.355 if ((md & TERMINATED) == 0) {
2257     for (ForkJoinTask<?> t; (t = pollScan(false)) != null; )
2258 dl 1.366 ForkJoinTask.cancelIgnoringExceptions(t); // help cancel tasks
2259    
2260     WorkQueue[] qs; int n; WorkQueue q; Thread thread;
2261     if ((qs = queues) != null && (n = qs.length) > 0) {
2262     for (int j = 1; j < n; j += 2) { // unblock other workers
2263     if ((q = qs[j]) != null && (thread = q.owner) != null &&
2264     !thread.isInterrupted()) {
2265     try {
2266     thread.interrupt();
2267     } catch (Throwable ignore) {
2268     }
2269 dl 1.203 }
2270     }
2271     }
2272 dl 1.210
2273 dl 1.366 ReentrantLock lock; Condition cond; // signal when no workers
2274 dl 1.355 if ((md & SMASK) + (short)(ctl >>> TC_SHIFT) <= 0 &&
2275     (getAndBitwiseOrMode(TERMINATED) & TERMINATED) == 0 &&
2276     (lock = registrationLock) != null) {
2277     lock.lock();
2278     if ((cond = termination) != null)
2279     cond.signalAll();
2280     lock.unlock();
2281 dl 1.200 }
2282 dl 1.52 }
2283 dl 1.300 return true;
2284 dl 1.105 }
2285    
2286 dl 1.52 // Exported methods
2287 jsr166 1.1
2288     // Constructors
2289    
2290     /**
2291 jsr166 1.9 * Creates a {@code ForkJoinPool} with parallelism equal to {@link
2292 dl 1.300 * java.lang.Runtime#availableProcessors}, using defaults for all
2293 dl 1.319 * other parameters (see {@link #ForkJoinPool(int,
2294     * ForkJoinWorkerThreadFactory, UncaughtExceptionHandler, boolean,
2295     * int, int, int, Predicate, long, TimeUnit)}).
2296 jsr166 1.1 *
2297     * @throws SecurityException if a security manager exists and
2298     * the caller is not permitted to modify threads
2299     * because it does not hold {@link
2300     * java.lang.RuntimePermission}{@code ("modifyThread")}
2301     */
2302     public ForkJoinPool() {
2303 jsr166 1.148 this(Math.min(MAX_CAP, Runtime.getRuntime().availableProcessors()),
2304 dl 1.300 defaultForkJoinWorkerThreadFactory, null, false,
2305 dl 1.307 0, MAX_CAP, 1, null, DEFAULT_KEEPALIVE, TimeUnit.MILLISECONDS);
2306 jsr166 1.1 }
2307    
2308     /**
2309 jsr166 1.9 * Creates a {@code ForkJoinPool} with the indicated parallelism
2310 dl 1.319 * level, using defaults for all other parameters (see {@link
2311     * #ForkJoinPool(int, ForkJoinWorkerThreadFactory,
2312     * UncaughtExceptionHandler, boolean, int, int, int, Predicate,
2313     * long, TimeUnit)}).
2314 jsr166 1.1 *
2315 jsr166 1.9 * @param parallelism the parallelism level
2316 jsr166 1.1 * @throws IllegalArgumentException if parallelism less than or
2317 jsr166 1.11 * equal to zero, or greater than implementation limit
2318 jsr166 1.1 * @throws SecurityException if a security manager exists and
2319     * the caller is not permitted to modify threads
2320     * because it does not hold {@link
2321     * java.lang.RuntimePermission}{@code ("modifyThread")}
2322     */
2323     public ForkJoinPool(int parallelism) {
2324 dl 1.300 this(parallelism, defaultForkJoinWorkerThreadFactory, null, false,
2325 dl 1.307 0, MAX_CAP, 1, null, DEFAULT_KEEPALIVE, TimeUnit.MILLISECONDS);
2326 jsr166 1.1 }
2327    
2328     /**
2329 dl 1.300 * Creates a {@code ForkJoinPool} with the given parameters (using
2330 dl 1.319 * defaults for others -- see {@link #ForkJoinPool(int,
2331     * ForkJoinWorkerThreadFactory, UncaughtExceptionHandler, boolean,
2332     * int, int, int, Predicate, long, TimeUnit)}).
2333 jsr166 1.1 *
2334 dl 1.18 * @param parallelism the parallelism level. For default value,
2335     * use {@link java.lang.Runtime#availableProcessors}.
2336     * @param factory the factory for creating new threads. For default value,
2337     * use {@link #defaultForkJoinWorkerThreadFactory}.
2338 dl 1.19 * @param handler the handler for internal worker threads that
2339     * terminate due to unrecoverable errors encountered while executing
2340 jsr166 1.31 * tasks. For default value, use {@code null}.
2341 dl 1.19 * @param asyncMode if true,
2342 dl 1.18 * establishes local first-in-first-out scheduling mode for forked
2343     * tasks that are never joined. This mode may be more appropriate
2344     * than default locally stack-based mode in applications in which
2345     * worker threads only process event-style asynchronous tasks.
2346 jsr166 1.31 * For default value, use {@code false}.
2347 jsr166 1.1 * @throws IllegalArgumentException if parallelism less than or
2348 jsr166 1.11 * equal to zero, or greater than implementation limit
2349     * @throws NullPointerException if the factory is null
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 dl 1.19 public ForkJoinPool(int parallelism,
2356 dl 1.18 ForkJoinWorkerThreadFactory factory,
2357 jsr166 1.156 UncaughtExceptionHandler handler,
2358 dl 1.18 boolean asyncMode) {
2359 dl 1.300 this(parallelism, factory, handler, asyncMode,
2360 dl 1.307 0, MAX_CAP, 1, null, DEFAULT_KEEPALIVE, TimeUnit.MILLISECONDS);
2361 dl 1.152 }
2362    
2363 dl 1.300 /**
2364     * Creates a {@code ForkJoinPool} with the given parameters.
2365     *
2366     * @param parallelism the parallelism level. For default value,
2367     * use {@link java.lang.Runtime#availableProcessors}.
2368     *
2369     * @param factory the factory for creating new threads. For
2370     * default value, use {@link #defaultForkJoinWorkerThreadFactory}.
2371     *
2372     * @param handler the handler for internal worker threads that
2373     * terminate due to unrecoverable errors encountered while
2374     * executing tasks. For default value, use {@code null}.
2375     *
2376     * @param asyncMode if true, establishes local first-in-first-out
2377     * scheduling mode for forked tasks that are never joined. This
2378     * mode may be more appropriate than default locally stack-based
2379     * mode in applications in which worker threads only process
2380     * event-style asynchronous tasks. For default value, use {@code
2381     * false}.
2382     *
2383     * @param corePoolSize the number of threads to keep in the pool
2384     * (unless timed out after an elapsed keep-alive). Normally (and
2385     * by default) this is the same value as the parallelism level,
2386     * but may be set to a larger value to reduce dynamic overhead if
2387     * tasks regularly block. Using a smaller value (for example
2388     * {@code 0}) has the same effect as the default.
2389     *
2390     * @param maximumPoolSize the maximum number of threads allowed.
2391     * When the maximum is reached, attempts to replace blocked
2392     * threads fail. (However, because creation and termination of
2393     * different threads may overlap, and may be managed by the given
2394 dl 1.307 * thread factory, this value may be transiently exceeded.) To
2395     * arrange the same value as is used by default for the common
2396 dl 1.319 * pool, use {@code 256} plus the {@code parallelism} level. (By
2397     * default, the common pool allows a maximum of 256 spare
2398     * threads.) Using a value (for example {@code
2399     * Integer.MAX_VALUE}) larger than the implementation's total
2400     * thread limit has the same effect as using this limit (which is
2401     * the default).
2402 dl 1.300 *
2403     * @param minimumRunnable the minimum allowed number of core
2404     * threads not blocked by a join or {@link ManagedBlocker}. To
2405     * ensure progress, when too few unblocked threads exist and
2406     * unexecuted tasks may exist, new threads are constructed, up to
2407     * the given maximumPoolSize. For the default value, use {@code
2408     * 1}, that ensures liveness. A larger value might improve
2409     * throughput in the presence of blocked activities, but might
2410     * not, due to increased overhead. A value of zero may be
2411     * acceptable when submitted tasks cannot have dependencies
2412     * requiring additional threads.
2413     *
2414 jsr166 1.318 * @param saturate if non-null, a predicate invoked upon attempts
2415 dl 1.307 * to create more than the maximum total allowed threads. By
2416     * default, when a thread is about to block on a join or {@link
2417     * ManagedBlocker}, but cannot be replaced because the
2418     * maximumPoolSize would be exceeded, a {@link
2419     * RejectedExecutionException} is thrown. But if this predicate
2420     * returns {@code true}, then no exception is thrown, so the pool
2421     * continues to operate with fewer than the target number of
2422     * runnable threads, which might not ensure progress.
2423 dl 1.300 *
2424     * @param keepAliveTime the elapsed time since last use before
2425     * a thread is terminated (and then later replaced if needed).
2426     * For the default value, use {@code 60, TimeUnit.SECONDS}.
2427     *
2428     * @param unit the time unit for the {@code keepAliveTime} argument
2429     *
2430     * @throws IllegalArgumentException if parallelism is less than or
2431     * equal to zero, or is greater than implementation limit,
2432     * or if maximumPoolSize is less than parallelism,
2433     * of if the keepAliveTime is less than or equal to zero.
2434     * @throws NullPointerException if the factory is null
2435     * @throws SecurityException if a security manager exists and
2436     * the caller is not permitted to modify threads
2437     * because it does not hold {@link
2438     * java.lang.RuntimePermission}{@code ("modifyThread")}
2439 jsr166 1.306 * @since 9
2440 dl 1.300 */
2441     public ForkJoinPool(int parallelism,
2442     ForkJoinWorkerThreadFactory factory,
2443     UncaughtExceptionHandler handler,
2444     boolean asyncMode,
2445     int corePoolSize,
2446     int maximumPoolSize,
2447     int minimumRunnable,
2448 dl 1.307 Predicate<? super ForkJoinPool> saturate,
2449 dl 1.300 long keepAliveTime,
2450     TimeUnit unit) {
2451 dl 1.355 checkPermission();
2452     int p = parallelism;
2453     if (p <= 0 || p > MAX_CAP || p > maximumPoolSize || keepAliveTime <= 0L)
2454 dl 1.152 throw new IllegalArgumentException();
2455 dl 1.355 if (factory == null || unit == null)
2456 dl 1.14 throw new NullPointerException();
2457 dl 1.300 this.factory = factory;
2458     this.ueh = handler;
2459 dl 1.307 this.saturate = saturate;
2460 dl 1.355 this.keepAlive = Math.max(unit.toMillis(keepAliveTime), TIMEOUT_SLOP);
2461     int size = 1 << (33 - Integer.numberOfLeadingZeros(p - 1));
2462     int corep = Math.min(Math.max(corePoolSize, p), MAX_CAP);
2463     int maxSpares = Math.min(maximumPoolSize, MAX_CAP) - p;
2464     int minAvail = Math.min(Math.max(minimumRunnable, 0), MAX_CAP);
2465     this.bounds = ((minAvail - p) & SMASK) | (maxSpares << SWIDTH);
2466     this.mode = p | (asyncMode ? FIFO : 0);
2467     this.ctl = ((((long)(-corep) << TC_SHIFT) & TC_MASK) |
2468     (((long)(-p) << RC_SHIFT) & RC_MASK));
2469     this.registrationLock = new ReentrantLock();
2470     this.queues = new WorkQueue[size];
2471     String pid = Integer.toString(getAndAddPoolIds(1) + 1);
2472     this.workerNamePrefix = "ForkJoinPool-" + pid + "-worker-";
2473 dl 1.152 }
2474    
2475 dl 1.355 // helper method for commonPool constructor
2476 jsr166 1.334 private static Object newInstanceFromSystemProperty(String property)
2477 jsr166 1.327 throws ReflectiveOperationException {
2478     String className = System.getProperty(property);
2479     return (className == null)
2480     ? null
2481     : ClassLoader.getSystemClassLoader().loadClass(className)
2482     .getConstructor().newInstance();
2483     }
2484    
2485 dl 1.152 /**
2486 dl 1.300 * Constructor for common pool using parameters possibly
2487     * overridden by system properties
2488     */
2489     private ForkJoinPool(byte forCommonPoolOnly) {
2490 dl 1.355 int parallelism = Runtime.getRuntime().availableProcessors() - 1;
2491 dl 1.300 ForkJoinWorkerThreadFactory fac = null;
2492     UncaughtExceptionHandler handler = null;
2493     try { // ignore exceptions in accessing/parsing properties
2494 dl 1.355 fac = (ForkJoinWorkerThreadFactory) newInstanceFromSystemProperty(
2495     "java.util.concurrent.ForkJoinPool.common.threadFactory");
2496     handler = (UncaughtExceptionHandler) newInstanceFromSystemProperty(
2497     "java.util.concurrent.ForkJoinPool.common.exceptionHandler");
2498 dl 1.300 String pp = System.getProperty
2499     ("java.util.concurrent.ForkJoinPool.common.parallelism");
2500     if (pp != null)
2501     parallelism = Integer.parseInt(pp);
2502     } catch (Exception ignore) {
2503     }
2504 dl 1.355 int p = this.mode = Math.min(Math.max(parallelism, 0), MAX_CAP);
2505     int size = 1 << (33 - Integer.numberOfLeadingZeros(p > 0 ? p - 1 : 1));
2506     this.factory = (fac != null) ? fac :
2507     (System.getSecurityManager() == null ?
2508     defaultForkJoinWorkerThreadFactory :
2509     new InnocuousForkJoinWorkerThreadFactory());
2510 dl 1.18 this.ueh = handler;
2511 dl 1.355 this.keepAlive = DEFAULT_KEEPALIVE;
2512 dl 1.307 this.saturate = null;
2513 dl 1.355 this.workerNamePrefix = null;
2514     this.bounds = ((1 - p) & SMASK) | (COMMON_MAX_SPARES << SWIDTH);
2515     this.ctl = ((((long)(-p) << TC_SHIFT) & TC_MASK) |
2516     (((long)(-p) << RC_SHIFT) & RC_MASK));
2517     this.queues = new WorkQueue[size];
2518     this.registrationLock = new ReentrantLock();
2519 dl 1.101 }
2520    
2521     /**
2522 dl 1.128 * Returns the common pool instance. This pool is statically
2523 dl 1.134 * constructed; its run state is unaffected by attempts to {@link
2524     * #shutdown} or {@link #shutdownNow}. However this pool and any
2525     * ongoing processing are automatically terminated upon program
2526     * {@link System#exit}. Any program that relies on asynchronous
2527     * task processing to complete before program termination should
2528 jsr166 1.158 * invoke {@code commonPool().}{@link #awaitQuiescence awaitQuiescence},
2529     * before exit.
2530 dl 1.100 *
2531     * @return the common pool instance
2532 jsr166 1.138 * @since 1.8
2533 dl 1.100 */
2534     public static ForkJoinPool commonPool() {
2535 dl 1.134 // assert common != null : "static init error";
2536     return common;
2537 dl 1.100 }
2538    
2539 jsr166 1.1 // Execution methods
2540    
2541     /**
2542     * Performs the given task, returning its result upon completion.
2543 dl 1.52 * If the computation encounters an unchecked Exception or Error,
2544     * it is rethrown as the outcome of this invocation. Rethrown
2545     * exceptions behave in the same way as regular exceptions, but,
2546     * when possible, contain stack traces (as displayed for example
2547     * using {@code ex.printStackTrace()}) of both the current thread
2548     * as well as the thread actually encountering the exception;
2549     * minimally only the latter.
2550 jsr166 1.1 *
2551     * @param task the task
2552 jsr166 1.191 * @param <T> the type of the task's result
2553 jsr166 1.1 * @return the task's result
2554 jsr166 1.11 * @throws NullPointerException if the task is null
2555     * @throws RejectedExecutionException if the task cannot be
2556     * scheduled for execution
2557 jsr166 1.1 */
2558     public <T> T invoke(ForkJoinTask<T> task) {
2559 dl 1.243 externalSubmit(task);
2560 dl 1.78 return task.join();
2561 jsr166 1.1 }
2562    
2563     /**
2564     * Arranges for (asynchronous) execution of the given task.
2565     *
2566     * @param task the task
2567 jsr166 1.11 * @throws NullPointerException if the task is null
2568     * @throws RejectedExecutionException if the task cannot be
2569     * scheduled for execution
2570 jsr166 1.1 */
2571 jsr166 1.8 public void execute(ForkJoinTask<?> task) {
2572 dl 1.243 externalSubmit(task);
2573 jsr166 1.1 }
2574    
2575     // AbstractExecutorService methods
2576    
2577 jsr166 1.11 /**
2578     * @throws NullPointerException if the task is null
2579     * @throws RejectedExecutionException if the task cannot be
2580     * scheduled for execution
2581     */
2582 dl 1.355 @Override
2583     @SuppressWarnings("unchecked")
2584 jsr166 1.1 public void execute(Runnable task) {
2585 dl 1.355 externalSubmit((task instanceof ForkJoinTask<?>)
2586     ? (ForkJoinTask<Void>) task // avoid re-wrap
2587     : new ForkJoinTask.RunnableExecuteAction(task));
2588 jsr166 1.1 }
2589    
2590 jsr166 1.11 /**
2591 dl 1.18 * Submits a ForkJoinTask for execution.
2592     *
2593     * @param task the task to submit
2594 jsr166 1.191 * @param <T> the type of the task's result
2595 dl 1.18 * @return the task
2596     * @throws NullPointerException if the task is null
2597     * @throws RejectedExecutionException if the task cannot be
2598     * scheduled for execution
2599     */
2600     public <T> ForkJoinTask<T> submit(ForkJoinTask<T> task) {
2601 dl 1.243 return externalSubmit(task);
2602 dl 1.18 }
2603    
2604     /**
2605 jsr166 1.11 * @throws NullPointerException if the task is null
2606     * @throws RejectedExecutionException if the task cannot be
2607     * scheduled for execution
2608     */
2609 dl 1.355 @Override
2610 jsr166 1.1 public <T> ForkJoinTask<T> submit(Callable<T> task) {
2611 dl 1.243 return externalSubmit(new ForkJoinTask.AdaptedCallable<T>(task));
2612 jsr166 1.1 }
2613    
2614 jsr166 1.11 /**
2615     * @throws NullPointerException if the task is null
2616     * @throws RejectedExecutionException if the task cannot be
2617     * scheduled for execution
2618     */
2619 dl 1.355 @Override
2620 jsr166 1.1 public <T> ForkJoinTask<T> submit(Runnable task, T result) {
2621 dl 1.243 return externalSubmit(new ForkJoinTask.AdaptedRunnable<T>(task, result));
2622 jsr166 1.1 }
2623    
2624 jsr166 1.11 /**
2625     * @throws NullPointerException if the task is null
2626     * @throws RejectedExecutionException if the task cannot be
2627     * scheduled for execution
2628     */
2629 dl 1.355 @Override
2630 jsr166 1.335 @SuppressWarnings("unchecked")
2631 jsr166 1.1 public ForkJoinTask<?> submit(Runnable task) {
2632 jsr166 1.335 return externalSubmit((task instanceof ForkJoinTask<?>)
2633     ? (ForkJoinTask<Void>) task // avoid re-wrap
2634     : new ForkJoinTask.AdaptedRunnableAction(task));
2635 jsr166 1.1 }
2636    
2637     /**
2638 jsr166 1.11 * @throws NullPointerException {@inheritDoc}
2639     * @throws RejectedExecutionException {@inheritDoc}
2640     */
2641 dl 1.355 @Override
2642 jsr166 1.1 public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) {
2643 dl 1.366 ArrayList<Future<T>> futures = new ArrayList<>(tasks.size());
2644     try {
2645     for (Callable<T> t : tasks) {
2646 dl 1.367 ForkJoinTask<T> f =
2647     new ForkJoinTask.AdaptedInterruptibleCallable<T>(t);
2648 dl 1.366 futures.add(f);
2649     externalSubmit(f);
2650     }
2651     for (int i = futures.size() - 1; i >= 0; --i)
2652     ((ForkJoinTask<?>)futures.get(i)).quietlyJoin();
2653     return futures;
2654     } catch (Throwable t) {
2655     for (Future<T> e : futures)
2656     ForkJoinTask.cancelIgnoringExceptions(e);
2657     throw t;
2658     }
2659 dl 1.355 }
2660    
2661     @Override
2662     public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks,
2663     long timeout, TimeUnit unit)
2664     throws InterruptedException {
2665 dl 1.366 long nanos = unit.toNanos(timeout);
2666     ArrayList<Future<T>> futures = new ArrayList<>(tasks.size());
2667     try {
2668     for (Callable<T> t : tasks) {
2669 dl 1.367 ForkJoinTask<T> f =
2670     new ForkJoinTask.AdaptedInterruptibleCallable<T>(t);
2671 dl 1.366 futures.add(f);
2672     externalSubmit(f);
2673     }
2674     long startTime = System.nanoTime(), ns = nanos;
2675     boolean timedOut = (ns < 0L);
2676     for (int i = futures.size() - 1; i >= 0; --i) {
2677     Future<T> f = futures.get(i);
2678     if (!f.isDone()) {
2679     if (timedOut)
2680     ForkJoinTask.cancelIgnoringExceptions(f);
2681     else {
2682     try {
2683     f.get(ns, TimeUnit.NANOSECONDS);
2684     } catch (CancellationException | TimeoutException |
2685     ExecutionException ok) {
2686     }
2687     if ((ns = nanos - (System.nanoTime() - startTime)) < 0L)
2688     timedOut = true;
2689     }
2690     }
2691 dl 1.355 }
2692 dl 1.366 return futures;
2693     } catch (Throwable t) {
2694     for (Future<T> e : futures)
2695     ForkJoinTask.cancelIgnoringExceptions(e);
2696     throw t;
2697 dl 1.355 }
2698 jsr166 1.1 }
2699    
2700 dl 1.367 // Task to hold results from InvokeAnyTasks
2701     static final class InvokeAnyRoot<E> extends ForkJoinTask<E> {
2702     private static final long serialVersionUID = 2838392045355241008L;
2703     @SuppressWarnings("serial") // Conditionally serializable
2704     volatile E result;
2705     final AtomicInteger count; // in case all throw
2706 dl 1.368 InvokeAnyRoot(int n) { count = new AtomicInteger(n); }
2707 dl 1.367 final void tryComplete(Callable<E> c) { // called by InvokeAnyTasks
2708     if (c != null && !isDone()) { // raciness OK
2709     try {
2710     complete(c.call());
2711     } catch (Throwable ex) {
2712 dl 1.368 if (count.getAndDecrement() <= 1)
2713     trySetThrown(ex);
2714 dl 1.367 }
2715     }
2716     }
2717     public final boolean exec() { return false; } // never forked
2718     public final E getRawResult() { return result; }
2719     public final void setRawResult(E v) { result = v; }
2720     }
2721    
2722     // Variant of AdaptedInterruptibleCallable with results in InvokeAnyRoot
2723     static final class InvokeAnyTask<E> extends ForkJoinTask<E> {
2724     private static final long serialVersionUID = 2838392045355241008L;
2725     final InvokeAnyRoot<E> root;
2726     @SuppressWarnings("serial") // Conditionally serializable
2727     final Callable<E> callable;
2728     transient volatile Thread runner;
2729     InvokeAnyTask(InvokeAnyRoot<E> root, Callable<E> callable) {
2730     this.root = root;
2731     this.callable = callable;
2732     }
2733     public final boolean exec() {
2734     Thread.interrupted();
2735     runner = Thread.currentThread();
2736     root.tryComplete(callable);
2737     runner = null;
2738     Thread.interrupted();
2739     return true;
2740     }
2741     public final boolean cancel(boolean mayInterruptIfRunning) {
2742     Thread t;
2743     boolean stat = super.cancel(false);
2744     if (mayInterruptIfRunning && (t = runner) != null) {
2745     try {
2746     t.interrupt();
2747     } catch (Throwable ignore) {
2748     }
2749     }
2750     return stat;
2751     }
2752     public final void setRawResult(E v) {} // unused
2753     public final E getRawResult() { return null; }
2754     }
2755    
2756     @Override
2757     public <T> T invokeAny(Collection<? extends Callable<T>> tasks)
2758     throws InterruptedException, ExecutionException {
2759     int n = tasks.size();
2760     if (n <= 0)
2761     throw new IllegalArgumentException();
2762 dl 1.368 InvokeAnyRoot<T> root = new InvokeAnyRoot<T>(n);
2763 dl 1.367 ArrayList<InvokeAnyTask<T>> fs = new ArrayList<>(n);
2764     for (Callable<T> c : tasks) {
2765     if (c == null)
2766     throw new NullPointerException();
2767     InvokeAnyTask<T> f = new InvokeAnyTask<T>(root, c);
2768     fs.add(f);
2769 dl 1.368 if (isSaturated())
2770     f.doExec();
2771     else
2772     externalSubmit(f);
2773     if (root.isDone())
2774     break;
2775 dl 1.367 }
2776     try {
2777     return root.get();
2778     } finally {
2779     for (InvokeAnyTask<T> f : fs)
2780 dl 1.369 ForkJoinTask.cancelIgnoringExceptions(f);
2781 dl 1.367 }
2782     }
2783    
2784     @Override
2785     public <T> T invokeAny(Collection<? extends Callable<T>> tasks,
2786     long timeout, TimeUnit unit)
2787     throws InterruptedException, ExecutionException, TimeoutException {
2788     long nanos = unit.toNanos(timeout);
2789     int n = tasks.size();
2790     if (n <= 0)
2791     throw new IllegalArgumentException();
2792 dl 1.368 InvokeAnyRoot<T> root = new InvokeAnyRoot<T>(n);
2793 dl 1.367 ArrayList<InvokeAnyTask<T>> fs = new ArrayList<>(n);
2794     for (Callable<T> c : tasks) {
2795     if (c == null)
2796     throw new NullPointerException();
2797     InvokeAnyTask<T> f = new InvokeAnyTask<T>(root, c);
2798     fs.add(f);
2799 dl 1.368 if (isSaturated())
2800     f.doExec();
2801     else
2802     externalSubmit(f);
2803     if (root.isDone())
2804     break;
2805 dl 1.367 }
2806     try {
2807     return root.get(nanos, TimeUnit.NANOSECONDS);
2808     } finally {
2809     for (InvokeAnyTask<T> f : fs)
2810 dl 1.369 ForkJoinTask.cancelIgnoringExceptions(f);
2811 dl 1.367 }
2812     }
2813    
2814 jsr166 1.1 /**
2815     * Returns the factory used for constructing new workers.
2816     *
2817     * @return the factory used for constructing new workers
2818     */
2819     public ForkJoinWorkerThreadFactory getFactory() {
2820     return factory;
2821     }
2822    
2823     /**
2824     * Returns the handler for internal worker threads that terminate
2825     * due to unrecoverable errors encountered while executing tasks.
2826     *
2827 jsr166 1.4 * @return the handler, or {@code null} if none
2828 jsr166 1.1 */
2829 jsr166 1.156 public UncaughtExceptionHandler getUncaughtExceptionHandler() {
2830 dl 1.14 return ueh;
2831 jsr166 1.1 }
2832    
2833     /**
2834 jsr166 1.9 * Returns the targeted parallelism level of this pool.
2835 jsr166 1.1 *
2836 jsr166 1.9 * @return the targeted parallelism level of this pool
2837 jsr166 1.1 */
2838     public int getParallelism() {
2839 dl 1.310 int par = mode & SMASK;
2840     return (par > 0) ? par : 1;
2841 jsr166 1.1 }
2842    
2843     /**
2844 dl 1.100 * Returns the targeted parallelism level of the common pool.
2845     *
2846     * @return the targeted parallelism level of the common pool
2847 jsr166 1.138 * @since 1.8
2848 dl 1.100 */
2849     public static int getCommonPoolParallelism() {
2850 jsr166 1.274 return COMMON_PARALLELISM;
2851 dl 1.100 }
2852    
2853     /**
2854 jsr166 1.1 * Returns the number of worker threads that have started but not
2855 jsr166 1.34 * yet terminated. The result returned by this method may differ
2856 jsr166 1.4 * from {@link #getParallelism} when threads are created to
2857 jsr166 1.1 * maintain parallelism when others are cooperatively blocked.
2858     *
2859     * @return the number of worker threads
2860     */
2861     public int getPoolSize() {
2862 dl 1.300 return ((mode & SMASK) + (short)(ctl >>> TC_SHIFT));
2863 jsr166 1.1 }
2864    
2865     /**
2866 jsr166 1.4 * Returns {@code true} if this pool uses local first-in-first-out
2867 jsr166 1.1 * scheduling mode for forked tasks that are never joined.
2868     *
2869 jsr166 1.4 * @return {@code true} if this pool uses async mode
2870 jsr166 1.1 */
2871     public boolean getAsyncMode() {
2872 dl 1.300 return (mode & FIFO) != 0;
2873 jsr166 1.1 }
2874    
2875     /**
2876     * Returns an estimate of the number of worker threads that are
2877     * not blocked waiting to join tasks or for other managed
2878 dl 1.14 * synchronization. This method may overestimate the
2879     * number of running threads.
2880 jsr166 1.1 *
2881     * @return the number of worker threads
2882     */
2883     public int getRunningThreadCount() {
2884 dl 1.345 VarHandle.acquireFence();
2885 dl 1.355 WorkQueue[] qs; WorkQueue q;
2886 jsr166 1.344 int rc = 0;
2887 dl 1.355 if ((qs = queues) != null) {
2888     for (int i = 1; i < qs.length; i += 2) {
2889     if ((q = qs[i]) != null && q.isApparentlyUnblocked())
2890 dl 1.78 ++rc;
2891     }
2892     }
2893     return rc;
2894 jsr166 1.1 }
2895    
2896     /**
2897     * Returns an estimate of the number of threads that are currently
2898     * stealing or executing tasks. This method may overestimate the
2899     * number of active threads.
2900     *
2901     * @return the number of active threads
2902     */
2903     public int getActiveThreadCount() {
2904 dl 1.300 int r = (mode & SMASK) + (int)(ctl >> RC_SHIFT);
2905 jsr166 1.63 return (r <= 0) ? 0 : r; // suppress momentarily negative values
2906 jsr166 1.1 }
2907    
2908     /**
2909 jsr166 1.4 * Returns {@code true} if all worker threads are currently idle.
2910     * An idle worker is one that cannot obtain a task to execute
2911     * because none are available to steal from other threads, and
2912     * there are no pending submissions to the pool. This method is
2913     * conservative; it might not return {@code true} immediately upon
2914     * idleness of all threads, but will eventually become true if
2915     * threads remain inactive.
2916 jsr166 1.1 *
2917 jsr166 1.4 * @return {@code true} if all threads are currently idle
2918 jsr166 1.1 */
2919     public boolean isQuiescent() {
2920 dl 1.366 return canStop();
2921 jsr166 1.1 }
2922    
2923     /**
2924 dl 1.354 * Returns an estimate of the total number of completed tasks that
2925     * were executed by a thread other than their submitter. The
2926     * reported value underestimates the actual total number of steals
2927     * when the pool is not quiescent. This value may be useful for
2928     * monitoring and tuning fork/join programs: in general, steal
2929     * counts should be high enough to keep threads busy, but low
2930     * enough to avoid overhead and contention across threads.
2931 jsr166 1.1 *
2932     * @return the number of steals
2933     */
2934     public long getStealCount() {
2935 dl 1.300 long count = stealCount;
2936 dl 1.355 WorkQueue[] qs; WorkQueue q;
2937     if ((qs = queues) != null) {
2938     for (int i = 1; i < qs.length; i += 2) {
2939     if ((q = qs[i]) != null)
2940     count += (long)q.nsteals & 0xffffffffL;
2941 dl 1.78 }
2942     }
2943     return count;
2944 jsr166 1.1 }
2945    
2946     /**
2947     * Returns an estimate of the total number of tasks currently held
2948     * in queues by worker threads (but not including tasks submitted
2949     * to the pool that have not begun executing). This value is only
2950     * an approximation, obtained by iterating across all threads in
2951     * the pool. This method may be useful for tuning task
2952     * granularities.
2953     *
2954     * @return the number of queued tasks
2955     */
2956     public long getQueuedTaskCount() {
2957 dl 1.345 VarHandle.acquireFence();
2958 dl 1.355 WorkQueue[] qs; WorkQueue q;
2959 dl 1.345 int count = 0;
2960 dl 1.355 if ((qs = queues) != null) {
2961     for (int i = 1; i < qs.length; i += 2) {
2962     if ((q = qs[i]) != null)
2963     count += q.queueSize();
2964 dl 1.78 }
2965 dl 1.52 }
2966 jsr166 1.1 return count;
2967     }
2968    
2969     /**
2970 jsr166 1.8 * Returns an estimate of the number of tasks submitted to this
2971 dl 1.55 * pool that have not yet begun executing. This method may take
2972 dl 1.52 * time proportional to the number of submissions.
2973 jsr166 1.1 *
2974     * @return the number of queued submissions
2975     */
2976     public int getQueuedSubmissionCount() {
2977 dl 1.345 VarHandle.acquireFence();
2978 dl 1.355 WorkQueue[] qs; WorkQueue q;
2979 jsr166 1.344 int count = 0;
2980 dl 1.355 if ((qs = queues) != null) {
2981     for (int i = 0; i < qs.length; i += 2) {
2982     if ((q = qs[i]) != null)
2983     count += q.queueSize();
2984 dl 1.78 }
2985     }
2986     return count;
2987 jsr166 1.1 }
2988    
2989     /**
2990 jsr166 1.4 * Returns {@code true} if there are any tasks submitted to this
2991     * pool that have not yet begun executing.
2992 jsr166 1.1 *
2993     * @return {@code true} if there are any queued submissions
2994     */
2995     public boolean hasQueuedSubmissions() {
2996 dl 1.345 VarHandle.acquireFence();
2997 dl 1.355 WorkQueue[] qs; WorkQueue q;
2998     if ((qs = queues) != null) {
2999     for (int i = 0; i < qs.length; i += 2) {
3000     if ((q = qs[i]) != null && !q.isEmpty())
3001 dl 1.78 return true;
3002     }
3003     }
3004     return false;
3005 jsr166 1.1 }
3006    
3007     /**
3008     * Removes and returns the next unexecuted submission if one is
3009     * available. This method may be useful in extensions to this
3010     * class that re-assign work in systems with multiple pools.
3011     *
3012 jsr166 1.4 * @return the next submission, or {@code null} if none
3013 jsr166 1.1 */
3014     protected ForkJoinTask<?> pollSubmission() {
3015 dl 1.300 return pollScan(true);
3016 jsr166 1.1 }
3017    
3018     /**
3019     * Removes all available unexecuted submitted and forked tasks
3020     * from scheduling queues and adds them to the given collection,
3021     * without altering their execution status. These may include
3022 jsr166 1.8 * artificially generated or wrapped tasks. This method is
3023     * designed to be invoked only when the pool is known to be
3024 jsr166 1.1 * quiescent. Invocations at other times may not remove all
3025     * tasks. A failure encountered while attempting to add elements
3026     * to collection {@code c} may result in elements being in
3027     * neither, either or both collections when the associated
3028     * exception is thrown. The behavior of this operation is
3029     * undefined if the specified collection is modified while the
3030     * operation is in progress.
3031     *
3032     * @param c the collection to transfer elements into
3033     * @return the number of elements transferred
3034     */
3035 jsr166 1.5 protected int drainTasksTo(Collection<? super ForkJoinTask<?>> c) {
3036 jsr166 1.344 int count = 0;
3037 dl 1.355 for (ForkJoinTask<?> t; (t = pollScan(false)) != null; ) {
3038     c.add(t);
3039     ++count;
3040 dl 1.52 }
3041 dl 1.18 return count;
3042     }
3043    
3044     /**
3045 jsr166 1.1 * Returns a string identifying this pool, as well as its state,
3046     * including indications of run state, parallelism level, and
3047     * worker and task counts.
3048     *
3049     * @return a string identifying this pool, as well as its state
3050     */
3051     public String toString() {
3052 dl 1.355 // Use a single pass through queues to collect counts
3053 dl 1.345 int md = mode; // read volatile fields first
3054     long c = ctl;
3055     long st = stealCount;
3056 dl 1.355 long qt = 0L, ss = 0L; int rc = 0;
3057     WorkQueue[] qs; WorkQueue q;
3058     if ((qs = queues) != null) {
3059     for (int i = 0; i < qs.length; ++i) {
3060     if ((q = qs[i]) != null) {
3061     int size = q.queueSize();
3062 dl 1.86 if ((i & 1) == 0)
3063 dl 1.355 ss += size;
3064 dl 1.86 else {
3065     qt += size;
3066 dl 1.355 st += (long)q.nsteals & 0xffffffffL;
3067     if (q.isApparentlyUnblocked())
3068 dl 1.86 ++rc;
3069     }
3070     }
3071     }
3072     }
3073 dl 1.300
3074     int pc = (md & SMASK);
3075 dl 1.52 int tc = pc + (short)(c >>> TC_SHIFT);
3076 dl 1.300 int ac = pc + (int)(c >> RC_SHIFT);
3077 dl 1.78 if (ac < 0) // ignore transient negative
3078     ac = 0;
3079 dl 1.300 String level = ((md & TERMINATED) != 0 ? "Terminated" :
3080     (md & STOP) != 0 ? "Terminating" :
3081     (md & SHUTDOWN) != 0 ? "Shutting down" :
3082 dl 1.200 "Running");
3083 jsr166 1.1 return super.toString() +
3084 dl 1.52 "[" + level +
3085 dl 1.14 ", parallelism = " + pc +
3086     ", size = " + tc +
3087     ", active = " + ac +
3088     ", running = " + rc +
3089 jsr166 1.1 ", steals = " + st +
3090     ", tasks = " + qt +
3091 dl 1.355 ", submissions = " + ss +
3092 jsr166 1.1 "]";
3093     }
3094    
3095     /**
3096 dl 1.100 * Possibly initiates an orderly shutdown in which previously
3097     * submitted tasks are executed, but no new tasks will be
3098     * accepted. Invocation has no effect on execution state if this
3099 jsr166 1.137 * is the {@link #commonPool()}, and no additional effect if
3100 dl 1.100 * already shut down. Tasks that are in the process of being
3101     * submitted concurrently during the course of this method may or
3102     * may not be rejected.
3103 jsr166 1.1 *
3104     * @throws SecurityException if a security manager exists and
3105     * the caller is not permitted to modify threads
3106     * because it does not hold {@link
3107     * java.lang.RuntimePermission}{@code ("modifyThread")}
3108     */
3109     public void shutdown() {
3110     checkPermission();
3111 dl 1.355 if (this != common)
3112     tryTerminate(false, true);
3113 jsr166 1.1 }
3114    
3115     /**
3116 dl 1.100 * Possibly attempts to cancel and/or stop all tasks, and reject
3117     * all subsequently submitted tasks. Invocation has no effect on
3118 jsr166 1.137 * execution state if this is the {@link #commonPool()}, and no
3119 dl 1.100 * additional effect if already shut down. Otherwise, tasks that
3120     * are in the process of being submitted or executed concurrently
3121     * during the course of this method may or may not be
3122     * rejected. This method cancels both existing and unexecuted
3123     * tasks, in order to permit termination in the presence of task
3124     * dependencies. So the method always returns an empty list
3125     * (unlike the case for some other Executors).
3126 jsr166 1.1 *
3127     * @return an empty list
3128     * @throws SecurityException if a security manager exists and
3129     * the caller is not permitted to modify threads
3130     * because it does not hold {@link
3131     * java.lang.RuntimePermission}{@code ("modifyThread")}
3132     */
3133     public List<Runnable> shutdownNow() {
3134     checkPermission();
3135 dl 1.355 if (this != common)
3136     tryTerminate(true, true);
3137 jsr166 1.1 return Collections.emptyList();
3138     }
3139    
3140     /**
3141     * Returns {@code true} if all tasks have completed following shut down.
3142     *
3143     * @return {@code true} if all tasks have completed following shut down
3144     */
3145     public boolean isTerminated() {
3146 dl 1.300 return (mode & TERMINATED) != 0;
3147 jsr166 1.1 }
3148    
3149     /**
3150     * Returns {@code true} if the process of termination has
3151 jsr166 1.9 * commenced but not yet completed. This method may be useful for
3152     * debugging. A return of {@code true} reported a sufficient
3153     * period after shutdown may indicate that submitted tasks have
3154 jsr166 1.119 * ignored or suppressed interruption, or are waiting for I/O,
3155 dl 1.49 * causing this executor not to properly terminate. (See the
3156     * advisory notes for class {@link ForkJoinTask} stating that
3157     * tasks should not normally entail blocking operations. But if
3158     * they do, they must abort them on interrupt.)
3159 jsr166 1.1 *
3160 jsr166 1.9 * @return {@code true} if terminating but not yet terminated
3161 jsr166 1.1 */
3162     public boolean isTerminating() {
3163 dl 1.355 return (mode & (STOP | TERMINATED)) == STOP;
3164 jsr166 1.1 }
3165    
3166     /**
3167     * Returns {@code true} if this pool has been shut down.
3168     *
3169     * @return {@code true} if this pool has been shut down
3170     */
3171     public boolean isShutdown() {
3172 dl 1.300 return (mode & SHUTDOWN) != 0;
3173 jsr166 1.9 }
3174    
3175     /**
3176 dl 1.105 * Blocks until all tasks have completed execution after a
3177     * shutdown request, or the timeout occurs, or the current thread
3178 dl 1.134 * is interrupted, whichever happens first. Because the {@link
3179     * #commonPool()} never terminates until program shutdown, when
3180     * applied to the common pool, this method is equivalent to {@link
3181 jsr166 1.158 * #awaitQuiescence(long, TimeUnit)} but always returns {@code false}.
3182 jsr166 1.1 *
3183     * @param timeout the maximum time to wait
3184     * @param unit the time unit of the timeout argument
3185     * @return {@code true} if this executor terminated and
3186     * {@code false} if the timeout elapsed before termination
3187     * @throws InterruptedException if interrupted while waiting
3188     */
3189     public boolean awaitTermination(long timeout, TimeUnit unit)
3190     throws InterruptedException {
3191 dl 1.366 ReentrantLock lock; Condition cond;
3192 dl 1.355 long nanos = unit.toNanos(timeout);
3193 dl 1.366 boolean terminated = false;
3194 dl 1.134 if (this == common) {
3195 dl 1.366 Thread t; ForkJoinWorkerThread wt; int q;
3196     if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread &&
3197     (wt = (ForkJoinWorkerThread)t).pool == this)
3198     q = helpQuiescePool(wt.workQueue, nanos, true);
3199     else
3200     q = externalHelpQuiescePool(nanos, true);
3201     if (q < 0)
3202     throw new InterruptedException();
3203 dl 1.134 }
3204 dl 1.375 else if (!(terminated = ((mode & TERMINATED) != 0)) &&
3205 dl 1.366 (lock = registrationLock) != null) {
3206     lock.lock();
3207     try {
3208     if ((cond = termination) == null)
3209     termination = cond = lock.newCondition();
3210 dl 1.374 while (!(terminated = ((mode & TERMINATED) != 0)) && nanos > 0L)
3211 dl 1.366 nanos = cond.awaitNanos(nanos);
3212     } finally {
3213     lock.unlock();
3214     }
3215 dl 1.18 }
3216 dl 1.366 return terminated;
3217 jsr166 1.1 }
3218    
3219     /**
3220 dl 1.134 * If called by a ForkJoinTask operating in this pool, equivalent
3221     * in effect to {@link ForkJoinTask#helpQuiesce}. Otherwise,
3222     * waits and/or attempts to assist performing tasks until this
3223     * pool {@link #isQuiescent} or the indicated timeout elapses.
3224     *
3225     * @param timeout the maximum time to wait
3226     * @param unit the time unit of the timeout argument
3227     * @return {@code true} if quiescent; {@code false} if the
3228     * timeout elapsed.
3229     */
3230     public boolean awaitQuiescence(long timeout, TimeUnit unit) {
3231 dl 1.366 Thread t; ForkJoinWorkerThread wt; int q;
3232 dl 1.134 long nanos = unit.toNanos(timeout);
3233 dl 1.366 if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread &&
3234     (wt = (ForkJoinWorkerThread)t).pool == this)
3235     q = helpQuiescePool(wt.workQueue, nanos, false);
3236     else
3237     q = externalHelpQuiescePool(nanos, false);
3238     return (q > 0);
3239 dl 1.134 }
3240    
3241     /**
3242 jsr166 1.1 * Interface for extending managed parallelism for tasks running
3243 jsr166 1.8 * in {@link ForkJoinPool}s.
3244     *
3245 dl 1.19 * <p>A {@code ManagedBlocker} provides two methods. Method
3246 jsr166 1.218 * {@link #isReleasable} must return {@code true} if blocking is
3247     * not necessary. Method {@link #block} blocks the current thread
3248 dl 1.19 * if necessary (perhaps internally invoking {@code isReleasable}
3249 dl 1.54 * before actually blocking). These actions are performed by any
3250 dl 1.355 * thread invoking {@link
3251     * ForkJoinPool#managedBlock(ManagedBlocker)}. The unusual
3252     * methods in this API accommodate synchronizers that may, but
3253     * don't usually, block for long periods. Similarly, they allow
3254     * more efficient internal handling of cases in which additional
3255     * workers may be, but usually are not, needed to ensure
3256     * sufficient parallelism. Toward this end, implementations of
3257     * method {@code isReleasable} must be amenable to repeated
3258     * invocation. Neither method is invoked after a prior invocation
3259     * of {@code isReleasable} or {@code block} returns {@code true}.
3260 jsr166 1.1 *
3261     * <p>For example, here is a ManagedBlocker based on a
3262     * ReentrantLock:
3263 jsr166 1.239 * <pre> {@code
3264 jsr166 1.1 * class ManagedLocker implements ManagedBlocker {
3265     * final ReentrantLock lock;
3266     * boolean hasLock = false;
3267     * ManagedLocker(ReentrantLock lock) { this.lock = lock; }
3268     * public boolean block() {
3269     * if (!hasLock)
3270     * lock.lock();
3271     * return true;
3272     * }
3273     * public boolean isReleasable() {
3274     * return hasLock || (hasLock = lock.tryLock());
3275     * }
3276     * }}</pre>
3277 dl 1.19 *
3278     * <p>Here is a class that possibly blocks waiting for an
3279     * item on a given queue:
3280 jsr166 1.239 * <pre> {@code
3281 dl 1.19 * class QueueTaker<E> implements ManagedBlocker {
3282     * final BlockingQueue<E> queue;
3283     * volatile E item = null;
3284     * QueueTaker(BlockingQueue<E> q) { this.queue = q; }
3285     * public boolean block() throws InterruptedException {
3286     * if (item == null)
3287 dl 1.23 * item = queue.take();
3288 dl 1.19 * return true;
3289     * }
3290     * public boolean isReleasable() {
3291 dl 1.23 * return item != null || (item = queue.poll()) != null;
3292 dl 1.19 * }
3293     * public E getItem() { // call after pool.managedBlock completes
3294     * return item;
3295     * }
3296     * }}</pre>
3297 jsr166 1.1 */
3298     public static interface ManagedBlocker {
3299     /**
3300     * Possibly blocks the current thread, for example waiting for
3301     * a lock or condition.
3302     *
3303 jsr166 1.4 * @return {@code true} if no additional blocking is necessary
3304     * (i.e., if isReleasable would return true)
3305 jsr166 1.1 * @throws InterruptedException if interrupted while waiting
3306     * (the method is not required to do so, but is allowed to)
3307     */
3308     boolean block() throws InterruptedException;
3309    
3310     /**
3311 jsr166 1.4 * Returns {@code true} if blocking is unnecessary.
3312 jsr166 1.154 * @return {@code true} if blocking is unnecessary
3313 jsr166 1.1 */
3314     boolean isReleasable();
3315     }
3316    
3317     /**
3318 jsr166 1.217 * Runs the given possibly blocking task. When {@linkplain
3319     * ForkJoinTask#inForkJoinPool() running in a ForkJoinPool}, this
3320     * method possibly arranges for a spare thread to be activated if
3321     * necessary to ensure sufficient parallelism while the current
3322     * thread is blocked in {@link ManagedBlocker#block blocker.block()}.
3323 jsr166 1.1 *
3324 jsr166 1.217 * <p>This method repeatedly calls {@code blocker.isReleasable()} and
3325     * {@code blocker.block()} until either method returns {@code true}.
3326     * Every call to {@code blocker.block()} is preceded by a call to
3327     * {@code blocker.isReleasable()} that returned {@code false}.
3328     *
3329     * <p>If not running in a ForkJoinPool, this method is
3330 jsr166 1.8 * behaviorally equivalent to
3331 jsr166 1.239 * <pre> {@code
3332 jsr166 1.1 * while (!blocker.isReleasable())
3333     * if (blocker.block())
3334 jsr166 1.217 * break;}</pre>
3335 jsr166 1.8 *
3336 jsr166 1.217 * If running in a ForkJoinPool, the pool may first be expanded to
3337     * ensure sufficient parallelism available during the call to
3338     * {@code blocker.block()}.
3339 jsr166 1.1 *
3340 jsr166 1.217 * @param blocker the blocker task
3341     * @throws InterruptedException if {@code blocker.block()} did so
3342 jsr166 1.1 */
3343 dl 1.18 public static void managedBlock(ManagedBlocker blocker)
3344 jsr166 1.1 throws InterruptedException {
3345 dl 1.355 Thread t; ForkJoinPool p;
3346     if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread &&
3347     (p = ((ForkJoinWorkerThread)t).pool) != null)
3348     p.compensatedBlock(blocker);
3349     else
3350     unmanagedBlock(blocker);
3351     }
3352    
3353     /** ManagedBlock for ForkJoinWorkerThreads */
3354     private void compensatedBlock(ManagedBlocker blocker)
3355     throws InterruptedException {
3356 dl 1.345 if (blocker == null) throw new NullPointerException();
3357 dl 1.355 for (;;) {
3358     int comp; boolean done;
3359     long c = ctl;
3360     if (blocker.isReleasable())
3361     break;
3362     if ((comp = tryCompensate(c)) >= 0) {
3363     long post = (comp == 0) ? 0L : RC_UNIT;
3364     try {
3365     done = blocker.block();
3366     } finally {
3367     getAndAddCtl(post);
3368     }
3369     if (done)
3370 dl 1.105 break;
3371 dl 1.78 }
3372 dl 1.18 }
3373 jsr166 1.1 }
3374    
3375 dl 1.355 /** ManagedBlock for external threads */
3376     private static void unmanagedBlock(ManagedBlocker blocker)
3377     throws InterruptedException {
3378     if (blocker == null) throw new NullPointerException();
3379     do {} while (!blocker.isReleasable() && !blocker.block());
3380 dl 1.310 }
3381    
3382 dl 1.355 // AbstractExecutorService.newTaskFor overrides rely on
3383     // undocumented fact that ForkJoinTask.adapt returns ForkJoinTasks
3384     // that also implement RunnableFuture.
3385 jsr166 1.1
3386 dl 1.355 @Override
3387 jsr166 1.1 protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
3388 dl 1.90 return new ForkJoinTask.AdaptedRunnable<T>(runnable, value);
3389 jsr166 1.1 }
3390    
3391 dl 1.355 @Override
3392 jsr166 1.1 protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
3393 dl 1.90 return new ForkJoinTask.AdaptedCallable<T>(callable);
3394 jsr166 1.1 }
3395    
3396 dl 1.52 static {
3397 jsr166 1.3 try {
3398 dl 1.314 MethodHandles.Lookup l = MethodHandles.lookup();
3399     CTL = l.findVarHandle(ForkJoinPool.class, "ctl", long.class);
3400     MODE = l.findVarHandle(ForkJoinPool.class, "mode", int.class);
3401 dl 1.355 THREADIDS = l.findVarHandle(ForkJoinPool.class, "threadIds", int.class);
3402     POOLIDS = l.findStaticVarHandle(ForkJoinPool.class, "poolIds", int.class);
3403 jsr166 1.231 } catch (ReflectiveOperationException e) {
3404 jsr166 1.347 throw new ExceptionInInitializerError(e);
3405 dl 1.52 }
3406 dl 1.105
3407 dl 1.243 // Reduce the risk of rare disastrous classloading in first call to
3408     // LockSupport.park: https://bugs.openjdk.java.net/browse/JDK-8074773
3409     Class<?> ensureLoaded = LockSupport.class;
3410    
3411 jsr166 1.273 int commonMaxSpares = DEFAULT_COMMON_MAX_SPARES;
3412     try {
3413     String p = System.getProperty
3414     ("java.util.concurrent.ForkJoinPool.common.maximumSpares");
3415     if (p != null)
3416     commonMaxSpares = Integer.parseInt(p);
3417     } catch (Exception ignore) {}
3418     COMMON_MAX_SPARES = commonMaxSpares;
3419    
3420 dl 1.152 defaultForkJoinWorkerThreadFactory =
3421 dl 1.112 new DefaultForkJoinWorkerThreadFactory();
3422 dl 1.115 modifyThreadPermission = new RuntimePermission("modifyThread");
3423 jsr166 1.329 common = AccessController.doPrivileged(new PrivilegedAction<>() {
3424     public ForkJoinPool run() {
3425     return new ForkJoinPool((byte)0); }});
3426 jsr166 1.275
3427 dl 1.310 COMMON_PARALLELISM = Math.max(common.mode & SMASK, 1);
3428 jsr166 1.3 }
3429 jsr166 1.1 }