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

File Contents

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