ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinPool.java
Revision: 1.388
Committed: Tue Dec 8 05:38:30 2020 UTC (3 years, 5 months ago) by jsr166
Branch: MAIN
Changes since 1.387: +5 -5 lines
Log Message:
tidy javadoc

File Contents

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