ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinPool.java
Revision: 1.392
Committed: Sun Jan 31 13:35:43 2021 UTC (3 years, 4 months ago) by dl
Branch: MAIN
Changes since 1.391: +13 -7 lines
Log Message:
Allow self-steal retries; expanding cases covered with parallelism 0

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