ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinPool.java
Revision: 1.404
Committed: Sun Nov 14 16:19:13 2021 UTC (2 years, 6 months ago) by dl
Branch: MAIN
Changes since 1.403: +241 -166 lines
Log Message:
Reduce static initialization; unify termination checks

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