ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinPool.java
Revision: 1.366
Committed: Sat Feb 1 20:20:17 2020 UTC (4 years, 4 months ago) by dl
Branch: MAIN
Changes since 1.365: +316 -346 lines
Log Message:
Reduce inessential FJP vs TPE differences

File Contents

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