ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinPool.java
Revision: 1.380
Committed: Sat Sep 26 11:01:30 2020 UTC (3 years, 8 months ago) by dl
Branch: MAIN
Changes since 1.379: +4 -2 lines
Log Message:
AccessControlContext compatibility

File Contents

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