ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinPool.java
Revision: 1.372
Committed: Fri Feb 7 13:53:19 2020 UTC (4 years, 4 months ago) by dl
Branch: MAIN
Changes since 1.371: +59 -34 lines
Log Message:
improve cancellation and shutdown support

File Contents

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