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

File Contents

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