1 /*
2 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
3 *
4 * This code is free software; you can redistribute it and/or modify it
5 * under the terms of the GNU General Public License version 2 only, as
6 * published by the Free Software Foundation. Oracle designates this
7 * particular file as subject to the "Classpath" exception as provided
8 * by Oracle in the LICENSE file that accompanied this code.
9 *
10 * This code is distributed in the hope that it will be useful, but WITHOUT
11 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
13 * version 2 for more details (a copy is included in the LICENSE file that
14 * accompanied this code).
15 *
16 * You should have received a copy of the GNU General Public License version
17 * 2 along with this work; if not, write to the Free Software Foundation,
18 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
19 *
20 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
21 * or visit www.oracle.com if you need additional information or have any
22 * questions.
23 */
24
25 /*
26 * This file is available under and governed by the GNU General Public
27 * License version 2 only, as published by the Free Software Foundation.
28 * However, the following notice accompanied the original version of this
29 * file:
30 *
31 * Written by Doug Lea with assistance from members of JCP JSR-166
32 * Expert Group and released to the public domain, as explained at
33 * http://creativecommons.org/publicdomain/zero/1.0/
34 */
35
36 package java.util.concurrent;
37
38 import java.lang.Thread.UncaughtExceptionHandler;
39 import java.lang.reflect.Field;
40 import java.util.ArrayList;
41 import java.util.Collection;
42 import java.util.Collections;
43 import java.util.List;
44 import java.util.Objects;
45 import java.util.function.Consumer;
46 import java.util.function.Predicate;
47 import java.util.concurrent.CountDownLatch;
48 import java.util.concurrent.locks.LockSupport;
49 import jdk.internal.access.JavaLangAccess;
50 import jdk.internal.access.JavaUtilConcurrentFJPAccess;
51 import jdk.internal.access.SharedSecrets;
52 import jdk.internal.misc.Unsafe;
53 import jdk.internal.vm.SharedThreadContainer;
54 import static java.util.concurrent.DelayScheduler.ScheduledForkJoinTask;
55
56 /**
57 * An {@link ExecutorService} for running {@link ForkJoinTask}s.
58 * A {@code ForkJoinPool} provides the entry point for submissions
59 * from non-{@code ForkJoinTask} clients, as well as management and
60 * monitoring operations.
61 *
62 * <p>A {@code ForkJoinPool} differs from other kinds of {@link
63 * ExecutorService} mainly by virtue of employing
64 * <em>work-stealing</em>: all threads in the pool attempt to find and
65 * execute tasks submitted to the pool and/or created by other active
66 * tasks (eventually blocking waiting for work if none exist). This
67 * enables efficient processing when most tasks spawn other subtasks
68 * (as do most {@code ForkJoinTask}s), as well as when many small
69 * tasks are submitted to the pool from external clients. Especially
70 * when setting <em>asyncMode</em> to true in constructors, {@code
71 * ForkJoinPool}s may also be appropriate for use with event-style
72 * tasks that are never joined. All worker threads are initialized
73 * with {@link Thread#isDaemon} set {@code true}.
74 *
75 * <p>A static {@link #commonPool()} is available and appropriate for
76 * most applications. The common pool is used by any ForkJoinTask that
77 * is not explicitly submitted to a specified pool. Using the common
78 * pool normally reduces resource usage (its threads are slowly
79 * reclaimed during periods of non-use, and reinstated upon subsequent
80 * use).
81 *
82 * <p>For applications that require separate or custom pools, a {@code
83 * ForkJoinPool} may be constructed with a given target parallelism
84 * level; by default, equal to the number of available processors.
85 * The pool attempts to maintain enough active (or available) threads
86 * by dynamically adding, suspending, or resuming internal worker
87 * threads, even if some tasks are stalled waiting to join others.
88 * However, no such adjustments are guaranteed in the face of blocked
89 * I/O or other unmanaged synchronization. The nested {@link
90 * ManagedBlocker} interface enables extension of the kinds of
91 * synchronization accommodated. The default policies may be
92 * overridden using a constructor with parameters corresponding to
93 * those documented in class {@link ThreadPoolExecutor}.
94 *
95 * <p>In addition to execution and lifecycle control methods, this
96 * class provides status check methods (for example
97 * {@link #getStealCount}) that are intended to aid in developing,
98 * tuning, and monitoring fork/join applications. Also, method
99 * {@link #toString} returns indications of pool state in a
100 * convenient form for informal monitoring.
101 *
102 * <p>As is the case with other ExecutorServices, there are three
103 * main task execution methods summarized in the following table.
104 * These are designed to be used primarily by clients not already
105 * engaged in fork/join computations in the current pool. The main
106 * forms of these methods accept instances of {@code ForkJoinTask},
107 * but overloaded forms also allow mixed execution of plain {@code
108 * Runnable}- or {@code Callable}- based activities as well. However,
109 * tasks that are already executing in a pool should normally instead
110 * use the within-computation forms listed in the table unless using
111 * async event-style tasks that are not usually joined, in which case
112 * there is little difference among choice of methods.
113 *
114 * <table class="plain">
115 * <caption>Summary of task execution methods</caption>
116 * <tr>
117 * <td></td>
118 * <th scope="col"> Call from non-fork/join clients</th>
119 * <th scope="col"> Call from within fork/join computations</th>
120 * </tr>
121 * <tr>
122 * <th scope="row" style="text-align:left"> Arrange async execution</th>
123 * <td> {@link #execute(ForkJoinTask)}</td>
124 * <td> {@link ForkJoinTask#fork}</td>
125 * </tr>
126 * <tr>
127 * <th scope="row" style="text-align:left"> Await and obtain result</th>
128 * <td> {@link #invoke(ForkJoinTask)}</td>
129 * <td> {@link ForkJoinTask#invoke}</td>
130 * </tr>
131 * <tr>
132 * <th scope="row" style="text-align:left"> Arrange exec and obtain Future</th>
133 * <td> {@link #submit(ForkJoinTask)}</td>
134 * <td> {@link ForkJoinTask#fork} (ForkJoinTasks <em>are</em> Futures)</td>
135 * </tr>
136 * </table>
137 *
138 * <p>Additionally, this class supports {@link
139 * ScheduledExecutorService} methods to delay or periodically execute
140 * tasks, as well as method {@link #submitWithTimeout} to cancel tasks
141 * that take too long. The scheduled functions or actions may create
142 * and invoke other {@linkplain ForkJoinTask ForkJoinTasks}. Delayed
143 * actions become enabled for execution and behave as ordinary submitted
144 * tasks when their delays elapse. Scheduling methods return
145 * {@linkplain ForkJoinTask ForkJoinTasks} that implement the {@link
146 * ScheduledFuture} interface. Resource exhaustion encountered after
147 * initial submission results in task cancellation. When time-based
148 * methods are used, shutdown policies match the default policies of
149 * class {@link ScheduledThreadPoolExecutor}: upon {@link #shutdown},
150 * existing periodic tasks will not re-execute, and the pool
151 * terminates when quiescent and existing delayed tasks
152 * complete. Method {@link #cancelDelayedTasksOnShutdown} may be used
153 * to disable all delayed tasks upon shutdown, and method {@link
154 * #shutdownNow} may be used to instead unconditionally initiate pool
155 * termination. Monitoring methods such as {@link #getQueuedTaskCount}
156 * do not include scheduled tasks that are not yet enabled for execution,
157 * which are reported separately by method {@link
158 * #getDelayedTaskCount}.
159 *
160 * <p>The parameters used to construct the common pool may be controlled by
161 * setting the following {@linkplain System#getProperty system properties}:
162 * <ul>
163 * <li>{@systemProperty java.util.concurrent.ForkJoinPool.common.parallelism}
164 * - the parallelism level, a non-negative integer. Usage is discouraged.
165 * Use {@link #setParallelism} instead.
166 * <li>{@systemProperty java.util.concurrent.ForkJoinPool.common.threadFactory}
167 * - the class name of a {@link ForkJoinWorkerThreadFactory}.
168 * The {@linkplain ClassLoader#getSystemClassLoader() system class loader}
169 * is used to load this class.
170 * <li>{@systemProperty java.util.concurrent.ForkJoinPool.common.exceptionHandler}
171 * - the class name of a {@link UncaughtExceptionHandler}.
172 * The {@linkplain ClassLoader#getSystemClassLoader() system class loader}
173 * is used to load this class.
174 * <li>{@systemProperty java.util.concurrent.ForkJoinPool.common.maximumSpares}
175 * - the maximum number of allowed extra threads to maintain target
176 * parallelism (default 256).
177 * </ul>
178 * If no thread factory is supplied via a system property, then the
179 * common pool uses a factory that uses the system class loader as the
180 * {@linkplain Thread#getContextClassLoader() thread context class loader}.
181 *
182 * Upon any error in establishing these settings, default parameters
183 * are used. It is possible to disable use of threads by using a
184 * factory that may return {@code null}, in which case some tasks may
185 * never execute. While possible, it is strongly discouraged to set
186 * the parallelism property to zero, which may be internally
187 * overridden in the presence of intrinsically async tasks.
188 *
189 * @implNote This implementation restricts the maximum number of
190 * running threads to 32767. Attempts to create pools with greater
191 * than the maximum number result in {@code
192 * IllegalArgumentException}. Also, this implementation rejects
193 * submitted tasks (that is, by throwing {@link
194 * RejectedExecutionException}) only when the pool is shut down or
195 * internal resources have been exhausted.
196 *
197 * @since 1.7
198 * @author Doug Lea
199 */
200 public class ForkJoinPool extends AbstractExecutorService
201 implements ScheduledExecutorService {
202
203 /*
204 * Implementation Overview
205 *
206 * This class and its nested classes provide the main
207 * functionality and control for a set of worker threads. Because
208 * most internal methods and nested classes are interrelated,
209 * their main rationale and descriptions are presented here;
210 * individual methods and nested classes contain only brief
211 * comments about details. Broadly: submissions from non-FJ
212 * threads enter into submission queues. Workers take these tasks
213 * and typically split them into subtasks that may be stolen by
214 * other workers. Work-stealing based on randomized scans
215 * generally leads to better throughput than "work dealing" in
216 * which producers assign tasks to idle threads, in part because
217 * threads that have finished other tasks before the signalled
218 * thread wakes up (which can be a long time) can take the task
219 * instead. Preference rules give first priority to processing
220 * tasks from their own queues (LIFO or FIFO, depending on mode),
221 * then to randomized FIFO steals of tasks in other queues.
222 *
223 * This framework began as vehicle for supporting structured
224 * parallelism using work-stealing, designed to work best when
225 * tasks are dag-structured (wrt completion dependencies), nested
226 * (generated using recursion or completions), of reasonable
227 * granularity, independent (wrt memory and resources) and where
228 * callers participate in task execution. These are properties
229 * that anyone aiming for efficient parallel multicore execution
230 * should design for. Over time, the scalability advantages of
231 * this framework led to extensions to better support more diverse
232 * usage contexts, amounting to weakenings or violations of each
233 * of these properties. Accommodating them may compromise
234 * performance, but mechanics discussed below include tradeoffs
235 * attempting to arrange that no single performance issue dominates.
236 *
237 * Here's a brief history of major revisions, each also with other
238 * minor features and changes.
239 *
240 * 1. Only handle recursively structured computational tasks
241 * 2. Async (FIFO) mode and striped submission queues
242 * 3. Completion-based tasks (mainly CountedCompleters)
243 * 4. CommonPool and parallelStream support
244 * 5. InterruptibleTasks for externally submitted tasks
245 * 6. Support ScheduledExecutorService methods
246 *
247 * Most changes involve adaptions of base algorithms using
248 * combinations of static and dynamic bitwise mode settings (both
249 * here and in ForkJoinTask), and subclassing of ForkJoinTask.
250 * There are a fair number of odd code constructions and design
251 * decisions for components that reside at the edge of Java vs JVM
252 * functionality.
253 *
254 * WorkQueues
255 * ==========
256 *
257 * Most operations occur within work-stealing queues (in nested
258 * class WorkQueue). These are special forms of Deques that
259 * support only three of the four possible end-operations -- push,
260 * pop, and poll (aka steal), under the further constraints that
261 * push and pop are called only from the owning thread (or, as
262 * extended here, under a lock), while poll may be called from
263 * other threads. (If you are unfamiliar with them, you probably
264 * want to read Herlihy and Shavit's book "The Art of
265 * Multiprocessor programming", chapter 16 describing these in
266 * more detail before proceeding.) The main work-stealing queue
267 * design is roughly similar to those in the papers "Dynamic
268 * Circular Work-Stealing Deque" by Chase and Lev, SPAA 2005
269 * (http://research.sun.com/scalable/pubs/index.html) and
270 * "Idempotent work stealing" by Michael, Saraswat, and Vechev,
271 * PPoPP 2009 (http://portal.acm.org/citation.cfm?id=1504186).
272 * The main differences ultimately stem from GC requirements that
273 * we null out taken slots as soon as we can, to maintain as small
274 * a footprint as possible even in programs generating huge
275 * numbers of tasks. To accomplish this, we shift the CAS
276 * arbitrating pop vs poll (steal) from being on the indices
277 * ("base" and "top") to the slots themselves. These provide the
278 * primary required memory ordering -- see "Correct and Efficient
279 * Work-Stealing for Weak Memory Models" by Le, Pop, Cohen, and
280 * Nardelli, PPoPP 2013
281 * (http://www.di.ens.fr/~zappa/readings/ppopp13.pdf) for an
282 * analysis of memory ordering requirements in work-stealing
283 * algorithms similar to the one used here. We use per-operation
284 * ordered writes of various kinds for accesses when required.
285 *
286 * We also support a user mode in which local task processing is
287 * in FIFO, not LIFO order, simply by using a local version of
288 * poll rather than pop. This can be useful in message-passing
289 * frameworks in which tasks are never joined, although with
290 * increased contention among task producers and consumers. Also,
291 * the same data structure (and class) is used for "submission
292 * queues" (described below) holding externally submitted tasks,
293 * that differ only in that a lock (using field "phase"; see below) is
294 * required by external callers to push and pop tasks.
295 *
296 * Adding tasks then takes the form of a classic array push(task)
297 * in a circular buffer:
298 * q.array[q.top++ % length] = task;
299 *
300 * The actual code needs to null-check and size-check the array,
301 * uses masking, not mod, for indexing a power-of-two-sized array,
302 * enforces memory ordering, supports resizing, and possibly
303 * signals waiting workers to start scanning (described below),
304 * which requires stronger forms of order accesses.
305 *
306 * The pop operation (always performed by owner) is of the form:
307 * if ((task = getAndSet(q.array, (q.top-1) % length, null)) != null)
308 * decrement top and return task;
309 * If this fails, the queue is empty. This operation is one part
310 * of the nextLocalTask method, that instead does a local-poll
311 * in FIFO mode.
312 *
313 * The poll operation is, basically:
314 * if (CAS nonnull task t = q.array[k = q.base % length] to null)
315 * increment base and return task;
316 *
317 * However, there are several more cases that must be dealt with.
318 * Some of them are just due to asynchrony; others reflect
319 * contention and stealing policies. Stepping through them
320 * illustrates some of the implementation decisions in this class.
321 *
322 * * Slot k must be read with an acquiring read, which it must
323 * anyway to dereference and run the task if the (acquiring)
324 * CAS succeeds.
325 *
326 * * q.base may change between reading and using its value to
327 * index the slot. To avoid trying to use the wrong t, the
328 * index and slot must be reread (not necessarily immediately)
329 * until consistent, unless this is a local poll by owner, in
330 * which case this form of inconsistency can only appear as t
331 * being null, below.
332 *
333 * * Similarly, q.array may change (due to a resize), unless this
334 * is a local poll by owner. Otherwise, when t is present, this
335 * only needs consideration on CAS failure (since a CAS
336 * confirms the non-resized case.)
337 *
338 * * t may appear null because a previous poll operation has not
339 * yet incremented q.base, so the read is from an already-taken
340 * index. This form of stall reflects the non-lock-freedom of
341 * the poll operation. Stalls can be detected by observing that
342 * q.base doesn't change on repeated reads of null t and when
343 * no other alternatives apply, spin-wait for it to settle. To
344 * reduce producing these kinds of stalls by other stealers, we
345 * encourage timely writes to indices using otherwise
346 * unnecessarily strong writes.
347 *
348 * * The CAS may fail, in which case we may want to retry unless
349 * there is too much contention. One goal is to balance and
350 * spread out the many forms of contention that may be
351 * encountered across polling and other operations to avoid
352 * sustained performance degradations. Across all cases where
353 * alternatives exist, a bounded number of CAS misses or stalls
354 * are tolerated (for slots, ctl, and elsewhere described
355 * below) before taking alternative action. These may move
356 * contention or retries elsewhere, which is still preferable
357 * to single-point bottlenecks.
358 *
359 * * Even though the check "top == base" is quiescently accurate
360 * to determine whether a queue is empty, it is not of much use
361 * when deciding whether to try to poll or repoll after a
362 * failure. Both top and base may move independently, and both
363 * lag updates to the underlying array. To reduce memory
364 * contention, non-owners avoid reading the "top" when
365 * possible, by using one-ahead reads to check whether to
366 * repoll, relying on the fact that a non-empty queue does not
367 * have two null slots in a row, except in cases (resizes and
368 * shifts) that can be detected with a secondary recheck that
369 * is less likely to conflict with owner writes.
370 *
371 * The poll operations in q.poll(), runWorker(), helpJoin(), and
372 * elsewhere differ with respect to whether other queues are
373 * available to try, and the presence or nature of screening steps
374 * when only some kinds of tasks can be taken. When alternatives
375 * (or failing) is an option, they uniformly give up after
376 * bounded numbers of stalls and/or CAS failures, which reduces
377 * contention when too many workers are polling too few tasks.
378 * Overall, in the aggregate, we ensure probabilistic
379 * non-blockingness of work-stealing at least until checking
380 * quiescence (which is intrinsically blocking): If an attempted
381 * steal fails in these ways, a scanning thief chooses a different
382 * target to try next. In contexts where alternatives aren't
383 * available, and when progress conditions can be isolated to
384 * values of a single variable, simple spinloops (using
385 * Thread.onSpinWait) are used to reduce memory traffic.
386 *
387 * WorkQueues are also used in a similar way for tasks submitted
388 * to the pool. We cannot mix these tasks in the same queues used
389 * by workers. Instead, we randomly associate submission queues
390 * with submitting threads (or carriers when using VirtualThreads)
391 * using a form of hashing. The ThreadLocalRandom probe value
392 * serves as a hash code for choosing existing queues, and may be
393 * randomly repositioned upon contention with other submitters.
394 * In essence, submitters act like workers except that they are
395 * restricted to executing local tasks that they submitted (or
396 * when known, subtasks thereof). Insertion of tasks in shared
397 * mode requires a lock. We use only a simple spinlock (as one
398 * role of field "phase") because submitters encountering a busy
399 * queue move to a different position to use or create other
400 * queues. They (spin) block when registering new queues, or
401 * indirectly elsewhere, by revisiting later.
402 *
403 * Management
404 * ==========
405 *
406 * The main throughput advantages of work-stealing stem from
407 * decentralized control -- workers mostly take tasks from
408 * themselves or each other, at rates that can exceed a billion
409 * per second. Most non-atomic control is performed by some form
410 * of scanning across or within queues. The pool itself creates,
411 * activates (enables scanning for and running tasks),
412 * deactivates, blocks, and terminates threads, all with minimal
413 * central information. There are only a few properties that we
414 * can globally track or maintain, so we pack them into a small
415 * number of variables, often maintaining atomicity without
416 * blocking or locking. Nearly all essentially atomic control
417 * state is held in a few variables that are by far most often
418 * read (not written) as status and consistency checks. We pack as
419 * much information into them as we can.
420 *
421 * Field "ctl" contains 64 bits holding information needed to
422 * atomically decide to add, enqueue (on an event queue), and
423 * dequeue and release workers. To enable this packing, we
424 * restrict maximum parallelism to (1<<15)-1 (which is far in
425 * excess of normal operating range) to allow ids, counts, and
426 * their negations (used for thresholding) to fit into 16bit
427 * subfields.
428 *
429 * Field "runState" and per-WorkQueue field "phase" play similar
430 * roles, as lockable, versioned counters. Field runState also
431 * includes monotonic event bits:
432 * * SHUTDOWN: no more external tasks accepted; STOP when quiescent
433 * * STOP: no more tasks run, and deregister all workers
434 * * CLEANED: all unexecuted tasks have been cancelled
435 * * TERMINATED: all workers deregistered and all queues cleaned
436 * The version tags enable detection of state changes (by
437 * comparing two reads) modulo bit wraparound. The bit range in
438 * each case suffices for purposes of determining quiescence,
439 * termination, avoiding ABA-like errors, and signal control, most
440 * of which are ultimately based on at most 15bit ranges (due to
441 * 32767 max total workers). RunState updates do not need to be
442 * atomic with respect to ctl updates, but because they are not,
443 * some care is required to avoid stalls. The seqLock properties
444 * detect changes and conditionally upgrade to coordinate with
445 * updates. It is typically held for less than a dozen
446 * instructions unless the queue array is being resized, during
447 * which contention is rare. To be conservative, lockRunState is
448 * implemented as a spin/sleep loop. Here and elsewhere spin
449 * constants are short enough to apply even on systems with few
450 * available processors. In addition to checking pool status,
451 * reads of runState sometimes serve as acquire fences before
452 * reading other fields.
453 *
454 * Field "parallelism" holds the target parallelism (normally
455 * corresponding to pool size). Users can dynamically reset target
456 * parallelism, but is only accessed when signalling or awaiting
457 * work, so only slowly has an effect in creating threads or
458 * letting them time out and terminate when idle.
459 *
460 * Array "queues" holds references to WorkQueues. It is updated
461 * (only during worker creation and termination) under the
462 * runState lock. It is otherwise concurrently readable but reads
463 * for use in scans (see below) are always prefaced by a volatile
464 * read of runState (or equivalent constructions), ensuring that
465 * its state is current at the point it is used (which is all we
466 * require). To simplify index-based operations, the array size is
467 * always a power of two, and all readers must tolerate null
468 * slots. Worker queues are at odd indices. Worker phase ids
469 * masked with SMASK match their index. Shared (submission) queues
470 * are at even indices. Grouping them together in this way aids in
471 * task scanning: At top-level, both kinds of queues should be
472 * sampled with approximately the same probability, which is
473 * simpler if they are all in the same array. But we also need to
474 * identify what kind they are without looking at them, leading to
475 * this odd/even scheme. One disadvantage is that there are
476 * usually many fewer submission queues, so there can be many
477 * wasted probes (null slots). But this is still cheaper than
478 * alternatives. Other loops over the queues array vary in origin
479 * and stride depending on whether they cover only submission
480 * (even) or worker (odd) queues or both, and whether they require
481 * randomness (in which case cyclically exhaustive strides may be
482 * used).
483 *
484 * All worker thread creation is on-demand, triggered by task
485 * submissions, replacement of terminated workers, and/or
486 * compensation for blocked workers. However, all other support
487 * code is set up to work with other policies. To ensure that we
488 * do not hold on to worker or task references that would prevent
489 * GC, all accesses to workQueues in waiting, signalling, and
490 * control methods are via indices into the queues array (which is
491 * one source of some of the messy code constructions here). In
492 * essence, the queues array serves as a weak reference
493 * mechanism. In particular, the stack top subfield of ctl stores
494 * indices, not references. Operations on queues obtained from
495 * these indices remain valid (with at most some unnecessary extra
496 * work) even if an underlying worker failed and was replaced by
497 * another at the same index. During termination, worker queue
498 * array updates are disabled.
499 *
500 * Queuing Idle Workers. Unlike HPC work-stealing frameworks, we
501 * cannot let workers spin indefinitely scanning for tasks when
502 * none can be found immediately, and we cannot start/resume
503 * workers unless there appear to be tasks available. On the
504 * other hand, we must quickly prod them into action when new
505 * tasks are submitted or generated. These latencies are mainly a
506 * function of JVM park/unpark (and underlying OS) performance,
507 * which can be slow and variable (even though usages are
508 * streamlined as much as possible). In many usages, ramp-up time
509 * is the main limiting factor in overall performance, which is
510 * compounded at program start-up by JIT compilation and
511 * allocation. On the other hand, throughput degrades when too
512 * many threads poll for too few tasks. (See below.)
513 *
514 * The "ctl" field atomically maintains total and "released"
515 * worker counts, plus the head of the available worker queue
516 * (actually stack, represented by the lower 32bit subfield of
517 * ctl). Released workers are those known to be scanning for
518 * and/or running tasks (we cannot accurately determine
519 * which). Unreleased ("available") workers are recorded in the
520 * ctl stack. These workers are made eligible for signalling by
521 * enqueuing in ctl (see method deactivate). This "queue" is a
522 * form of Treiber stack. This is ideal for activating threads in
523 * most-recently used order, and improves performance and
524 * locality, outweighing the disadvantages of being prone to
525 * contention and inability to release a worker unless it is
526 * topmost on stack. The top stack state holds the value of the
527 * "phase" field of the worker: its index and status, plus a
528 * version counter that, in addition to the count subfields (also
529 * serving as version stamps) provide protection against Treiber
530 * stack ABA effects.
531 *
532 * Creating workers. To create a worker, we pre-increment counts
533 * (serving as a reservation), and attempt to construct a
534 * ForkJoinWorkerThread via its factory. On starting, the new
535 * thread first invokes registerWorker, where it is assigned an
536 * index in the queues array (expanding the array if necessary).
537 * Upon any exception across these steps, or null return from
538 * factory, deregisterWorker adjusts counts and records
539 * accordingly. If a null return, the pool continues running with
540 * fewer than the target number workers. If exceptional, the
541 * exception is propagated, generally to some external caller.
542 *
543 * WorkQueue field "phase" encodes the queue array id in lower
544 * bits, and otherwise acts similarly to the pool runState field:
545 * The "IDLE" bit is clear while active (either a released worker
546 * or a locked external queue), with other bits serving as a
547 * version counter to distinguish changes across multiple reads.
548 * Note that phase field updates lag queue CAS releases; seeing a
549 * non-idle phase does not guarantee that the worker is available
550 * (and so is never checked in this way).
551 *
552 * The ctl field also serves as the basis for memory
553 * synchronization surrounding activation. This uses a more
554 * efficient version of a Dekker-like rule that task producers and
555 * consumers sync with each other by both writing/CASing ctl (even
556 * if to its current value). However, rather than CASing ctl to
557 * its current value in the common case where no action is
558 * required, we reduce write contention by ensuring that
559 * signalWork invocations are prefaced with a fully fenced memory
560 * access (which is usually needed anyway).
561 *
562 * Signalling. Signals (in signalWork) cause new or reactivated
563 * workers to scan for tasks. SignalWork is invoked in two cases:
564 * (1) When a task is pushed onto an empty queue, and (2) When a
565 * worker takes a top-level task from a queue that has additional
566 * tasks. Together, these suffice in O(log(#threads)) steps to
567 * fully activate with at least enough workers, and ideally no
568 * more than required. This ideal is unobtainable: Callers do not
569 * know whether another worker will finish its current task and
570 * poll for others without need of a signal (which is otherwise an
571 * advantage of work-stealing vs other schemes), and also must
572 * conservatively estimate the triggering conditions of emptiness
573 * or non-emptiness; all of which usually cause more activations
574 * than necessary (see below). (Method signalWork is also used as
575 * failsafe in case of Thread failures in deregisterWorker, to
576 * activate or create a new worker to replace them).
577 *
578 * Top-Level scheduling
579 * ====================
580 *
581 * Scanning. Method runWorker performs top-level scanning for (and
582 * execution of) tasks by polling a pseudo-random permutation of
583 * the array (by starting at a given index, and using a constant
584 * cyclically exhaustive stride.) It uses the same basic polling
585 * method as WorkQueue.poll(), but restarts with a different
586 * permutation on each rescan. The pseudorandom generator need
587 * not have high-quality statistical properties in the long
588 * term. We use Marsaglia XorShifts, seeded with the Weyl sequence
589 * from ThreadLocalRandom probes, which are cheap and suffice.
590 *
591 * Deactivation. When no tasks are found by a worker in runWorker,
592 * it invokes awaitWork, that first deactivates (to an IDLE
593 * phase). Avoiding missed signals during deactivation requires a
594 * (conservative) rescan, reactivating if there may be tasks to
595 * poll. Because idle workers are often not yet blocked (parked),
596 * we use a WorkQueue field to advertise that a waiter actually
597 * needs unparking upon signal.
598 *
599 * When tasks are constructed as (recursive) DAGs, top-level
600 * scanning is usually infrequent, and doesn't encounter most
601 * of the following problems addressed by runWorker and awaitWork:
602 *
603 * Locality. Polls are organized into "runs", continuing until
604 * empty or contended, while also minimizing interference by
605 * postponing bookeeping to ends of runs. This may reduce
606 * fairness.
607 *
608 * Contention. When many workers try to poll few queues, they
609 * often collide, generating CAS failures and disrupting locality
610 * of workers already running their tasks. This also leads to
611 * stalls when tasks cannot be taken because other workers have
612 * not finished poll operations, which is detected by reading
613 * ahead in queue arrays. In both cases, workers restart scans in a
614 * way that approximates randomized backoff.
615 *
616 * Oversignalling. When many short top-level tasks are present in
617 * a small number of queues, the above signalling strategy may
618 * activate many more workers than needed, worsening locality and
619 * contention problems, while also generating more global
620 * contention (field ctl is CASed on every activation and
621 * deactivation). We filter out (both in runWorker and
622 * signalWork) attempted signals that are surely not needed
623 * because the signalled tasks are already taken.
624 *
625 * Shutdown and Quiescence
626 * =======================
627 *
628 * Quiescence. Workers scan looking for work, giving up when they
629 * don't find any, without being sure that none are available.
630 * However, some required functionality relies on consensus about
631 * quiescence (also termination, discussed below). The count
632 * fields in ctl allow accurate discovery of states in which all
633 * workers are idle. However, because external (asynchronous)
634 * submitters are not part of this vote, these mechanisms
635 * themselves do not guarantee that the pool is in a quiescent
636 * state with respect to methods isQuiescent, shutdown (which
637 * begins termination when quiescent), helpQuiesce, and indirectly
638 * others including tryCompensate. Method quiescent() is used in
639 * all of these contexts. It provides checks that all workers are
640 * idle and there are no submissions that they could poll if they
641 * were not idle, retrying on inconsistent reads of queues and
642 * using the runState seqLock to retry on queue array updates.
643 * (It also reports quiescence if the pool is terminating.) A true
644 * report means only that there was a moment at which quiescence
645 * held. False negatives are inevitable (for example when queues
646 * indices lag updates, as described above), which is accommodated
647 * when (tentatively) idle by scanning for work etc, and then
648 * re-invoking. This includes cases in which the final unparked
649 * thread (in deactivate()) uses quiescent() to check for tasks
650 * that could have been added during a race window that would not
651 * be accompanied by a signal, in which case re-activating itself
652 * (or any other worker) to rescan. Method helpQuiesce acts
653 * similarly but cannot rely on ctl counts to determine that all
654 * workers are inactive because the caller and any others
655 * executing helpQuiesce are not included in counts.
656 *
657 * Termination. Termination is initiated by setting STOP in one of
658 * three ways (via methods tryTerminate and quiescent):
659 * * A call to shutdownNow, in which case all workers are
660 * interrupted, first ensuring that the queues array is stable,
661 * to avoid missing any workers.
662 * * A call to shutdown when quiescent, in which case method
663 * releaseWaiters is used to dequeue them, at which point they notice
664 * STOP state and return from runWorker to deregister();
665 * * The pool becomes quiescent() sometime after shutdown has
666 * been called, in which case releaseWaiters is also used to
667 * propagate as they deregister.
668 * Upon STOP, each worker, as well as external callers to
669 * tryTerminate (via close() etc) race to set CLEANED, indicating
670 * that all tasks have been cancelled. The implementation (method
671 * cleanQueues) balances cases in which there may be many tasks to
672 * cancel (benefitting from parallelism) versus contention and
673 * interference when many threads try to poll remaining queues,
674 * while also avoiding unnecessary rechecks, by using
675 * pseudorandom scans and giving up upon interference. This may be
676 * retried by the same caller only when there are no more
677 * registered workers, using the same criteria as method
678 * quiescent. When CLEANED and all workers have deregistered,
679 * TERMINATED is set, also signalling any caller of
680 * awaitTermination or close. Because shutdownNow-based
681 * termination relies on interrupts, there is no guarantee that
682 * workers will stop if their tasks ignore interrupts. Class
683 * InterruptibleTask (see below) further arranges runState checks
684 * before executing task bodies, and ensures interrupts while
685 * terminating. Even so, there are no guarantees because tasks may
686 * internally enter unbounded loops.
687 *
688 * Trimming workers. To release resources after periods of lack of
689 * use, a worker starting to wait when the pool is quiescent will
690 * time out and terminate if the pool has remained quiescent for
691 * period given by field keepAlive (default 60sec), which applies
692 * to the first timeout of a quiescent pool. Subsequent cases use
693 * minimal delays such that, if still quiescent, all will be
694 * released soon thereafter. This is checked by setting the
695 * "source" field of signallee to an invalid value, that will
696 * remain invalid only if it did not process any tasks.
697 *
698 * Joining Tasks
699 * =============
700 *
701 * The "Join" part of ForkJoinPools consists of a set of
702 * mechanisms that sometimes or always (depending on the kind of
703 * task) avoid context switching or adding worker threads when one
704 * task would otherwise be blocked waiting for completion of
705 * another, basically, just by running that task or one of its
706 * subtasks if not already taken. These mechanics are disabled for
707 * InterruptibleTasks, that guarantee that callers do not execute
708 * submitted tasks.
709 *
710 * The basic structure of joining is an extended spin/block scheme
711 * in which workers check for task completions status between
712 * steps to find other work, until relevant pool state stabilizes
713 * enough to believe that no such tasks are available, at which
714 * point blocking. This is usually a good choice of when to block
715 * that would otherwise be harder to approximate.
716 *
717 * These forms of helping may increase stack space usage, but that
718 * space is bounded in tree/dag structured procedurally parallel
719 * designs to be no more than that if a task were executed only by
720 * the joining thread. This is arranged by associated task
721 * subclasses that also help detect and control the ways in which
722 * this may occur.
723 *
724 * Normally, the first option when joining a task that is not done
725 * is to try to take it from the local queue and run it. Method
726 * tryRemoveAndExec tries to do so. For tasks with any form of
727 * subtasks that must be completed first, we try to locate these
728 * subtasks and run them as well. This is easy when local, but
729 * when stolen, steal-backs are restricted to the same rules as
730 * stealing (polling), which requires additional bookkeeping and
731 * scanning. This cost is still very much worthwhile because of
732 * its impact on task scheduling and resource control.
733 *
734 * The two methods for finding and executing subtasks vary in
735 * details. The algorithm in helpJoin entails a form of "linear
736 * helping". Each worker records (in field "source") the index of
737 * the internal queue from which it last stole a task. (Note:
738 * because chains cannot include even-numbered external queues,
739 * they are ignored, and 0 is an OK default. However, the source
740 * field is set anyway, or eventually to DROPPED, to ensure
741 * volatile memory synchronization effects.) The scan in method
742 * helpJoin uses these markers to try to find a worker to help
743 * (i.e., steal back a task from and execute it) that could make
744 * progress toward completion of the actively joined task. Thus,
745 * the joiner executes a task that would be on its own local deque
746 * if the to-be-joined task had not been stolen. This is a
747 * conservative variant of the approach described in Wagner &
748 * Calder "Leapfrogging: a portable technique for implementing
749 * efficient futures" SIGPLAN Notices, 1993
750 * (http://portal.acm.org/citation.cfm?id=155354). It differs
751 * mainly in that we only record queues, not full dependency
752 * links. This requires a linear scan of the queues to locate
753 * stealers, but isolates cost to when it is needed, rather than
754 * adding to per-task overhead. For CountedCompleters, the
755 * analogous method helpComplete doesn't need stealer-tracking,
756 * but requires a similar (but simpler) check of completion
757 * chains.
758 *
759 * In either case, searches can fail to locate stealers when
760 * stalls delay recording sources or issuing subtasks. We avoid
761 * some of these cases by using snapshotted values of ctl as a
762 * check that the numbers of workers are not changing, along with
763 * rescans to deal with contention and stalls. But even when
764 * accurately identified, stealers might not ever produce a task
765 * that the joiner can in turn help with.
766 *
767 * Related method helpAsyncBlocker does not directly rely on
768 * subtask structure, but instead avoids or postpones blocking of
769 * tagged tasks (CompletableFuture.AsynchronousCompletionTask) by
770 * executing other asyncs that can be processed in any order.
771 * This is currently invoked only in non-join-based blocking
772 * contexts from classes CompletableFuture and
773 * SubmissionPublisher, that could be further generalized.
774 *
775 * When any of the above fail to avoid blocking, we rely on
776 * "compensation" -- an indirect form of context switching that
777 * either activates an existing worker to take the place of the
778 * blocked one, or expands the number of workers.
779 *
780 * Compensation does not by default aim to keep exactly the target
781 * parallelism number of unblocked threads running at any given
782 * time. Some previous versions of this class employed immediate
783 * compensations for any blocked join. However, in practice, the
784 * vast majority of blockages are transient byproducts of GC and
785 * other JVM or OS activities that are made worse by replacement
786 * by causing longer-term oversubscription. These are inevitable
787 * without (unobtainably) perfect information about whether worker
788 * creation is actually necessary. False alarms are common enough
789 * to negatively impact performance, so compensation is by default
790 * attempted only when it appears possible that the pool could
791 * stall due to lack of any unblocked workers. However, we allow
792 * users to override defaults using the long form of the
793 * ForkJoinPool constructor. The compensation mechanism may also
794 * be bounded. Bounds for the commonPool better enable JVMs to
795 * cope with programming errors and abuse before running out of
796 * resources to do so.
797 *
798 * The ManagedBlocker extension API can't use helping so relies
799 * only on compensation in method awaitBlocker. This API was
800 * designed to highlight the uncertainty of compensation decisions
801 * by requiring implementation of method isReleasable to abort
802 * compensation during attempts to obtain a stable snapshot. But
803 * users now rely upon the fact that if isReleasable always
804 * returns false, the API can be used to obtain precautionary
805 * compensation, which is sometimes the only reasonable option
806 * when running unknown code in tasks; which is now supported more
807 * simply (see method beginCompensatedBlock).
808 *
809 * Common Pool
810 * ===========
811 *
812 * The static common pool always exists after static
813 * initialization. Since it (or any other created pool) need
814 * never be used, we minimize initial construction overhead and
815 * footprint to the setup of about a dozen fields, although with
816 * some System property parsing properties are set. The common pool is
817 * distinguished by having a null workerNamePrefix (which is an
818 * odd convention, but avoids the need to decode status in factory
819 * classes). It also has PRESET_SIZE config set if parallelism
820 * was configured by system property.
821 *
822 * When external threads use the common pool, they can perform
823 * subtask processing (see helpComplete and related methods) upon
824 * joins, unless they are submitted using ExecutorService
825 * submission methods, which implicitly disallow this. This
826 * caller-helps policy makes it sensible to set common pool
827 * parallelism level to one (or more) less than the total number
828 * of available cores, or even zero for pure caller-runs. External
829 * threads waiting for joins first check the common pool for their
830 * task, which fails quickly if the caller did not fork to common
831 * pool.
832 *
833 * Guarantees for common pool parallelism zero are limited to
834 * tasks that are joined by their callers in a tree-structured
835 * fashion or use CountedCompleters (as is true for jdk
836 * parallelStreams). Support infiltrates several methods,
837 * including those that retry helping steps until we are sure that
838 * none apply if there are no workers. To deal with conflicting
839 * requirements, uses of the commonPool that require async because
840 * caller-runs need not apply, ensure threads are enabled (by
841 * setting parallelism) via method asyncCommonPool before
842 * proceeding. (In principle, overriding zero parallelism needs to
843 * ensure at least one worker, but due to other backward
844 * compatibility contraints, ensures two.)
845 *
846 * As a more appropriate default in managed environments, unless
847 * overridden by system properties, we use workers of subclass
848 * InnocuousForkJoinWorkerThread for the commonPool. These
849 * workers do not belong to any user-defined ThreadGroup, and
850 * clear all ThreadLocals and reset the ContextClassLoader before
851 * (re)activating to execute top-level tasks. The associated
852 * mechanics may be JVM-dependent and must access particular
853 * Thread class fields to achieve this effect.
854 *
855 * InterruptibleTasks
856 * ====================
857 *
858 * Regular ForkJoinTasks manage task cancellation (method cancel)
859 * independently from the interrupted status of threads running
860 * tasks. Interrupts are issued internally only while
861 * terminating, to wake up workers and cancel queued tasks. By
862 * default, interrupts are cleared only when necessary to ensure
863 * that calls to LockSupport.park do not loop indefinitely (park
864 * returns immediately if the current thread is interrupted).
865 *
866 * To comply with ExecutorService specs, we use subclasses of
867 * abstract class InterruptibleTask for tasks that require
868 * stronger interruption and cancellation guarantees. External
869 * submitters never run these tasks, even if in the common pool
870 * (as indicated by ForkJoinTask.noUserHelp status bit).
871 * InterruptibleTasks include a "runner" field (implemented
872 * similarly to FutureTask) to support cancel(true). Upon pool
873 * shutdown, runners are interrupted so they can cancel. Since
874 * external joining callers never run these tasks, they must await
875 * cancellation by others, which can occur along several different
876 * paths.
877 *
878 * Across these APIs, rules for reporting exceptions for tasks
879 * with results accessed via join() differ from those via get(),
880 * which differ from those invoked using pool submit methods by
881 * non-workers (which comply with Future.get() specs). Internal
882 * usages of ForkJoinTasks ignore interrupted status when executing
883 * or awaiting completion. Otherwise, reporting task results or
884 * exceptions is preferred to throwing InterruptedExceptions,
885 * which are in turn preferred to timeouts. Similarly, completion
886 * status is preferred to reporting cancellation. Cancellation is
887 * reported as an unchecked exception by join(), and by worker
888 * calls to get(), but is otherwise wrapped in a (checked)
889 * ExecutionException.
890 *
891 * Worker Threads cannot be VirtualThreads, as enforced by
892 * requiring ForkJoinWorkerThreads in factories. There are
893 * several constructions relying on this. However as of this
894 * writing, virtual thread bodies are by default run as some form
895 * of InterruptibleTask.
896 *
897 * DelayScheduler
898 * ================
899 *
900 * This class supports ScheduledExecutorService methods by
901 * creating and starting a DelayScheduler on first use of these
902 * methods (via startDelayScheduler). The scheduler operates
903 * independently in its own thread, relaying tasks to the pool to
904 * execute when their delays elapse (see method
905 * executeEnabledScheduledTask). The only other interactions with
906 * the delayScheduler are to control shutdown and maintain
907 * shutdown-related policies in methods quiescent() and
908 * tryTerminate(). In particular, processing must deal with cases
909 * in which tasks are submitted before shutdown, but not enabled
910 * until afterwards, in which case they must bypass some screening
911 * to be allowed to run. Conversely, the DelayScheduler checks
912 * runState status and when enabled, completes termination, using
913 * only methods shutdownStatus and tryStopIfShutdown. All of these
914 * methods are final and have signatures referencing
915 * DelaySchedulers, so cannot conflict with those of any existing
916 * FJP subclasses.
917 *
918 * Memory placement
919 * ================
920 *
921 * Performance is very sensitive to placement of instances of
922 * ForkJoinPool and WorkQueues and their queue arrays, as well as
923 * the placement of their fields. Caches misses and contention due
924 * to false-sharing have been observed to slow down some programs
925 * by more than a factor of four. Effects may vary across initial
926 * memory configuarations, applications, and different garbage
927 * collectors and GC settings, so there is no perfect solution.
928 * Too much isolation may generate more cache misses in common
929 * cases (because some fields snd slots are usually read at the
930 * same time). The @Contended annotation provides only rough
931 * control (for good reason). Similarly for relying on fields
932 * being placed in size-sorted declaration order.
933 *
934 * We isolate the ForkJoinPool.ctl field that otherwise causes the
935 * most false-sharing misses with respect to other fields. Also,
936 * ForkJoinPool fields are ordered such that fields less prone to
937 * contention effects are first, offsetting those that otherwise
938 * would be, while also reducing total footprint vs using
939 * multiple @Contended regions, which tends to slow down
940 * less-contended applications. To help arrange this, some
941 * non-reference fields are declared as "long" even when ints or
942 * shorts would suffice. For class WorkQueue, an
943 * embedded @Contended isolates the very busy top index, and
944 * another segregates status and bookkeeping fields written
945 * (mostly) by owners, that otherwise interfere with reading
946 * array, top, and base fields. There are other variables commonly
947 * contributing to false-sharing-related performance issues
948 * (including fields of class Thread), but we can't do much about
949 * this except try to minimize access.
950 *
951 * Initial sizing and resizing of WorkQueue arrays is an even more
952 * delicate tradeoff because the best strategy systematically
953 * varies across garbage collectors. Small arrays are better for
954 * locality and reduce GC scan time, but large arrays reduce both
955 * direct false-sharing and indirect cases due to GC bookkeeping
956 * (cardmarks etc), and reduce the number of resizes, which are
957 * not especially fast because they require atomic transfers.
958 * Currently, arrays are initialized to be just large enough to
959 * avoid resizing in most tree-structured tasks, but grow rapidly
960 * until large. (Maintenance note: any changes in fields, queues,
961 * or their uses, or JVM layout policies, must be accompanied by
962 * re-evaluation of these placement and sizing decisions.)
963 *
964 * Style notes
965 * ===========
966 *
967 * Memory ordering relies mainly on atomic operations (CAS,
968 * getAndSet, getAndAdd) along with moded accesses. These use
969 * jdk-internal Unsafe for atomics and special memory modes,
970 * rather than VarHandles, to avoid initialization dependencies in
971 * other jdk components that require early parallelism. This can
972 * be awkward and ugly, but also reflects the need to control
973 * outcomes across the unusual cases that arise in very racy code
974 * with very few invariants. All atomic task slot updates use
975 * Unsafe operations requiring offset positions, not indices, as
976 * computed by method slotOffset. All fields are read into locals
977 * before use, and null-checked if they are references, even if
978 * they can never be null under current usages. Usually,
979 * computations (held in local variables) are defined as soon as
980 * logically enabled, sometimes to convince compilers that they
981 * may be performed despite memory ordering constraints. Array
982 * accesses using masked indices include checks (that are always
983 * true) that the array length is non-zero to avoid compilers
984 * inserting more expensive traps. This is usually done in a
985 * "C"-like style of listing declarations at the heads of methods
986 * or blocks, and using inline assignments on first encounter.
987 * Nearly all explicit checks lead to bypass/return, not exception
988 * throws, because they may legitimately arise during shutdown. A
989 * few unusual loop constructions encourage (with varying
990 * effectiveness) JVMs about where (not) to place safepoints. All
991 * public methods screen arguments (mainly null checks) before
992 * creating or executing tasks.
993 *
994 * There is a lot of representation-level coupling among classes
995 * ForkJoinPool, ForkJoinWorkerThread, and ForkJoinTask. The
996 * fields of WorkQueue maintain data structures managed by
997 * ForkJoinPool, so are directly accessed. There is little point
998 * trying to reduce this, since any associated future changes in
999 * representations will need to be accompanied by algorithmic
1000 * changes anyway. Several methods intrinsically sprawl because
1001 * they must accumulate sets of consistent reads of fields held in
1002 * local variables. Some others are artificially broken up to
1003 * reduce producer/consumer imbalances due to dynamic compilation.
1004 * There are also other coding oddities (including several
1005 * unnecessary-looking hoisted null checks) that help some methods
1006 * perform reasonably even when interpreted (not compiled).
1007 *
1008 * The order of declarations in this file is (with a few exceptions):
1009 * (1) Static configuration constants
1010 * (2) Static utility functions
1011 * (3) Nested (static) classes
1012 * (4) Fields, along with constants used when unpacking some of them
1013 * (5) Internal control methods
1014 * (6) Callbacks and other support for ForkJoinTask methods
1015 * (7) Exported methods
1016 * (8) Static block initializing statics in minimally dependent order
1017 *
1018 */
1019
1020 // static configuration constants
1021
1022 /**
1023 * Default idle timeout value (in milliseconds) for idle threads
1024 * to park waiting for new work before terminating.
1025 */
1026 static final long DEFAULT_KEEPALIVE = 60_000L;
1027
1028 /**
1029 * Undershoot tolerance for idle timeouts, also serving as the
1030 * minimum allowed timeout value.
1031 */
1032 static final long TIMEOUT_SLOP = 20L;
1033
1034 /**
1035 * The default value for common pool maxSpares. Overridable using
1036 * the "java.util.concurrent.ForkJoinPool.common.maximumSpares"
1037 * system property. The default value is far in excess of normal
1038 * requirements, but also far short of maximum capacity and typical OS
1039 * thread limits, so allows JVMs to catch misuse/abuse before
1040 * running out of resources needed to do so.
1041 */
1042 static final int DEFAULT_COMMON_MAX_SPARES = 256;
1043
1044 /**
1045 * Initial capacity of work-stealing queue array.
1046 * Must be a power of two, at least 2. See above.
1047 */
1048 static final int INITIAL_QUEUE_CAPACITY = 1 << 6;
1049
1050 // conversions among short, int, long
1051 static final int SMASK = 0xffff; // (unsigned) short bits
1052 static final long LMASK = 0xffffffffL; // lower 32 bits of long
1053 static final long UMASK = ~LMASK; // upper 32 bits
1054
1055 // masks and sentinels for queue indices
1056 static final int MAX_CAP = 0x7fff; // max # workers
1057 static final int EXTERNAL_ID_MASK = 0x3ffe; // max external queue id
1058 static final int INVALID_ID = 0x4000; // unused external queue id
1059
1060 // pool.runState bits
1061 static final long STOP = 1L << 0; // terminating
1062 static final long SHUTDOWN = 1L << 1; // terminate when quiescent
1063 static final long CLEANED = 1L << 2; // stopped and queues cleared
1064 static final long TERMINATED = 1L << 3; // only set if STOP also set
1065 static final long RS_LOCK = 1L << 4; // lowest seqlock bit
1066
1067 // spin/sleep limits for runState locking and elsewhere
1068 static final int SPIN_WAITS = 1 << 7; // max calls to onSpinWait
1069 static final int MIN_SLEEP = 1 << 10; // approx 1 usec as nanos
1070 static final int MAX_SLEEP = 1 << 20; // approx 1 sec as nanos
1071
1072 // {pool, workQueue} config bits
1073 static final int FIFO = 1 << 0; // fifo queue or access mode
1074 static final int CLEAR_TLS = 1 << 1; // set for Innocuous workers
1075 static final int PRESET_SIZE = 1 << 2; // size was set by property
1076
1077 // others
1078 static final int DROPPED = 1 << 16; // removed from ctl counts
1079 static final int UNCOMPENSATE = 1 << 16; // tryCompensate return
1080 static final int IDLE = 1 << 16; // phase seqlock/version count
1081 static final int MIN_QUEUES_SIZE = 1 << 4; // ensure external slots
1082
1083 /*
1084 * Bits and masks for ctl and bounds are packed with 4 16 bit subfields:
1085 * RC: Number of released (unqueued) workers
1086 * TC: Number of total workers
1087 * SS: version count and status of top waiting thread
1088 * ID: poolIndex of top of Treiber stack of waiters
1089 *
1090 * When convenient, we can extract the lower 32 stack top bits
1091 * (including version bits) as sp=(int)ctl. When sp is non-zero,
1092 * there are waiting workers. Count fields may be transiently
1093 * negative during termination because of out-of-order updates.
1094 * To deal with this, we use casts in and out of "short" and/or
1095 * signed shifts to maintain signedness. Because it occupies
1096 * uppermost bits, we can add one release count using getAndAdd of
1097 * RC_UNIT, rather than CAS, when returning from a blocked join.
1098 * Other updates of multiple subfields require CAS.
1099 */
1100
1101 // Release counts
1102 static final int RC_SHIFT = 48;
1103 static final long RC_UNIT = 0x0001L << RC_SHIFT;
1104 static final long RC_MASK = 0xffffL << RC_SHIFT;
1105 // Total counts
1106 static final int TC_SHIFT = 32;
1107 static final long TC_UNIT = 0x0001L << TC_SHIFT;
1108 static final long TC_MASK = 0xffffL << TC_SHIFT;
1109
1110 /*
1111 * All atomic operations on task arrays (queues) use Unsafe
1112 * operations that take array offsets versus indices, based on
1113 * array base and shift constants established during static
1114 * initialization.
1115 */
1116 static final long ABASE;
1117 static final int ASHIFT;
1118
1119 // Static utilities
1120
1121 /**
1122 * Returns the array offset corresponding to the given index for
1123 * Unsafe task queue operations
1124 */
1125 static long slotOffset(int index) {
1126 return ((long)index << ASHIFT) + ABASE;
1127 }
1128
1129 // Nested classes
1130
1131 /**
1132 * Factory for creating new {@link ForkJoinWorkerThread}s.
1133 * A {@code ForkJoinWorkerThreadFactory} must be defined and used
1134 * for {@code ForkJoinWorkerThread} subclasses that extend base
1135 * functionality or initialize threads with different contexts.
1136 */
1137 public static interface ForkJoinWorkerThreadFactory {
1138 /**
1139 * Returns a new worker thread operating in the given pool.
1140 * Returning null or throwing an exception may result in tasks
1141 * never being executed. If this method throws an exception,
1142 * it is relayed to the caller of the method (for example
1143 * {@code execute}) causing attempted thread creation. If this
1144 * method returns null or throws an exception, it is not
1145 * retried until the next attempted creation (for example
1146 * another call to {@code execute}).
1147 *
1148 * @param pool the pool this thread works in
1149 * @return the new worker thread, or {@code null} if the request
1150 * to create a thread is rejected
1151 * @throws NullPointerException if the pool is null
1152 */
1153 public ForkJoinWorkerThread newThread(ForkJoinPool pool);
1154 }
1155
1156 /**
1157 * Default ForkJoinWorkerThreadFactory implementation; creates a
1158 * new ForkJoinWorkerThread using the system class loader as the
1159 * thread context class loader.
1160 */
1161 static final class DefaultForkJoinWorkerThreadFactory
1162 implements ForkJoinWorkerThreadFactory {
1163 public final ForkJoinWorkerThread newThread(ForkJoinPool pool) {
1164 return ((pool.workerNamePrefix == null) ? // is commonPool
1165 new ForkJoinWorkerThread.InnocuousForkJoinWorkerThread(pool) :
1166 new ForkJoinWorkerThread(null, pool, true, false));
1167 }
1168 }
1169
1170 /**
1171 * Queues supporting work-stealing as well as external task
1172 * submission. See above for descriptions and algorithms.
1173 */
1174 static final class WorkQueue {
1175 // fields declared in order of their likely layout on most VMs
1176 final ForkJoinWorkerThread owner; // null if shared
1177 ForkJoinTask<?>[] array; // the queued tasks; power of 2 size
1178 int base; // index of next slot for poll
1179 final int config; // mode bits
1180
1181 @jdk.internal.vm.annotation.Contended("t") // segregate
1182 int top; // index of next slot for push
1183
1184 // fields otherwise causing more unnecessary false-sharing cache misses
1185 @jdk.internal.vm.annotation.Contended("w")
1186 volatile int phase; // versioned active status
1187 @jdk.internal.vm.annotation.Contended("w")
1188 int stackPred; // pool stack (ctl) predecessor link
1189 @jdk.internal.vm.annotation.Contended("w")
1190 volatile int parking; // nonzero if parked in awaitWork
1191 @jdk.internal.vm.annotation.Contended("w")
1192 volatile int source; // source queue id (or DROPPED)
1193 @jdk.internal.vm.annotation.Contended("w")
1194 int nsteals; // number of steals from other queues
1195
1196 // Support for atomic operations
1197 private static final Unsafe U;
1198 private static final long PHASE;
1199 private static final long BASE;
1200 private static final long TOP;
1201 private static final long ARRAY;
1202
1203 final void updateBase(int v) {
1204 U.putIntVolatile(this, BASE, v);
1205 }
1206 final void updateTop(int v) {
1207 U.putIntOpaque(this, TOP, v);
1208 }
1209 final void updateArray(ForkJoinTask<?>[] a) {
1210 U.getAndSetReference(this, ARRAY, a);
1211 }
1212 final void unlockPhase() {
1213 U.getAndAddInt(this, PHASE, IDLE);
1214 }
1215 final boolean tryLockPhase() { // seqlock acquire
1216 int p;
1217 return (((p = phase) & IDLE) != 0 &&
1218 U.compareAndSetInt(this, PHASE, p, p + IDLE));
1219 }
1220
1221 /**
1222 * Constructor. For internal queues, most fields are initialized
1223 * upon thread start in pool.registerWorker.
1224 */
1225 WorkQueue(ForkJoinWorkerThread owner, int id, int cfg,
1226 boolean clearThreadLocals) {
1227 this.config = (clearThreadLocals) ? cfg | CLEAR_TLS : cfg;
1228 if ((this.owner = owner) == null) {
1229 array = new ForkJoinTask<?>[INITIAL_QUEUE_CAPACITY];
1230 phase = id | IDLE;
1231 }
1232 }
1233
1234 /**
1235 * Returns an exportable index (used by ForkJoinWorkerThread).
1236 */
1237 final int getPoolIndex() {
1238 return (phase & 0xffff) >>> 1; // ignore odd/even tag bit
1239 }
1240
1241 /**
1242 * Returns the approximate number of tasks in the queue.
1243 */
1244 final int queueSize() {
1245 int unused = phase; // for ordering effect
1246 return Math.max(top - base, 0); // ignore transient negative
1247 }
1248
1249 /**
1250 * Pushes a task. Called only by owner or if already locked
1251 *
1252 * @param task the task; no-op if null
1253 * @param pool the pool to signal if was previously empty, else null
1254 * @param internal if caller owns this queue
1255 * @throws RejectedExecutionException if array could not be resized
1256 */
1257 final void push(ForkJoinTask<?> task, ForkJoinPool pool, boolean internal) {
1258 int s = top, b = base, m, cap, room; ForkJoinTask<?>[] a, na;
1259 if ((a = array) != null && (cap = a.length) > 0) { // else disabled
1260 int k = (m = cap - 1) & s;
1261 if ((room = m - (s - b)) >= 0) {
1262 top = s + 1;
1263 long pos = slotOffset(k);
1264 if (!internal)
1265 U.putReference(a, pos, task); // inside lock
1266 else
1267 U.getAndSetReference(a, pos, task); // fully fenced
1268 if (room == 0 && (na = growArray(a, cap, s)) != null)
1269 k = ((a = na).length - 1) & s; // resize
1270 }
1271 if (!internal)
1272 unlockPhase();
1273 if (room < 0)
1274 throw new RejectedExecutionException("Queue capacity exceeded");
1275 if (pool != null &&
1276 (room == 0 ||
1277 U.getReferenceAcquire(a, slotOffset(m & (s - 1))) == null))
1278 pool.signalWork(a, k); // may have appeared empty
1279 }
1280 }
1281
1282 /**
1283 * Resizes the queue array unless out of memory.
1284 * @param a old array
1285 * @param cap old array capacity
1286 * @param s current top
1287 * @return new array, or null on failure
1288 */
1289 private ForkJoinTask<?>[] growArray(ForkJoinTask<?>[] a, int cap, int s) {
1290 int newCap = (cap >= 1 << 16) ? cap << 1 : cap << 2;
1291 ForkJoinTask<?>[] newArray = null;
1292 if (a != null && a.length == cap && cap > 0 && newCap > 0) {
1293 try {
1294 newArray = new ForkJoinTask<?>[newCap];
1295 } catch (OutOfMemoryError ex) {
1296 }
1297 if (newArray != null) { // else throw on next push
1298 int mask = cap - 1, newMask = newCap - 1;
1299 for (int k = s, j = cap; j > 0; --j, --k) {
1300 ForkJoinTask<?> u; // poll old, push to new
1301 if ((u = (ForkJoinTask<?>)U.getAndSetReference(
1302 a, slotOffset(k & mask), null)) == null)
1303 break; // lost to pollers
1304 newArray[k & newMask] = u;
1305 }
1306 updateArray(newArray); // fully fenced
1307 }
1308 }
1309 return newArray;
1310 }
1311
1312 /**
1313 * Takes next task, if one exists, in lifo order.
1314 */
1315 private ForkJoinTask<?> localPop() {
1316 ForkJoinTask<?> t = null;
1317 int s = top - 1, cap; long k; ForkJoinTask<?>[] a;
1318 if ((a = array) != null && (cap = a.length) > 0 &&
1319 U.getReference(a, k = slotOffset((cap - 1) & s)) != null &&
1320 (t = (ForkJoinTask<?>)U.getAndSetReference(a, k, null)) != null)
1321 updateTop(s);
1322 return t;
1323 }
1324
1325 /**
1326 * Takes next task, if one exists, in fifo order.
1327 */
1328 private ForkJoinTask<?> localPoll() {
1329 ForkJoinTask<?> t = null;
1330 int p = top, cap; ForkJoinTask<?>[] a;
1331 if ((a = array) != null && (cap = a.length) > 0) {
1332 for (int b = base; p - b > 0; ) {
1333 int nb = b + 1;
1334 long k = slotOffset((cap - 1) & b);
1335 if (U.getReference(a, k) == null) {
1336 if (nb == p)
1337 break; // else base is lagging
1338 while (b == (b = U.getIntAcquire(this, BASE)))
1339 Thread.onSpinWait(); // spin to reduce memory traffic
1340 }
1341 else if ((t = (ForkJoinTask<?>)
1342 U.getAndSetReference(a, k, null)) != null) {
1343 updateBase(nb);
1344 break;
1345 }
1346 else
1347 b = base;
1348 }
1349 }
1350 return t;
1351 }
1352
1353 /**
1354 * Takes next task, if one exists, using configured mode.
1355 */
1356 final ForkJoinTask<?> nextLocalTask() {
1357 return (config & FIFO) == 0 ? localPop() : localPoll();
1358 }
1359
1360 /**
1361 * Pops the given task only if it is at the current top.
1362 * @param task the task. Caller must ensure non-null.
1363 * @param internal if caller owns this queue
1364 */
1365 final boolean tryUnpush(ForkJoinTask<?> task, boolean internal) {
1366 boolean taken = false;
1367 ForkJoinTask<?>[] a = array;
1368 int p = top, s = p - 1, cap; long k;
1369 if (a != null && (cap = a.length) > 0 &&
1370 U.getReference(a, k = slotOffset((cap - 1) & s)) == task &&
1371 (internal || tryLockPhase())) {
1372 if (top == p && U.compareAndSetReference(a, k, task, null)) {
1373 taken = true;
1374 updateTop(s);
1375 }
1376 if (!internal)
1377 unlockPhase();
1378 }
1379 return taken;
1380 }
1381
1382 /**
1383 * Returns next task, if one exists, in order specified by mode.
1384 */
1385 final ForkJoinTask<?> peek() {
1386 ForkJoinTask<?>[] a = array;
1387 int b = base, cfg = config, p = top, cap;
1388 if (p != b && a != null && (cap = a.length) > 0) {
1389 if ((cfg & FIFO) == 0)
1390 return a[(cap - 1) & (p - 1)];
1391 else { // skip over in-progress removals
1392 ForkJoinTask<?> t;
1393 for ( ; p - b > 0; ++b) {
1394 if ((t = a[(cap - 1) & b]) != null)
1395 return t;
1396 }
1397 }
1398 }
1399 return null;
1400 }
1401
1402 /**
1403 * Polls for a task. Used only by non-owners.
1404 */
1405 final ForkJoinTask<?> poll() {
1406 for (int pb = -1, b; ; pb = b) { // track progress
1407 ForkJoinTask<?> t; int cap, nb; long k; ForkJoinTask<?>[] a;
1408 if ((a = array) == null || (cap = a.length) <= 0)
1409 break;
1410 t = (ForkJoinTask<?>)U.getReferenceAcquire(
1411 a, k = slotOffset((cap - 1) & (b = base)));
1412 Object u = U.getReference( // next slot
1413 a, slotOffset((cap - 1) & (nb = b + 1)));
1414 if (base != b) // inconsistent
1415 ;
1416 else if (t == null) {
1417 if (u == null && top - b <= 0)
1418 break; // empty
1419 if (pb == b)
1420 Thread.onSpinWait(); // stalled
1421 }
1422 else if (U.compareAndSetReference(a, k, t, null)) {
1423 updateBase(nb);
1424 return t;
1425 }
1426 }
1427 return null;
1428 }
1429
1430 // specialized execution methods
1431
1432 /*
1433 * Two version (lifo and fifo) of top-level execution, split
1434 * across modes to better isolate task dispatch and local
1435 * processing from top-level scheduling.
1436 */
1437 final void topLevelExecLifo(ForkJoinTask<?> task) {
1438 while (task != null) {
1439 task.doExec();
1440 task = localPop();
1441 }
1442 }
1443
1444 final void topLevelExecFifo(ForkJoinTask<?> task) {
1445 while (task != null) {
1446 task.doExec();
1447 task = localPoll();
1448 }
1449 }
1450
1451 /**
1452 * Deep form of tryUnpush: Traverses from top and removes and
1453 * runs task if present.
1454 */
1455 final void tryRemoveAndExec(ForkJoinTask<?> task, boolean internal) {
1456 ForkJoinTask<?>[] a = array;
1457 int b = base, p = top, s = p - 1, d = p - b, cap;
1458 if (a != null && (cap = a.length) > 0) {
1459 for (int m = cap - 1, i = s; d > 0; --i, --d) {
1460 long k; boolean taken;
1461 ForkJoinTask<?> t = (ForkJoinTask<?>)U.getReference(
1462 a, k = slotOffset(i & m));
1463 if (t == null)
1464 break;
1465 if (t == task) {
1466 if (!internal && !tryLockPhase())
1467 break; // fail if locked
1468 if (taken =
1469 (top == p &&
1470 U.compareAndSetReference(a, k, task, null))) {
1471 if (i == s) // act as pop
1472 updateTop(s);
1473 else if (i == base) // act as poll
1474 updateBase(i + 1);
1475 else { // swap with top
1476 U.putReferenceVolatile(
1477 a, k, (ForkJoinTask<?>)
1478 U.getAndSetReference(
1479 a, slotOffset(s & m), null));
1480 updateTop(s);
1481 }
1482 }
1483 if (!internal)
1484 unlockPhase();
1485 if (taken)
1486 task.doExec();
1487 break;
1488 }
1489 }
1490 }
1491 }
1492
1493 /**
1494 * Tries to pop and run tasks within the target's computation
1495 * until done, not found, or limit exceeded.
1496 *
1497 * @param task root of computation
1498 * @param limit max runs, or zero for no limit
1499 * @return task status if known to be done
1500 */
1501 final int helpComplete(ForkJoinTask<?> task, boolean internal, int limit) {
1502 int status = 0;
1503 if (task != null) {
1504 outer: for (;;) {
1505 ForkJoinTask<?>[] a; boolean taken; Object o;
1506 int stat, p, s, cap;
1507 if ((stat = task.status) < 0) {
1508 status = stat;
1509 break;
1510 }
1511 if ((a = array) == null || (cap = a.length) <= 0)
1512 break;
1513 long k = slotOffset((cap - 1) & (s = (p = top) - 1));
1514 if (!((o = U.getReference(a, k)) instanceof CountedCompleter))
1515 break;
1516 CountedCompleter<?> t = (CountedCompleter<?>)o, f = t;
1517 for (int steps = cap;;) { // bound path
1518 if (f == task)
1519 break;
1520 if ((f = f.completer) == null || --steps == 0)
1521 break outer;
1522 }
1523 if (!internal && !tryLockPhase())
1524 break;
1525 if (taken =
1526 (top == p &&
1527 U.compareAndSetReference(a, k, t, null)))
1528 updateTop(s);
1529 if (!internal)
1530 unlockPhase();
1531 if (!taken)
1532 break;
1533 t.doExec();
1534 if (limit != 0 && --limit == 0)
1535 break;
1536 }
1537 }
1538 return status;
1539 }
1540
1541 /**
1542 * Tries to poll and run AsynchronousCompletionTasks until
1543 * none found or blocker is released
1544 *
1545 * @param blocker the blocker
1546 */
1547 final void helpAsyncBlocker(ManagedBlocker blocker) {
1548 for (;;) {
1549 ForkJoinTask<?> t; ForkJoinTask<?>[] a; int b, cap; long k;
1550 if ((a = array) == null || (cap = a.length) <= 0)
1551 break;
1552 t = (ForkJoinTask<?>)U.getReferenceAcquire(
1553 a, k = slotOffset((cap - 1) & (b = base)));
1554 if (t == null) {
1555 if (top - b <= 0)
1556 break;
1557 }
1558 else if (!(t instanceof CompletableFuture
1559 .AsynchronousCompletionTask))
1560 break;
1561 if (blocker != null && blocker.isReleasable())
1562 break;
1563 if (base == b && t != null &&
1564 U.compareAndSetReference(a, k, t, null)) {
1565 updateBase(b + 1);
1566 t.doExec();
1567 }
1568 }
1569 }
1570
1571 // misc
1572
1573 /**
1574 * Cancels all local tasks. Called only by owner.
1575 */
1576 final void cancelTasks() {
1577 for (ForkJoinTask<?> t; (t = localPop()) != null; ) {
1578 try {
1579 t.cancel(false);
1580 } catch (Throwable ignore) {
1581 }
1582 }
1583 }
1584
1585 /**
1586 * Returns true if internal and not known to be blocked.
1587 */
1588 final boolean isApparentlyUnblocked() {
1589 Thread wt; Thread.State s;
1590 return ((wt = owner) != null && (phase & IDLE) != 0 &&
1591 (s = wt.getState()) != Thread.State.BLOCKED &&
1592 s != Thread.State.WAITING &&
1593 s != Thread.State.TIMED_WAITING);
1594 }
1595
1596 static {
1597 U = Unsafe.getUnsafe();
1598 Class<WorkQueue> klass = WorkQueue.class;
1599 PHASE = U.objectFieldOffset(klass, "phase");
1600 BASE = U.objectFieldOffset(klass, "base");
1601 TOP = U.objectFieldOffset(klass, "top");
1602 ARRAY = U.objectFieldOffset(klass, "array");
1603 }
1604 }
1605
1606 // static fields (initialized in static initializer below)
1607
1608 /**
1609 * Creates a new ForkJoinWorkerThread. This factory is used unless
1610 * overridden in ForkJoinPool constructors.
1611 */
1612 public static final ForkJoinWorkerThreadFactory
1613 defaultForkJoinWorkerThreadFactory;
1614
1615 /**
1616 * Common (static) pool. Non-null for public use unless a static
1617 * construction exception, but internal usages null-check on use
1618 * to paranoically avoid potential initialization circularities
1619 * as well as to simplify generated code.
1620 */
1621 static final ForkJoinPool common;
1622
1623 /**
1624 * Sequence number for creating worker names
1625 */
1626 private static volatile int poolIds;
1627
1628 /**
1629 * For VirtualThread intrinsics
1630 */
1631 private static final JavaLangAccess JLA;
1632
1633 // fields declared in order of their likely layout on most VMs
1634 volatile CountDownLatch termination; // lazily constructed
1635 final Predicate<? super ForkJoinPool> saturate;
1636 final ForkJoinWorkerThreadFactory factory;
1637 final UncaughtExceptionHandler ueh; // per-worker UEH
1638 final SharedThreadContainer container;
1639 final String workerNamePrefix; // null for common pool
1640 final String poolName;
1641 volatile DelayScheduler delayScheduler; // lazily constructed
1642 WorkQueue[] queues; // main registry
1643 volatile long runState; // versioned, lockable
1644 final long keepAlive; // milliseconds before dropping if idle
1645 final long config; // static configuration bits
1646 volatile long stealCount; // collects worker nsteals
1647 volatile long threadIds; // for worker thread names
1648
1649 @jdk.internal.vm.annotation.Contended("fjpctl") // segregate
1650 volatile long ctl; // main pool control
1651 @jdk.internal.vm.annotation.Contended("fjpctl") // colocate
1652 int parallelism; // target number of workers
1653
1654 // Support for atomic operations
1655 private static final Unsafe U;
1656 private static final long CTL;
1657 private static final long RUNSTATE;
1658 private static final long PARALLELISM;
1659 private static final long THREADIDS;
1660 private static final long TERMINATION;
1661 private static final Object POOLIDS_BASE;
1662 private static final long POOLIDS;
1663
1664 private boolean compareAndSetCtl(long c, long v) {
1665 return U.compareAndSetLong(this, CTL, c, v);
1666 }
1667 private long compareAndExchangeCtl(long c, long v) {
1668 return U.compareAndExchangeLong(this, CTL, c, v);
1669 }
1670 private long getAndAddCtl(long v) {
1671 return U.getAndAddLong(this, CTL, v);
1672 }
1673 private long incrementThreadIds() {
1674 return U.getAndAddLong(this, THREADIDS, 1L);
1675 }
1676 private static int getAndAddPoolIds(int x) {
1677 return U.getAndAddInt(POOLIDS_BASE, POOLIDS, x);
1678 }
1679 private int getAndSetParallelism(int v) {
1680 return U.getAndSetInt(this, PARALLELISM, v);
1681 }
1682 private int getParallelismOpaque() {
1683 return U.getIntOpaque(this, PARALLELISM);
1684 }
1685 private CountDownLatch cmpExTerminationSignal(CountDownLatch x) {
1686 return (CountDownLatch)
1687 U.compareAndExchangeReference(this, TERMINATION, null, x);
1688 }
1689
1690 // runState operations
1691
1692 private long getAndBitwiseOrRunState(long v) { // for status bits
1693 return U.getAndBitwiseOrLong(this, RUNSTATE, v);
1694 }
1695 private boolean casRunState(long c, long v) {
1696 return U.compareAndSetLong(this, RUNSTATE, c, v);
1697 }
1698 private void unlockRunState() { // increment lock bit
1699 U.getAndAddLong(this, RUNSTATE, RS_LOCK);
1700 }
1701 private long lockRunState() { // lock and return current state
1702 long s, u; // locked when RS_LOCK set
1703 if (((s = runState) & RS_LOCK) == 0L && casRunState(s, u = s + RS_LOCK))
1704 return u;
1705 else
1706 return spinLockRunState();
1707 }
1708 private long spinLockRunState() { // spin/sleep
1709 for (int waits = 0;;) {
1710 long s, u;
1711 if (((s = runState) & RS_LOCK) == 0L) {
1712 if (casRunState(s, u = s + RS_LOCK))
1713 return u;
1714 waits = 0;
1715 } else if (waits < SPIN_WAITS) {
1716 ++waits;
1717 Thread.onSpinWait();
1718 } else {
1719 if (waits < MIN_SLEEP)
1720 waits = MIN_SLEEP;
1721 LockSupport.parkNanos(this, (long)waits);
1722 if (waits < MAX_SLEEP)
1723 waits <<= 1;
1724 }
1725 }
1726 }
1727
1728 static boolean poolIsStopping(ForkJoinPool p) { // Used by ForkJoinTask
1729 return p != null && (p.runState & STOP) != 0L;
1730 }
1731
1732 // Creating, registering, and deregistering workers
1733
1734 /**
1735 * Tries to construct and start one worker. Assumes that total
1736 * count has already been incremented as a reservation. Invokes
1737 * deregisterWorker on any failure.
1738 *
1739 * @return true if successful
1740 */
1741 private boolean createWorker() {
1742 ForkJoinWorkerThreadFactory fac = factory;
1743 SharedThreadContainer ctr = container;
1744 Throwable ex = null;
1745 ForkJoinWorkerThread wt = null;
1746 try {
1747 if ((runState & STOP) == 0L && // avoid construction if terminating
1748 fac != null && (wt = fac.newThread(this)) != null) {
1749 if (ctr != null)
1750 ctr.start(wt);
1751 else
1752 wt.start();
1753 return true;
1754 }
1755 } catch (Throwable rex) {
1756 ex = rex;
1757 }
1758 deregisterWorker(wt, ex);
1759 return false;
1760 }
1761
1762 /**
1763 * Provides a name for ForkJoinWorkerThread constructor.
1764 */
1765 final String nextWorkerThreadName() {
1766 String prefix = workerNamePrefix;
1767 long tid = incrementThreadIds() + 1L;
1768 if (prefix == null) // commonPool has no prefix
1769 prefix = "ForkJoinPool.commonPool-worker-";
1770 return prefix.concat(Long.toString(tid));
1771 }
1772
1773 /**
1774 * Finishes initializing and records internal queue.
1775 *
1776 * @param w caller's WorkQueue
1777 */
1778 final void registerWorker(WorkQueue w) {
1779 if (w != null) {
1780 w.array = new ForkJoinTask<?>[INITIAL_QUEUE_CAPACITY];
1781 ThreadLocalRandom.localInit();
1782 int seed = w.stackPred = ThreadLocalRandom.getProbe();
1783 int phaseSeq = seed & ~((IDLE << 1) - 1); // initial phase tag
1784 int id = ((seed << 1) | 1) & SMASK; // base of linear-probe-like scan
1785 long stop = lockRunState() & STOP;
1786 try {
1787 WorkQueue[] qs; int n;
1788 if (stop == 0L && (qs = queues) != null && (n = qs.length) > 0) {
1789 for (int k = n, m = n - 1; ; id += 2) {
1790 if (qs[id &= m] == null)
1791 break;
1792 if ((k -= 2) <= 0) {
1793 id |= n;
1794 break;
1795 }
1796 }
1797 w.phase = id | phaseSeq; // now publishable
1798 if (id < n)
1799 qs[id] = w;
1800 else { // expand
1801 int an = n << 1, am = an - 1;
1802 WorkQueue[] as = new WorkQueue[an];
1803 as[id & am] = w;
1804 for (int j = 1; j < n; j += 2)
1805 as[j] = qs[j];
1806 for (int j = 0; j < n; j += 2) {
1807 WorkQueue q; // shared queues may move
1808 if ((q = qs[j]) != null)
1809 as[q.phase & EXTERNAL_ID_MASK & am] = q;
1810 }
1811 U.storeFence(); // fill before publish
1812 queues = as;
1813 }
1814 }
1815 } finally {
1816 unlockRunState();
1817 }
1818 }
1819 }
1820
1821 /**
1822 * Final callback from terminating worker, as well as upon failure
1823 * to construct or start a worker. Removes record of worker from
1824 * array, and adjusts counts. If pool is shutting down, tries to
1825 * complete termination.
1826 *
1827 * @param wt the worker thread, or null if construction failed
1828 * @param ex the exception causing failure, or null if none
1829 */
1830 final void deregisterWorker(ForkJoinWorkerThread wt, Throwable ex) {
1831 WorkQueue w = null; // null if not created
1832 int phase = 0; // 0 if not registered
1833 if (wt != null && (w = wt.workQueue) != null &&
1834 (phase = w.phase) != 0 && (phase & IDLE) != 0)
1835 releaseWaiters(); // ensure released
1836 if (w == null || w.source != DROPPED) {
1837 long c = ctl; // decrement counts
1838 do {} while (c != (c = compareAndExchangeCtl(
1839 c, ((RC_MASK & (c - RC_UNIT)) |
1840 (TC_MASK & (c - TC_UNIT)) |
1841 (LMASK & c)))));
1842 }
1843 if (phase != 0 && w != null) { // remove index unless terminating
1844 long ns = w.nsteals & 0xffffffffL;
1845 if ((runState & STOP) == 0L) {
1846 WorkQueue[] qs; int n, i;
1847 if ((lockRunState() & STOP) == 0L &&
1848 (qs = queues) != null && (n = qs.length) > 0 &&
1849 qs[i = phase & SMASK & (n - 1)] == w) {
1850 qs[i] = null;
1851 stealCount += ns; // accumulate steals
1852 }
1853 unlockRunState();
1854 }
1855 }
1856 if ((tryTerminate(false, false) & STOP) == 0L &&
1857 phase != 0 && w != null && w.source != DROPPED) {
1858 w.cancelTasks(); // clean queue
1859 signalWork(null, 0); // possibly replace
1860 }
1861 if (ex != null)
1862 ForkJoinTask.rethrow(ex);
1863 }
1864
1865 /**
1866 * Releases an idle worker, or creates one if not enough exist,
1867 * giving up if array a is nonnull and task at a[k] already taken.
1868 */
1869 final void signalWork(ForkJoinTask<?>[] a, int k) {
1870 int pc = parallelism;
1871 for (long c = ctl;;) {
1872 WorkQueue[] qs = queues;
1873 long ac = (c + RC_UNIT) & RC_MASK, nc;
1874 int sp = (int)c, i = sp & SMASK;
1875 if ((short)(c >>> RC_SHIFT) >= pc)
1876 break;
1877 if (qs == null)
1878 break;
1879 if (qs.length <= i)
1880 break;
1881 WorkQueue w = qs[i], v = null;
1882 if (sp == 0) {
1883 if ((short)(c >>> TC_SHIFT) >= pc)
1884 break;
1885 nc = ((c + TC_UNIT) & TC_MASK) | ac;
1886 }
1887 else if ((v = w) == null)
1888 break;
1889 else
1890 nc = (v.stackPred & LMASK) | (c & TC_MASK) | ac;
1891 if (a != null && k < a.length && k >= 0 && a[k] == null)
1892 break;
1893 if (c == (c = ctl) && c == (c = compareAndExchangeCtl(c, nc))) {
1894 if (v == null)
1895 createWorker();
1896 else {
1897 v.phase = sp;
1898 if (v.parking != 0)
1899 U.unpark(v.owner);
1900 }
1901 break;
1902 }
1903 }
1904 }
1905
1906 /**
1907 * Releases all waiting workers. Called only during shutdown.
1908 */
1909 private void releaseWaiters() {
1910 for (long c = ctl;;) {
1911 WorkQueue[] qs; WorkQueue v; int sp, i;
1912 if ((sp = (int)c) == 0 || (qs = queues) == null ||
1913 qs.length <= (i = sp & SMASK) || (v = qs[i]) == null)
1914 break;
1915 if (c == (c = compareAndExchangeCtl(
1916 c, ((UMASK & (c + RC_UNIT)) | (c & TC_MASK) |
1917 (v.stackPred & LMASK))))) {
1918 v.phase = sp;
1919 if (v.parking != 0)
1920 U.unpark(v.owner);
1921 }
1922 }
1923 }
1924
1925 /**
1926 * Internal version of isQuiescent and related functionality.
1927 * @return positive if stopping, nonnegative if terminating or all
1928 * workers are inactive and submission queues are empty and
1929 * unlocked; if so, setting STOP if shutdown is enabled
1930 */
1931 private int quiescent() {
1932 for (;;) {
1933 long phaseSum = 0L;
1934 boolean swept = false;
1935 for (long e, prevRunState = 0L; ; prevRunState = e) {
1936 DelayScheduler ds;
1937 long c = ctl;
1938 if (((e = runState) & STOP) != 0L)
1939 return 1; // terminating
1940 else if ((c & RC_MASK) > 0L)
1941 return -1; // at least one active
1942 else if (!swept || e != prevRunState || (e & RS_LOCK) != 0) {
1943 long sum = c;
1944 WorkQueue[] qs = queues;
1945 int n = (qs == null) ? 0 : qs.length;
1946 for (int i = 0; i < n; ++i) { // scan queues
1947 WorkQueue q;
1948 if ((q = qs[i]) != null) {
1949 int p = q.phase, s = q.top, b = q.base;
1950 sum += (p & 0xffffffffL) | ((long)b << 32);
1951 if ((p & IDLE) == 0 || s - b > 0)
1952 return -1;
1953 }
1954 }
1955 swept = (phaseSum == (phaseSum = sum));
1956 }
1957 else if ((e & SHUTDOWN) == 0)
1958 return 0;
1959 else if ((ds = delayScheduler) != null && !ds.canShutDown())
1960 return 0;
1961 else if (compareAndSetCtl(c, c) && casRunState(e, e | STOP))
1962 return 1; // enable termination
1963 else
1964 break; // restart
1965 }
1966 }
1967 }
1968
1969 /**
1970 * Top-level runloop for workers, called by ForkJoinWorkerThread.run.
1971 * See above for explanation.
1972 *
1973 * @param w caller's WorkQueue (may be null on failed initialization)
1974 */
1975 final void runWorker(WorkQueue w) {
1976 if (w != null) {
1977 int phase = w.phase, r = w.stackPred; // seed from registerWorker
1978 int fifo = (int)config & FIFO;
1979 int nsteals = 0; // shadow w.nsteals
1980 boolean rescan = true;
1981 WorkQueue[] qs; int n;
1982 while ((rescan || (phase = deactivate(w, phase)) != 0) &&
1983 (runState & STOP) == 0L && (qs = queues) != null &&
1984 (n = qs.length) > 0) {
1985 rescan = false;
1986 int i = r, step = (r >>> 16) | 1;
1987 r ^= r << 13; r ^= r >>> 17; r ^= r << 5; // xorshift
1988 scan: for (int j = -n; j < n; ++j, i += step) { // 2 passes
1989 WorkQueue q; int qid;
1990 if ((q = qs[qid = i & (n - 1)]) != null) {
1991 for (;;) { // poll queue q
1992 ForkJoinTask<?>[] a; int cap, b, m, nb, nk;
1993 if ((a = q.array) == null || (cap = a.length) <= 0)
1994 break;
1995 long bp = slotOffset((m = cap - 1) & (b = q.base));
1996 long np = slotOffset(nk = m & (nb = b + 1));
1997 ForkJoinTask<?> t = (ForkJoinTask<?>)
1998 U.getReferenceAcquire(a, bp);
1999 if (q.base != b || U.getReference(a, bp) != t)
2000 continue; // inconsistent
2001 if (t == null) {
2002 if (rescan) { // end of run
2003 w.nsteals = nsteals;
2004 break scan;
2005 }
2006 if (U.getReference(a, np) != null) {
2007 rescan = true;
2008 break scan; // stalled; reorder scan
2009 }
2010 if (j >= 0 && q.top - b > 0) {
2011 rescan = true;
2012 break scan; // size check on 2nd pass
2013 }
2014 break; // probably empty
2015 }
2016 if ((phase & IDLE) != 0) // can't take yet
2017 phase = tryReactivate(w, phase);
2018 else if (U.compareAndSetReference(a, bp, t, null)) {
2019 q.base = nb;
2020 Object nt = U.getReferenceAcquire(a, np);
2021 if (!rescan) { // begin run
2022 rescan = true;
2023 w.source = qid;
2024 }
2025 ++nsteals;
2026 if (nt != null && // confirm a[nk]
2027 U.getReference(a, np) == nt)
2028 signalWork(a, nk); // propagate
2029 if (fifo != 0) // run t & its subtasks
2030 w.topLevelExecFifo(t);
2031 else
2032 w.topLevelExecLifo(t);
2033 }
2034 }
2035 }
2036 }
2037 }
2038 }
2039 }
2040
2041 /**
2042 * If active, tries to deactivate worker, keeping active on contention,
2043 * else awaits signal or termination.
2044 *
2045 * @param w the work queue
2046 * @param phase w's currently known phase
2047 * @return current phase or 0 on exit
2048 */
2049 private int deactivate(WorkQueue w, int phase) {
2050 if ((phase & IDLE) == 0 && w != null) {
2051 int idlePhase = phase | IDLE;
2052 long pc = ctl, e;
2053 long qc = ((phase + (IDLE << 1)) & LMASK) | ((pc - RC_UNIT) & UMASK);
2054 w.stackPred = (int)pc; // set ctl stack link
2055 w.phase = idlePhase; // try to enqueue
2056 if (!compareAndSetCtl(pc, qc))
2057 w.phase = phase; // back out on contention
2058 else {
2059 phase = idlePhase;
2060 if ((qc & RC_MASK) <= 0L && ((e = runState) & SHUTDOWN) != 0L &&
2061 (e & STOP) == 0L)
2062 quiescent(); // check quiescent termination
2063 }
2064 }
2065 else
2066 phase = awaitWork(w, phase);
2067 return phase;
2068 }
2069
2070 /**
2071 * Reactivates worker w if it is currently top of ctl stack
2072 *
2073 * @param w the work queue
2074 * @param phase w's currently known (idle) phase
2075 * @return currently known phase on exit
2076 */
2077 private int tryReactivate(WorkQueue w, int phase) {
2078 int activePhase = phase + IDLE; long c;
2079 if (w != null && (phase = w.phase) != activePhase &&
2080 (int)(c = ctl) == activePhase &&
2081 compareAndSetCtl(c, (w.stackPred & LMASK) | ((c + RC_UNIT) & UMASK)))
2082 phase = w.phase = activePhase;
2083 return phase;
2084 }
2085
2086 /**
2087 * Awaits signal or termination.
2088 *
2089 * @param w the work queue
2090 * @param phase w's currently known (idle) phase
2091 * @return current phase or 0 on exit
2092 */
2093 private int awaitWork(WorkQueue w, int phase) {
2094 int idle = 1, activePhase = phase + IDLE;
2095 if ((runState & STOP) == 0L && w != null &&
2096 (idle = w.phase - activePhase) != 0) {
2097 WorkQueue[] qs;
2098 int cfg = w.config;
2099 long waitTime = (w.source == INVALID_ID) ? 0L : keepAlive;
2100 int n = ((qs = queues) == null) ? 0 : qs.length;
2101 int spins = Math.max((n << 1) | (n - 1), SPIN_WAITS);
2102 long deadline = waitTime + System.currentTimeMillis();
2103 if ((cfg & CLEAR_TLS) != 0 && // instanceof check always true
2104 Thread.currentThread() instanceof ForkJoinWorkerThread f)
2105 f.resetThreadLocals(); // clear while accessing thread state
2106 LockSupport.setCurrentBlocker(this);
2107 for (;;) {
2108 Thread.interrupted(); // clear status
2109 int s = spins;
2110 while ((idle = w.phase - activePhase) != 0 && --s != 0)
2111 Thread.onSpinWait(); // spin before/between parks
2112 if (idle == 0)
2113 break;
2114 if ((runState & STOP) != 0L)
2115 break;
2116 boolean trimmable = false; // use timed wait if trimmable
2117 long d = 0L, c;
2118 if (((c = ctl) & RC_MASK) == 0L && (int)c == activePhase) {
2119 if (deadline - System.currentTimeMillis() <= TIMEOUT_SLOP) {
2120 if (tryTrim(w, c, activePhase))
2121 break;
2122 continue; // lost race to trim
2123 }
2124 d = deadline;
2125 trimmable = true;
2126 }
2127 w.parking = 1; // enable unpark and recheck
2128 if ((idle = w.phase - activePhase) != 0)
2129 U.park(trimmable, d);
2130 w.parking = 0; // close unpark window
2131 if (idle == 0 || (idle = w.phase - activePhase) == 0)
2132 break;
2133 }
2134 LockSupport.setCurrentBlocker(null);
2135 }
2136 return (idle == 0) ? activePhase : 0;
2137 }
2138
2139 /**
2140 * Tries to remove and deregister worker after timeout, and release
2141 * another to do the same unless new tasks are found.
2142 */
2143 private boolean tryTrim(WorkQueue w, long c, int activePhase) {
2144 if (w != null) {
2145 int vp, i; WorkQueue[] vs; WorkQueue v;
2146 long nc = ((w.stackPred & LMASK) |
2147 ((RC_MASK & c) | (TC_MASK & (c - TC_UNIT))));
2148 if (compareAndSetCtl(c, nc)) {
2149 w.source = DROPPED;
2150 w.phase = activePhase;
2151 if ((vp = (int)nc) != 0 && (vs = queues) != null &&
2152 vs.length > (i = vp & SMASK) && (v = vs[i]) != null &&
2153 compareAndSetCtl( // try to wake up next waiter
2154 nc, ((v.stackPred & LMASK) |
2155 ((UMASK & (nc + RC_UNIT)) | (nc & TC_MASK))))) {
2156 v.source = INVALID_ID; // enable cascaded timeouts
2157 v.phase = vp;
2158 U.unpark(v.owner);
2159 }
2160 return true;
2161 }
2162 }
2163 return false;
2164 }
2165
2166 /**
2167 * Scans for and returns a polled task, if available. Used only
2168 * for untracked polls. Begins scan at a random index to avoid
2169 * systematic unfairness.
2170 *
2171 * @param submissionsOnly if true, only scan submission queues
2172 */
2173 private ForkJoinTask<?> pollScan(boolean submissionsOnly) {
2174 if ((runState & STOP) == 0L) {
2175 WorkQueue[] qs; int n; WorkQueue q; ForkJoinTask<?> t;
2176 int r = ThreadLocalRandom.nextSecondarySeed();
2177 if (submissionsOnly) // even indices only
2178 r &= ~1;
2179 int step = (submissionsOnly) ? 2 : 1;
2180 if ((qs = queues) != null && (n = qs.length) > 0) {
2181 for (int i = n; i > 0; i -= step, r += step) {
2182 if ((q = qs[r & (n - 1)]) != null &&
2183 (t = q.poll()) != null)
2184 return t;
2185 }
2186 }
2187 }
2188 return null;
2189 }
2190
2191 /**
2192 * Tries to decrement counts (sometimes implicitly) and possibly
2193 * arrange for a compensating worker in preparation for
2194 * blocking. May fail due to interference, in which case -1 is
2195 * returned so caller may retry. A zero return value indicates
2196 * that the caller doesn't need to re-adjust counts when later
2197 * unblocked.
2198 *
2199 * @param c incoming ctl value
2200 * @return UNCOMPENSATE: block then adjust, 0: block, -1 : retry
2201 */
2202 private int tryCompensate(long c) {
2203 Predicate<? super ForkJoinPool> sat;
2204 long b = config;
2205 int pc = parallelism, // unpack fields
2206 minActive = (short)(b >>> RC_SHIFT),
2207 maxTotal = (short)(b >>> TC_SHIFT) + pc,
2208 active = (short)(c >>> RC_SHIFT),
2209 total = (short)(c >>> TC_SHIFT),
2210 sp = (int)c,
2211 stat = -1; // default retry return
2212 if (sp != 0 && active <= pc) { // activate idle worker
2213 WorkQueue[] qs; WorkQueue v; int i;
2214 if ((qs = queues) != null && qs.length > (i = sp & SMASK) &&
2215 (v = qs[i]) != null &&
2216 compareAndSetCtl(c, (c & UMASK) | (v.stackPred & LMASK))) {
2217 v.phase = sp;
2218 if (v.parking != 0)
2219 U.unpark(v.owner);
2220 stat = UNCOMPENSATE;
2221 }
2222 }
2223 else if (active > minActive && total >= pc) { // reduce active workers
2224 if (compareAndSetCtl(c, ((c - RC_UNIT) & RC_MASK) | (c & ~RC_MASK)))
2225 stat = UNCOMPENSATE;
2226 }
2227 else if (total < maxTotal && total < MAX_CAP) { // try to expand pool
2228 long nc = ((c + TC_UNIT) & TC_MASK) | (c & ~TC_MASK);
2229 if ((runState & STOP) != 0L) // terminating
2230 stat = 0;
2231 else if (compareAndSetCtl(c, nc))
2232 stat = createWorker() ? UNCOMPENSATE : 0;
2233 }
2234 else if (!compareAndSetCtl(c, c)) // validate
2235 ;
2236 else if ((sat = saturate) != null && sat.test(this))
2237 stat = 0;
2238 else
2239 throw new RejectedExecutionException(
2240 "Thread limit exceeded replacing blocked worker");
2241 return stat;
2242 }
2243
2244 /**
2245 * Readjusts RC count; called from ForkJoinTask after blocking.
2246 */
2247 final void uncompensate() {
2248 getAndAddCtl(RC_UNIT);
2249 }
2250
2251 /**
2252 * Helps if possible until the given task is done. Processes
2253 * compatible local tasks and scans other queues for task produced
2254 * by w's stealers; returning compensated blocking sentinel if
2255 * none are found.
2256 *
2257 * @param task the task
2258 * @param w caller's WorkQueue
2259 * @param internal true if w is owned by a ForkJoinWorkerThread
2260 * @return task status on exit, or UNCOMPENSATE for compensated blocking
2261 */
2262 final int helpJoin(ForkJoinTask<?> task, WorkQueue w, boolean internal) {
2263 if (w != null)
2264 w.tryRemoveAndExec(task, internal);
2265 int s = 0;
2266 if (task != null && (s = task.status) >= 0 && internal && w != null) {
2267 int wid = w.phase & SMASK, r = wid + 2, wsrc = w.source;
2268 long sctl = 0L; // track stability
2269 outer: for (boolean rescan = true;;) {
2270 if ((s = task.status) < 0)
2271 break;
2272 if (!rescan) {
2273 if ((runState & STOP) != 0L)
2274 break;
2275 if (sctl == (sctl = ctl) && (s = tryCompensate(sctl)) >= 0)
2276 break;
2277 }
2278 rescan = false;
2279 WorkQueue[] qs = queues;
2280 int n = (qs == null) ? 0 : qs.length;
2281 scan: for (int l = n >>> 1; l > 0; --l, r += 2) {
2282 int j; WorkQueue q;
2283 if ((q = qs[j = r & SMASK & (n - 1)]) != null) {
2284 for (;;) {
2285 ForkJoinTask<?> t; ForkJoinTask<?>[] a;
2286 boolean eligible = false;
2287 int sq = q.source, b, cap; long k;
2288 if ((a = q.array) == null || (cap = a.length) <= 0)
2289 break;
2290 t = (ForkJoinTask<?>)U.getReferenceAcquire(
2291 a, k = slotOffset((cap - 1) & (b = q.base)));
2292 if (t == task)
2293 eligible = true;
2294 else if (t != null) { // check steal chain
2295 for (int v = sq, d = cap;;) {
2296 WorkQueue p;
2297 if (v == wid) {
2298 eligible = true;
2299 break;
2300 }
2301 if ((v & 1) == 0 || // external or none
2302 --d < 0 || // bound depth
2303 (p = qs[v & (n - 1)]) == null)
2304 break;
2305 v = p.source;
2306 }
2307 }
2308 if ((s = task.status) < 0)
2309 break outer; // validate
2310 if (q.source == sq && q.base == b &&
2311 U.getReference(a, k) == t) {
2312 if (!eligible) { // revisit if nonempty
2313 if (!rescan && t == null && q.top - b > 0)
2314 rescan = true;
2315 break;
2316 }
2317 if (U.compareAndSetReference(a, k, t, null)) {
2318 q.base = b + 1;
2319 w.source = j; // volatile write
2320 t.doExec();
2321 w.source = wsrc;
2322 rescan = true; // restart at index r
2323 break scan;
2324 }
2325 }
2326 }
2327 }
2328 }
2329 }
2330 }
2331 return s;
2332 }
2333
2334 /**
2335 * Version of helpJoin for CountedCompleters.
2336 *
2337 * @param task root of computation (only called when a CountedCompleter)
2338 * @param w caller's WorkQueue
2339 * @param internal true if w is owned by a ForkJoinWorkerThread
2340 * @return task status on exit, or UNCOMPENSATE for compensated blocking
2341 */
2342 final int helpComplete(ForkJoinTask<?> task, WorkQueue w, boolean internal) {
2343 int s = 0;
2344 if (task != null && (s = task.status) >= 0 && w != null) {
2345 int r = w.phase + 1; // for indexing
2346 long sctl = 0L; // track stability
2347 outer: for (boolean rescan = true, locals = true;;) {
2348 if (locals && (s = w.helpComplete(task, internal, 0)) < 0)
2349 break;
2350 if ((s = task.status) < 0)
2351 break;
2352 if (!rescan) {
2353 if ((runState & STOP) != 0L)
2354 break;
2355 if (sctl == (sctl = ctl) &&
2356 (!internal || (s = tryCompensate(sctl)) >= 0))
2357 break;
2358 }
2359 rescan = locals = false;
2360 WorkQueue[] qs = queues;
2361 int n = (qs == null) ? 0 : qs.length;
2362 scan: for (int l = n; l > 0; --l, ++r) {
2363 int j; WorkQueue q;
2364 if ((q = qs[j = r & SMASK & (n - 1)]) != null) {
2365 for (;;) {
2366 ForkJoinTask<?> t; ForkJoinTask<?>[] a;
2367 int b, cap, nb; long k;
2368 boolean eligible = false;
2369 if ((a = q.array) == null || (cap = a.length) <= 0)
2370 break;
2371 t = (ForkJoinTask<?>)U.getReferenceAcquire(
2372 a, k = slotOffset((cap - 1) & (b = q.base)));
2373 if (t instanceof CountedCompleter) {
2374 CountedCompleter<?> f = (CountedCompleter<?>)t;
2375 for (int steps = cap; steps > 0; --steps) {
2376 if (f == task) {
2377 eligible = true;
2378 break;
2379 }
2380 if ((f = f.completer) == null)
2381 break;
2382 }
2383 }
2384 if ((s = task.status) < 0) // validate
2385 break outer;
2386 if (q.base == b) {
2387 if (eligible) {
2388 if (U.compareAndSetReference(
2389 a, k, t, null)) {
2390 q.updateBase(b + 1);
2391 t.doExec();
2392 locals = rescan = true;
2393 break scan;
2394 }
2395 }
2396 else if (U.getReference(a, k) == t) {
2397 if (!rescan && t == null && q.top - b > 0)
2398 rescan = true; // revisit
2399 break;
2400 }
2401 }
2402 }
2403 }
2404 }
2405 }
2406 }
2407 return s;
2408 }
2409
2410 /**
2411 * Runs tasks until all workers are inactive and no tasks are
2412 * found. Rather than blocking when tasks cannot be found, rescans
2413 * until all others cannot find tasks either.
2414 *
2415 * @param nanos max wait time (Long.MAX_VALUE if effectively untimed)
2416 * @param interruptible true if return on interrupt
2417 * @return positive if quiescent, negative if interrupted, else 0
2418 */
2419 private int helpQuiesce(WorkQueue w, long nanos, boolean interruptible) {
2420 int phase; // w.phase inactive bit set when temporarily quiescent
2421 if (w == null || ((phase = w.phase) & IDLE) != 0)
2422 return 0;
2423 int wsrc = w.source;
2424 long startTime = System.nanoTime();
2425 long maxSleep = Math.min(nanos >>> 8, MAX_SLEEP); // approx 1% nanos
2426 long prevSum = 0L;
2427 int activePhase = phase, inactivePhase = phase + IDLE;
2428 int r = phase + 1, waits = 0, returnStatus = 1;
2429 boolean locals = true;
2430 for (long e = runState;;) {
2431 if ((e & STOP) != 0L)
2432 break; // terminating
2433 if (interruptible && Thread.interrupted()) {
2434 returnStatus = -1;
2435 break;
2436 }
2437 if (locals) { // run local tasks before (re)polling
2438 locals = false;
2439 for (ForkJoinTask<?> u; (u = w.nextLocalTask()) != null;)
2440 u.doExec();
2441 }
2442 WorkQueue[] qs = queues;
2443 int n = (qs == null) ? 0 : qs.length;
2444 long phaseSum = 0L;
2445 boolean rescan = false, busy = false;
2446 scan: for (int l = n; l > 0; --l, ++r) {
2447 int j; WorkQueue q;
2448 if ((q = qs[j = r & SMASK & (n - 1)]) != null && q != w) {
2449 for (;;) {
2450 ForkJoinTask<?> t; ForkJoinTask<?>[] a;
2451 int b, cap; long k;
2452 if ((a = q.array) == null || (cap = a.length) <= 0)
2453 break;
2454 t = (ForkJoinTask<?>)U.getReferenceAcquire(
2455 a, k = slotOffset((cap - 1) & (b = q.base)));
2456 if (t != null && phase == inactivePhase) // reactivate
2457 w.phase = phase = activePhase;
2458 if (q.base == b && U.getReference(a, k) == t) {
2459 int nb = b + 1;
2460 if (t == null) {
2461 if (!rescan) {
2462 int qp = q.phase, mq = qp & (IDLE | 1);
2463 phaseSum += qp;
2464 if (mq == 0 || q.top - b > 0)
2465 rescan = true;
2466 else if (mq == 1)
2467 busy = true;
2468 }
2469 break;
2470 }
2471 if (U.compareAndSetReference(a, k, t, null)) {
2472 q.base = nb;
2473 w.source = j; // volatile write
2474 t.doExec();
2475 w.source = wsrc;
2476 rescan = locals = true;
2477 break scan;
2478 }
2479 }
2480 }
2481 }
2482 }
2483 if (e != (e = runState) || prevSum != (prevSum = phaseSum) ||
2484 rescan || (e & RS_LOCK) != 0L)
2485 ; // inconsistent
2486 else if (!busy)
2487 break;
2488 else if (phase == activePhase) {
2489 waits = 0; // recheck, then sleep
2490 w.phase = phase = inactivePhase;
2491 }
2492 else if (System.nanoTime() - startTime > nanos) {
2493 returnStatus = 0; // timed out
2494 break;
2495 }
2496 else if (waits == 0) // same as spinLockRunState except
2497 waits = MIN_SLEEP; // with rescan instead of onSpinWait
2498 else {
2499 LockSupport.parkNanos(this, (long)waits);
2500 if (waits < maxSleep)
2501 waits <<= 1;
2502 }
2503 }
2504 w.phase = activePhase;
2505 return returnStatus;
2506 }
2507
2508 /**
2509 * Helps quiesce from external caller until done, interrupted, or timeout
2510 *
2511 * @param nanos max wait time (Long.MAX_VALUE if effectively untimed)
2512 * @param interruptible true if return on interrupt
2513 * @return positive if quiescent, negative if interrupted, else 0
2514 */
2515 private int externalHelpQuiesce(long nanos, boolean interruptible) {
2516 if (quiescent() < 0) {
2517 long startTime = System.nanoTime();
2518 long maxSleep = Math.min(nanos >>> 8, MAX_SLEEP);
2519 for (int waits = 0;;) {
2520 ForkJoinTask<?> t;
2521 if (interruptible && Thread.interrupted())
2522 return -1;
2523 else if ((t = pollScan(false)) != null) {
2524 waits = 0;
2525 t.doExec();
2526 }
2527 else if (quiescent() >= 0)
2528 break;
2529 else if (System.nanoTime() - startTime > nanos)
2530 return 0;
2531 else if (waits == 0)
2532 waits = MIN_SLEEP;
2533 else {
2534 LockSupport.parkNanos(this, (long)waits);
2535 if (waits < maxSleep)
2536 waits <<= 1;
2537 }
2538 }
2539 }
2540 return 1;
2541 }
2542
2543 /**
2544 * Helps quiesce from either internal or external caller
2545 *
2546 * @param pool the pool to use, or null if any
2547 * @param nanos max wait time (Long.MAX_VALUE if effectively untimed)
2548 * @param interruptible true if return on interrupt
2549 * @return positive if quiescent, negative if interrupted, else 0
2550 */
2551 static final int helpQuiescePool(ForkJoinPool pool, long nanos,
2552 boolean interruptible) {
2553 Thread t; ForkJoinPool p; ForkJoinWorkerThread wt;
2554 if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread &&
2555 (p = (wt = (ForkJoinWorkerThread)t).pool) != null &&
2556 (p == pool || pool == null))
2557 return p.helpQuiesce(wt.workQueue, nanos, interruptible);
2558 else if ((p = pool) != null || (p = common) != null)
2559 return p.externalHelpQuiesce(nanos, interruptible);
2560 else
2561 return 0;
2562 }
2563
2564 /**
2565 * Gets and removes a local or stolen task for the given worker.
2566 *
2567 * @return a task, if available
2568 */
2569 final ForkJoinTask<?> nextTaskFor(WorkQueue w) {
2570 ForkJoinTask<?> t;
2571 if (w == null || (t = w.nextLocalTask()) == null)
2572 t = pollScan(false);
2573 return t;
2574 }
2575
2576 // External operations
2577
2578 /**
2579 * Finds and locks a WorkQueue for an external submitter, or
2580 * throws RejectedExecutionException if shutdown
2581 * @param rejectOnShutdown true if RejectedExecutionException
2582 * should be thrown when shutdown
2583 */
2584 final WorkQueue externalSubmissionQueue(boolean rejectOnShutdown) {
2585 int r;
2586 if ((r = ThreadLocalRandom.getProbe()) == 0) {
2587 ThreadLocalRandom.localInit(); // initialize caller's probe
2588 r = ThreadLocalRandom.getProbe();
2589 }
2590 for (;;) {
2591 WorkQueue q; WorkQueue[] qs; int n, id, i;
2592 if ((qs = queues) == null || (n = qs.length) <= 0)
2593 break;
2594 if ((q = qs[i = (id = r & EXTERNAL_ID_MASK) & (n - 1)]) == null) {
2595 WorkQueue newq = new WorkQueue(null, id, 0, false);
2596 lockRunState();
2597 if (qs[i] == null && queues == qs)
2598 q = qs[i] = newq; // else lost race to install
2599 unlockRunState();
2600 }
2601 if (q != null && q.tryLockPhase()) {
2602 if (rejectOnShutdown && (runState & SHUTDOWN) != 0L) {
2603 q.unlockPhase(); // check while q lock held
2604 break;
2605 }
2606 return q;
2607 }
2608 r = ThreadLocalRandom.advanceProbe(r); // move
2609 }
2610 throw new RejectedExecutionException();
2611 }
2612
2613 private <T> ForkJoinTask<T> poolSubmit(boolean signalIfEmpty, ForkJoinTask<T> task) {
2614 Thread t; ForkJoinWorkerThread wt; WorkQueue q; boolean internal;
2615 if (((t = JLA.currentCarrierThread()) instanceof ForkJoinWorkerThread) &&
2616 (wt = (ForkJoinWorkerThread)t).pool == this) {
2617 internal = true;
2618 q = wt.workQueue;
2619 }
2620 else { // find and lock queue
2621 internal = false;
2622 q = externalSubmissionQueue(true);
2623 }
2624 q.push(task, signalIfEmpty ? this : null, internal);
2625 return task;
2626 }
2627
2628 /**
2629 * Returns queue for an external thread, if one exists that has
2630 * possibly ever submitted to the given pool (nonzero probe), or
2631 * null if none.
2632 */
2633 static WorkQueue externalQueue(ForkJoinPool p) {
2634 WorkQueue[] qs; int n;
2635 int r = ThreadLocalRandom.getProbe();
2636 return (p != null && (qs = p.queues) != null &&
2637 (n = qs.length) > 0 && r != 0) ?
2638 qs[r & EXTERNAL_ID_MASK & (n - 1)] : null;
2639 }
2640
2641 /**
2642 * Returns external queue for common pool.
2643 */
2644 static WorkQueue commonQueue() {
2645 return externalQueue(common);
2646 }
2647
2648 /**
2649 * If the given executor is a ForkJoinPool, poll and execute
2650 * AsynchronousCompletionTasks from worker's queue until none are
2651 * available or blocker is released.
2652 */
2653 static void helpAsyncBlocker(Executor e, ManagedBlocker blocker) {
2654 WorkQueue w = null; Thread t; ForkJoinWorkerThread wt;
2655 if (((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) &&
2656 (wt = (ForkJoinWorkerThread)t).pool == e)
2657 w = wt.workQueue;
2658 else if (e instanceof ForkJoinPool)
2659 w = externalQueue((ForkJoinPool)e);
2660 if (w != null)
2661 w.helpAsyncBlocker(blocker);
2662 }
2663
2664 /**
2665 * Returns a cheap heuristic guide for task partitioning when
2666 * programmers, frameworks, tools, or languages have little or no
2667 * idea about task granularity. In essence, by offering this
2668 * method, we ask users only about tradeoffs in overhead vs
2669 * expected throughput and its variance, rather than how finely to
2670 * partition tasks.
2671 *
2672 * In a steady state strict (tree-structured) computation, each
2673 * thread makes available for stealing enough tasks for other
2674 * threads to remain active. Inductively, if all threads play by
2675 * the same rules, each thread should make available only a
2676 * constant number of tasks.
2677 *
2678 * The minimum useful constant is just 1. But using a value of 1
2679 * would require immediate replenishment upon each steal to
2680 * maintain enough tasks, which is infeasible. Further,
2681 * partitionings/granularities of offered tasks should minimize
2682 * steal rates, which in general means that threads nearer the top
2683 * of computation tree should generate more than those nearer the
2684 * bottom. In perfect steady state, each thread is at
2685 * approximately the same level of computation tree. However,
2686 * producing extra tasks amortizes the uncertainty of progress and
2687 * diffusion assumptions.
2688 *
2689 * So, users will want to use values larger (but not much larger)
2690 * than 1 to both smooth over transient shortages and hedge
2691 * against uneven progress; as traded off against the cost of
2692 * extra task overhead. We leave the user to pick a threshold
2693 * value to compare with the results of this call to guide
2694 * decisions, but recommend values such as 3.
2695 *
2696 * When all threads are active, it is on average OK to estimate
2697 * surplus strictly locally. In steady-state, if one thread is
2698 * maintaining say 2 surplus tasks, then so are others. So we can
2699 * just use estimated queue length. However, this strategy alone
2700 * leads to serious mis-estimates in some non-steady-state
2701 * conditions (ramp-up, ramp-down, other stalls). We can detect
2702 * many of these by further considering the number of "idle"
2703 * threads, that are known to have zero queued tasks, so
2704 * compensate by a factor of (#idle/#active) threads.
2705 */
2706 static int getSurplusQueuedTaskCount() {
2707 Thread t; ForkJoinWorkerThread wt; ForkJoinPool pool; WorkQueue q;
2708 if (((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) &&
2709 (pool = (wt = (ForkJoinWorkerThread)t).pool) != null &&
2710 (q = wt.workQueue) != null) {
2711 int n = q.top - q.base;
2712 int p = pool.parallelism;
2713 int a = (short)(pool.ctl >>> RC_SHIFT);
2714 return n - (a > (p >>>= 1) ? 0 :
2715 a > (p >>>= 1) ? 1 :
2716 a > (p >>>= 1) ? 2 :
2717 a > (p >>>= 1) ? 4 :
2718 8);
2719 }
2720 return 0;
2721 }
2722
2723 // Termination
2724
2725 /**
2726 * Possibly initiates and/or completes pool termination.
2727 *
2728 * @param now if true, unconditionally terminate, else only
2729 * if no work and no active workers
2730 * @param enable if true, terminate when next possible
2731 * @return runState on exit
2732 */
2733 private long tryTerminate(boolean now, boolean enable) {
2734 long e, isShutdown, ps;
2735 if (((e = runState) & TERMINATED) != 0L)
2736 now = false;
2737 else if ((e & STOP) != 0L)
2738 now = true;
2739 else if (now) {
2740 if (((ps = getAndBitwiseOrRunState(SHUTDOWN|STOP) & STOP)) == 0L) {
2741 if ((ps & RS_LOCK) != 0L) {
2742 spinLockRunState(); // ensure queues array stable after stop
2743 unlockRunState();
2744 }
2745 interruptAll();
2746 }
2747 }
2748 else if ((isShutdown = (e & SHUTDOWN)) != 0L || enable) {
2749 long quiet; DelayScheduler ds;
2750 if (isShutdown == 0L)
2751 getAndBitwiseOrRunState(SHUTDOWN);
2752 if ((quiet = quiescent()) > 0)
2753 now = true;
2754 else if (quiet == 0 && (ds = delayScheduler) != null)
2755 ds.signal();
2756 }
2757
2758 if (now) {
2759 DelayScheduler ds;
2760 releaseWaiters();
2761 if ((ds = delayScheduler) != null)
2762 ds.signal();
2763 for (;;) {
2764 if (((e = runState) & CLEANED) == 0L) {
2765 boolean clean = cleanQueues();
2766 if (((e = runState) & CLEANED) == 0L && clean)
2767 e = getAndBitwiseOrRunState(CLEANED) | CLEANED;
2768 }
2769 if ((e & TERMINATED) != 0L)
2770 break;
2771 if (ctl != 0L) // else loop if didn't finish cleaning
2772 break;
2773 if ((ds = delayScheduler) != null && ds.signal() >= 0)
2774 break;
2775 if ((e & CLEANED) != 0L) {
2776 e |= TERMINATED;
2777 if ((getAndBitwiseOrRunState(TERMINATED) & TERMINATED) == 0L) {
2778 CountDownLatch done; SharedThreadContainer ctr;
2779 if ((done = termination) != null)
2780 done.countDown();
2781 if ((ctr = container) != null)
2782 ctr.close();
2783 }
2784 break;
2785 }
2786 }
2787 }
2788 return e;
2789 }
2790
2791 /**
2792 * Scans queues in a psuedorandom order based on thread id,
2793 * cancelling tasks until empty, or returning early upon
2794 * interference or still-active external queues, in which case
2795 * other calls will finish cancellation.
2796 *
2797 * @return true if all queues empty
2798 */
2799 private boolean cleanQueues() {
2800 int r = (int)Thread.currentThread().threadId();
2801 r ^= r << 13; r ^= r >>> 17; r ^= r << 5; // xorshift
2802 int step = (r >>> 16) | 1; // randomize traversals
2803 WorkQueue[] qs = queues;
2804 int n = (qs == null) ? 0 : qs.length;
2805 for (int l = n; l > 0; --l, r += step) {
2806 WorkQueue q; ForkJoinTask<?>[] a; int cap;
2807 if ((q = qs[r & (n - 1)]) != null &&
2808 (a = q.array) != null && (cap = a.length) > 0) {
2809 for (;;) {
2810 ForkJoinTask<?> t; int b; long k;
2811 t = (ForkJoinTask<?>)U.getReferenceAcquire(
2812 a, k = slotOffset((cap - 1) & (b = q.base)));
2813 if (q.base == b && t != null &&
2814 U.compareAndSetReference(a, k, t, null)) {
2815 q.updateBase(b + 1);
2816 try {
2817 t.cancel(false);
2818 } catch (Throwable ignore) {
2819 }
2820 }
2821 else if ((q.phase & (IDLE|1)) == 0 || // externally locked
2822 q.top - q.base > 0)
2823 return false; // incomplete
2824 else
2825 break;
2826 }
2827 }
2828 }
2829 return true;
2830 }
2831
2832 /**
2833 * Interrupts all workers
2834 */
2835 private void interruptAll() {
2836 Thread current = Thread.currentThread();
2837 WorkQueue[] qs = queues;
2838 int n = (qs == null) ? 0 : qs.length;
2839 for (int i = 1; i < n; i += 2) {
2840 WorkQueue q; Thread o;
2841 if ((q = qs[i]) != null && (o = q.owner) != null && o != current) {
2842 try {
2843 o.interrupt();
2844 } catch (Throwable ignore) {
2845 }
2846 }
2847 }
2848 }
2849
2850 /**
2851 * Returns termination signal, constructing if necessary
2852 */
2853 private CountDownLatch terminationSignal() {
2854 CountDownLatch signal, s, u;
2855 if ((signal = termination) == null)
2856 signal = ((u = cmpExTerminationSignal(
2857 s = new CountDownLatch(1))) == null) ? s : u;
2858 return signal;
2859 }
2860
2861 // Exported methods
2862
2863 // Constructors
2864
2865 /**
2866 * Creates a {@code ForkJoinPool} with parallelism equal to {@link
2867 * java.lang.Runtime#availableProcessors}, using defaults for all
2868 * other parameters (see {@link #ForkJoinPool(int,
2869 * ForkJoinWorkerThreadFactory, UncaughtExceptionHandler, boolean,
2870 * int, int, int, Predicate, long, TimeUnit)}).
2871 */
2872 public ForkJoinPool() {
2873 this(Math.min(MAX_CAP, Runtime.getRuntime().availableProcessors()),
2874 defaultForkJoinWorkerThreadFactory, null, false,
2875 0, MAX_CAP, 1, null, DEFAULT_KEEPALIVE, TimeUnit.MILLISECONDS);
2876 }
2877
2878 /**
2879 * Creates a {@code ForkJoinPool} with the indicated parallelism
2880 * level, using defaults for all other parameters (see {@link
2881 * #ForkJoinPool(int, ForkJoinWorkerThreadFactory,
2882 * UncaughtExceptionHandler, boolean, int, int, int, Predicate,
2883 * long, TimeUnit)}).
2884 *
2885 * @param parallelism the parallelism level
2886 * @throws IllegalArgumentException if parallelism less than or
2887 * equal to zero, or greater than implementation limit
2888 */
2889 public ForkJoinPool(int parallelism) {
2890 this(parallelism, defaultForkJoinWorkerThreadFactory, null, false,
2891 0, MAX_CAP, 1, null, DEFAULT_KEEPALIVE, TimeUnit.MILLISECONDS);
2892 }
2893
2894 /**
2895 * Creates a {@code ForkJoinPool} with the given parameters (using
2896 * defaults for others -- see {@link #ForkJoinPool(int,
2897 * ForkJoinWorkerThreadFactory, UncaughtExceptionHandler, boolean,
2898 * int, int, int, Predicate, long, TimeUnit)}).
2899 *
2900 * @param parallelism the parallelism level. For default value,
2901 * use {@link java.lang.Runtime#availableProcessors}.
2902 * @param factory the factory for creating new threads. For default value,
2903 * use {@link #defaultForkJoinWorkerThreadFactory}.
2904 * @param handler the handler for internal worker threads that
2905 * terminate due to unrecoverable errors encountered while executing
2906 * tasks. For default value, use {@code null}.
2907 * @param asyncMode if true,
2908 * establishes local first-in-first-out scheduling mode for forked
2909 * tasks that are never joined. This mode may be more appropriate
2910 * than default locally stack-based mode in applications in which
2911 * worker threads only process event-style asynchronous tasks.
2912 * For default value, use {@code false}.
2913 * @throws IllegalArgumentException if parallelism less than or
2914 * equal to zero, or greater than implementation limit
2915 * @throws NullPointerException if the factory is null
2916 */
2917 public ForkJoinPool(int parallelism,
2918 ForkJoinWorkerThreadFactory factory,
2919 UncaughtExceptionHandler handler,
2920 boolean asyncMode) {
2921 this(parallelism, factory, handler, asyncMode,
2922 0, MAX_CAP, 1, null, DEFAULT_KEEPALIVE, TimeUnit.MILLISECONDS);
2923 }
2924
2925 /**
2926 * Creates a {@code ForkJoinPool} with the given parameters.
2927 *
2928 * @param parallelism the parallelism level. For default value,
2929 * use {@link java.lang.Runtime#availableProcessors}.
2930 *
2931 * @param factory the factory for creating new threads. For
2932 * default value, use {@link #defaultForkJoinWorkerThreadFactory}.
2933 *
2934 * @param handler the handler for internal worker threads that
2935 * terminate due to unrecoverable errors encountered while
2936 * executing tasks. For default value, use {@code null}.
2937 *
2938 * @param asyncMode if true, establishes local first-in-first-out
2939 * scheduling mode for forked tasks that are never joined. This
2940 * mode may be more appropriate than default locally stack-based
2941 * mode in applications in which worker threads only process
2942 * event-style asynchronous tasks. For default value, use {@code
2943 * false}.
2944 *
2945 * @param corePoolSize ignored: used in previous releases of this
2946 * class but no longer applicable. Using {@code 0} maintains
2947 * compatibility across releases.
2948 *
2949 * @param maximumPoolSize the maximum number of threads allowed.
2950 * When the maximum is reached, attempts to replace blocked
2951 * threads fail. (However, because creation and termination of
2952 * different threads may overlap, and may be managed by the given
2953 * thread factory, this value may be transiently exceeded.) To
2954 * arrange the same value as is used by default for the common
2955 * pool, use {@code 256} plus the {@code parallelism} level. (By
2956 * default, the common pool allows a maximum of 256 spare
2957 * threads.) Using a value (for example {@code
2958 * Integer.MAX_VALUE}) larger than the implementation's total
2959 * thread limit has the same effect as using this limit (which is
2960 * the default).
2961 *
2962 * @param minimumRunnable the minimum allowed number of core
2963 * threads not blocked by a join or {@link ManagedBlocker}. To
2964 * ensure progress, when too few unblocked threads exist and
2965 * unexecuted tasks may exist, new threads are constructed, up to
2966 * the given maximumPoolSize. For the default value, use {@code
2967 * 1}, that ensures liveness. A larger value might improve
2968 * throughput in the presence of blocked activities, but might
2969 * not, due to increased overhead. A value of zero may be
2970 * acceptable when submitted tasks cannot have dependencies
2971 * requiring additional threads.
2972 *
2973 * @param saturate if non-null, a predicate invoked upon attempts
2974 * to create more than the maximum total allowed threads. By
2975 * default, when a thread is about to block on a join or {@link
2976 * ManagedBlocker}, but cannot be replaced because the
2977 * maximumPoolSize would be exceeded, a {@link
2978 * RejectedExecutionException} is thrown. But if this predicate
2979 * returns {@code true}, then no exception is thrown, so the pool
2980 * continues to operate with fewer than the target number of
2981 * runnable threads, which might not ensure progress.
2982 *
2983 * @param keepAliveTime the elapsed time since last use before
2984 * a thread is terminated (and then later replaced if needed).
2985 * For the default value, use {@code 60, TimeUnit.SECONDS}.
2986 *
2987 * @param unit the time unit for the {@code keepAliveTime} argument
2988 *
2989 * @throws IllegalArgumentException if parallelism is less than or
2990 * equal to zero, or is greater than implementation limit,
2991 * or if maximumPoolSize is less than parallelism,
2992 * of if the keepAliveTime is less than or equal to zero.
2993 * @throws NullPointerException if the factory is null
2994 * @since 9
2995 */
2996 public ForkJoinPool(int parallelism,
2997 ForkJoinWorkerThreadFactory factory,
2998 UncaughtExceptionHandler handler,
2999 boolean asyncMode,
3000 int corePoolSize,
3001 int maximumPoolSize,
3002 int minimumRunnable,
3003 Predicate<? super ForkJoinPool> saturate,
3004 long keepAliveTime,
3005 TimeUnit unit) {
3006 int p = parallelism;
3007 if (p <= 0 || p > MAX_CAP || p > maximumPoolSize || keepAliveTime <= 0L)
3008 throw new IllegalArgumentException();
3009 if (factory == null || unit == null)
3010 throw new NullPointerException();
3011 int size = Math.max(MIN_QUEUES_SIZE,
3012 1 << (33 - Integer.numberOfLeadingZeros(p - 1)));
3013 this.parallelism = p;
3014 this.factory = factory;
3015 this.ueh = handler;
3016 this.saturate = saturate;
3017 this.keepAlive = Math.max(unit.toMillis(keepAliveTime), TIMEOUT_SLOP);
3018 int maxSpares = Math.clamp(maximumPoolSize - p, 0, MAX_CAP);
3019 int minAvail = Math.clamp(minimumRunnable, 0, MAX_CAP);
3020 this.config = (((asyncMode ? FIFO : 0) & LMASK) |
3021 (((long)maxSpares) << TC_SHIFT) |
3022 (((long)minAvail) << RC_SHIFT));
3023 this.queues = new WorkQueue[size];
3024 String pid = Integer.toString(getAndAddPoolIds(1) + 1);
3025 String name = "ForkJoinPool-" + pid;
3026 this.poolName = name;
3027 this.workerNamePrefix = name + "-worker-";
3028 this.container = SharedThreadContainer.create(name);
3029 }
3030
3031 /**
3032 * Constructor for common pool using parameters possibly
3033 * overridden by system properties
3034 */
3035 private ForkJoinPool(byte forCommonPoolOnly) {
3036 String name = "ForkJoinPool.commonPool";
3037 ForkJoinWorkerThreadFactory fac = defaultForkJoinWorkerThreadFactory;
3038 UncaughtExceptionHandler handler = null;
3039 int maxSpares = DEFAULT_COMMON_MAX_SPARES;
3040 int pc = 0, preset = 0; // nonzero if size set as property
3041 try { // ignore exceptions in accessing/parsing properties
3042 String pp = System.getProperty
3043 ("java.util.concurrent.ForkJoinPool.common.parallelism");
3044 if (pp != null) {
3045 pc = Math.max(0, Integer.parseInt(pp));
3046 preset = PRESET_SIZE;
3047 }
3048 String ms = System.getProperty
3049 ("java.util.concurrent.ForkJoinPool.common.maximumSpares");
3050 if (ms != null)
3051 maxSpares = Math.clamp(Integer.parseInt(ms), 0, MAX_CAP);
3052 String sf = System.getProperty
3053 ("java.util.concurrent.ForkJoinPool.common.threadFactory");
3054 String sh = System.getProperty
3055 ("java.util.concurrent.ForkJoinPool.common.exceptionHandler");
3056 if (sf != null || sh != null) {
3057 ClassLoader ldr = ClassLoader.getSystemClassLoader();
3058 if (sf != null)
3059 fac = (ForkJoinWorkerThreadFactory)
3060 ldr.loadClass(sf).getConstructor().newInstance();
3061 if (sh != null)
3062 handler = (UncaughtExceptionHandler)
3063 ldr.loadClass(sh).getConstructor().newInstance();
3064 }
3065 } catch (Exception ignore) {
3066 }
3067 if (preset == 0)
3068 pc = Math.max(1, Runtime.getRuntime().availableProcessors() - 1);
3069 int p = Math.min(pc, MAX_CAP);
3070 int size = Math.max(MIN_QUEUES_SIZE,
3071 (p == 0) ? 1 :
3072 1 << (33 - Integer.numberOfLeadingZeros(p-1)));
3073 this.parallelism = p;
3074 this.config = ((preset & LMASK) | (((long)maxSpares) << TC_SHIFT) |
3075 (1L << RC_SHIFT));
3076 this.factory = fac;
3077 this.ueh = handler;
3078 this.keepAlive = DEFAULT_KEEPALIVE;
3079 this.saturate = null;
3080 this.workerNamePrefix = null;
3081 this.poolName = name;
3082 this.queues = new WorkQueue[size];
3083 this.container = SharedThreadContainer.create(name);
3084 }
3085
3086 /**
3087 * Returns the common pool instance. This pool is statically
3088 * constructed; its run state is unaffected by attempts to {@link
3089 * #shutdown} or {@link #shutdownNow}. However this pool and any
3090 * ongoing processing are automatically terminated upon program
3091 * {@link System#exit}. Any program that relies on asynchronous
3092 * task processing to complete before program termination should
3093 * invoke {@code commonPool().}{@link #awaitQuiescence awaitQuiescence},
3094 * before exit.
3095 *
3096 * @return the common pool instance
3097 * @since 1.8
3098 */
3099 public static ForkJoinPool commonPool() {
3100 // assert common != null : "static init error";
3101 return common;
3102 }
3103
3104 /**
3105 * Package-private access to commonPool overriding zero parallelism
3106 */
3107 static ForkJoinPool asyncCommonPool() {
3108 ForkJoinPool cp; int p;
3109 if ((p = (cp = common).parallelism) == 0)
3110 U.compareAndSetInt(cp, PARALLELISM, 0, 2);
3111 return cp;
3112 }
3113
3114 // Execution methods
3115
3116 /**
3117 * Performs the given task, returning its result upon completion.
3118 * If the computation encounters an unchecked Exception or Error,
3119 * it is rethrown as the outcome of this invocation. Rethrown
3120 * exceptions behave in the same way as regular exceptions, but,
3121 * when possible, contain stack traces (as displayed for example
3122 * using {@code ex.printStackTrace()}) of both the current thread
3123 * as well as the thread actually encountering the exception;
3124 * minimally only the latter.
3125 *
3126 * @param task the task
3127 * @param <T> the type of the task's result
3128 * @return the task's result
3129 * @throws NullPointerException if the task is null
3130 * @throws RejectedExecutionException if the task cannot be
3131 * scheduled for execution
3132 */
3133 public <T> T invoke(ForkJoinTask<T> task) {
3134 poolSubmit(true, Objects.requireNonNull(task));
3135 try {
3136 return task.join();
3137 } catch (RuntimeException | Error unchecked) {
3138 throw unchecked;
3139 } catch (Exception checked) {
3140 throw new RuntimeException(checked);
3141 }
3142 }
3143
3144 /**
3145 * Arranges for (asynchronous) execution of the given task.
3146 *
3147 * @param task the task
3148 * @throws NullPointerException if the task is null
3149 * @throws RejectedExecutionException if the task cannot be
3150 * scheduled for execution
3151 */
3152 public void execute(ForkJoinTask<?> task) {
3153 poolSubmit(true, Objects.requireNonNull(task));
3154 }
3155
3156 // AbstractExecutorService methods
3157
3158 /**
3159 * @throws NullPointerException if the task is null
3160 * @throws RejectedExecutionException if the task cannot be
3161 * scheduled for execution
3162 */
3163 @Override
3164 @SuppressWarnings("unchecked")
3165 public void execute(Runnable task) {
3166 poolSubmit(true, (Objects.requireNonNull(task) instanceof ForkJoinTask<?>)
3167 ? (ForkJoinTask<Void>) task // avoid re-wrap
3168 : new ForkJoinTask.RunnableExecuteAction(task));
3169 }
3170
3171 /**
3172 * Submits a ForkJoinTask for execution.
3173 *
3174 * @implSpec
3175 * This method is equivalent to {@link #externalSubmit(ForkJoinTask)}
3176 * when called from a thread that is not in this pool.
3177 *
3178 * @param task the task to submit
3179 * @param <T> the type of the task's result
3180 * @return the task
3181 * @throws NullPointerException if the task is null
3182 * @throws RejectedExecutionException if the task cannot be
3183 * scheduled for execution
3184 */
3185 public <T> ForkJoinTask<T> submit(ForkJoinTask<T> task) {
3186 return poolSubmit(true, Objects.requireNonNull(task));
3187 }
3188
3189 /**
3190 * @throws NullPointerException if the task is null
3191 * @throws RejectedExecutionException if the task cannot be
3192 * scheduled for execution
3193 */
3194 @Override
3195 public <T> ForkJoinTask<T> submit(Callable<T> task) {
3196 Objects.requireNonNull(task);
3197 return poolSubmit(
3198 true,
3199 (Thread.currentThread() instanceof ForkJoinWorkerThread) ?
3200 new ForkJoinTask.AdaptedCallable<T>(task) :
3201 new ForkJoinTask.AdaptedInterruptibleCallable<T>(task));
3202 }
3203
3204 /**
3205 * @throws NullPointerException if the task is null
3206 * @throws RejectedExecutionException if the task cannot be
3207 * scheduled for execution
3208 */
3209 @Override
3210 public <T> ForkJoinTask<T> submit(Runnable task, T result) {
3211 Objects.requireNonNull(task);
3212 return poolSubmit(
3213 true,
3214 (Thread.currentThread() instanceof ForkJoinWorkerThread) ?
3215 new ForkJoinTask.AdaptedRunnable<T>(task, result) :
3216 new ForkJoinTask.AdaptedInterruptibleRunnable<T>(task, result));
3217 }
3218
3219 /**
3220 * @throws NullPointerException if the task is null
3221 * @throws RejectedExecutionException if the task cannot be
3222 * scheduled for execution
3223 */
3224 @Override
3225 @SuppressWarnings("unchecked")
3226 public ForkJoinTask<?> submit(Runnable task) {
3227 Objects.requireNonNull(task);
3228 return poolSubmit(
3229 true,
3230 (task instanceof ForkJoinTask<?>) ?
3231 (ForkJoinTask<Void>) task : // avoid re-wrap
3232 ((Thread.currentThread() instanceof ForkJoinWorkerThread) ?
3233 new ForkJoinTask.AdaptedRunnable<Void>(task, null) :
3234 new ForkJoinTask.AdaptedInterruptibleRunnable<Void>(task, null)));
3235 }
3236
3237 /**
3238 * Submits the given task as if submitted from a non-{@code ForkJoinTask}
3239 * client. The task is added to a scheduling queue for submissions to the
3240 * pool even when called from a thread in the pool.
3241 *
3242 * @implSpec
3243 * This method is equivalent to {@link #submit(ForkJoinTask)} when called
3244 * from a thread that is not in this pool.
3245 *
3246 * @return the task
3247 * @param task the task to submit
3248 * @param <T> the type of the task's result
3249 * @throws NullPointerException if the task is null
3250 * @throws RejectedExecutionException if the task cannot be
3251 * scheduled for execution
3252 * @since 20
3253 */
3254 public <T> ForkJoinTask<T> externalSubmit(ForkJoinTask<T> task) {
3255 Objects.requireNonNull(task);
3256 externalSubmissionQueue(true).push(task, this, false);
3257 return task;
3258 }
3259
3260 /**
3261 * Submits the given task without guaranteeing that it will
3262 * eventually execute in the absence of available active threads.
3263 * In some contexts, this method may reduce contention and
3264 * overhead by relying on context-specific knowledge that existing
3265 * threads (possibly including the calling thread if operating in
3266 * this pool) will eventually be available to execute the task.
3267 *
3268 * @param task the task
3269 * @param <T> the type of the task's result
3270 * @return the task
3271 * @throws NullPointerException if the task is null
3272 * @throws RejectedExecutionException if the task cannot be
3273 * scheduled for execution
3274 * @since 19
3275 */
3276 public <T> ForkJoinTask<T> lazySubmit(ForkJoinTask<T> task) {
3277 return poolSubmit(false, Objects.requireNonNull(task));
3278 }
3279
3280 /**
3281 * Changes the target parallelism of this pool, controlling the
3282 * future creation, use, and termination of worker threads.
3283 * Applications include contexts in which the number of available
3284 * processors changes over time.
3285 *
3286 * @implNote This implementation restricts the maximum number of
3287 * running threads to 32767
3288 *
3289 * @param size the target parallelism level
3290 * @return the previous parallelism level.
3291 * @throws IllegalArgumentException if size is less than 1 or
3292 * greater than the maximum supported by this pool.
3293 * @throws UnsupportedOperationException this is the{@link
3294 * #commonPool()} and parallelism level was set by System
3295 * property {@systemProperty
3296 * java.util.concurrent.ForkJoinPool.common.parallelism}.
3297 * @since 19
3298 */
3299 public int setParallelism(int size) {
3300 if (size < 1 || size > MAX_CAP)
3301 throw new IllegalArgumentException();
3302 if ((config & PRESET_SIZE) != 0)
3303 throw new UnsupportedOperationException("Cannot override System property");
3304 return getAndSetParallelism(size);
3305 }
3306
3307 /**
3308 * Uninterrupible version of {@code invokeAll}. Executes the given
3309 * tasks, returning a list of Futures holding their status and
3310 * results when all complete, ignoring interrupts. {@link
3311 * Future#isDone} is {@code true} for each element of the returned
3312 * list. Note that a <em>completed</em> task could have
3313 * terminated either normally or by throwing an exception. The
3314 * results of this method are undefined if the given collection is
3315 * modified while this operation is in progress.
3316 *
3317 * @apiNote This method supports usages that previously relied on an
3318 * incompatible override of
3319 * {@link ExecutorService#invokeAll(java.util.Collection)}.
3320 *
3321 * @param tasks the collection of tasks
3322 * @param <T> the type of the values returned from the tasks
3323 * @return a list of Futures representing the tasks, in the same
3324 * sequential order as produced by the iterator for the
3325 * given task list, each of which has completed
3326 * @throws NullPointerException if tasks or any of its elements are {@code null}
3327 * @throws RejectedExecutionException if any task cannot be
3328 * scheduled for execution
3329 * @since 22
3330 */
3331 public <T> List<Future<T>> invokeAllUninterruptibly(Collection<? extends Callable<T>> tasks) {
3332 ArrayList<Future<T>> futures = new ArrayList<>(tasks.size());
3333 try {
3334 for (Callable<T> t : tasks) {
3335 ForkJoinTask<T> f = ForkJoinTask.adapt(t);
3336 futures.add(f);
3337 poolSubmit(true, f);
3338 }
3339 for (int i = futures.size() - 1; i >= 0; --i)
3340 ((ForkJoinTask<?>)futures.get(i)).quietlyJoin();
3341 return futures;
3342 } catch (Throwable t) {
3343 for (Future<T> e : futures)
3344 e.cancel(true);
3345 throw t;
3346 }
3347 }
3348
3349 /**
3350 * Common support for timed and untimed invokeAll
3351 */
3352 private <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks,
3353 long deadline)
3354 throws InterruptedException {
3355 ArrayList<Future<T>> futures = new ArrayList<>(tasks.size());
3356 try {
3357 for (Callable<T> t : tasks) {
3358 ForkJoinTask<T> f = ForkJoinTask.adaptInterruptible(t);
3359 futures.add(f);
3360 poolSubmit(true, f);
3361 }
3362 for (int i = futures.size() - 1; i >= 0; --i)
3363 ((ForkJoinTask<?>)futures.get(i))
3364 .quietlyJoinPoolInvokeAllTask(deadline);
3365 return futures;
3366 } catch (Throwable t) {
3367 for (Future<T> e : futures)
3368 e.cancel(true);
3369 throw t;
3370 }
3371 }
3372
3373 @Override
3374 public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
3375 throws InterruptedException {
3376 return invokeAll(tasks, 0L);
3377 }
3378 // for jdk version < 22, replace with
3379 // /**
3380 // * @throws NullPointerException {@inheritDoc}
3381 // * @throws RejectedExecutionException {@inheritDoc}
3382 // */
3383 // @Override
3384 // public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) {
3385 // return invokeAllUninterruptibly(tasks);
3386 // }
3387
3388 @Override
3389 public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks,
3390 long timeout, TimeUnit unit)
3391 throws InterruptedException {
3392 return invokeAll(tasks, (System.nanoTime() + unit.toNanos(timeout)) | 1L);
3393 }
3394
3395 @Override
3396 public <T> T invokeAny(Collection<? extends Callable<T>> tasks)
3397 throws InterruptedException, ExecutionException {
3398 try {
3399 return new ForkJoinTask.InvokeAnyRoot<T>()
3400 .invokeAny(tasks, this, false, 0L);
3401 } catch (TimeoutException cannotHappen) {
3402 assert false;
3403 return null;
3404 }
3405 }
3406
3407 @Override
3408 public <T> T invokeAny(Collection<? extends Callable<T>> tasks,
3409 long timeout, TimeUnit unit)
3410 throws InterruptedException, ExecutionException, TimeoutException {
3411 return new ForkJoinTask.InvokeAnyRoot<T>()
3412 .invokeAny(tasks, this, true, unit.toNanos(timeout));
3413 }
3414
3415 // Support for delayed tasks
3416
3417 /**
3418 * Returns STOP and SHUTDOWN status (zero if neither), masking or
3419 * truncating out other bits.
3420 */
3421 final int shutdownStatus(DelayScheduler ds) {
3422 return (int)(runState & (SHUTDOWN | STOP));
3423 }
3424
3425 /**
3426 * Tries to stop and possibly terminate if already enabled, return success.
3427 */
3428 final boolean tryStopIfShutdown(DelayScheduler ds) {
3429 return (tryTerminate(false, false) & STOP) != 0L;
3430 }
3431
3432 /**
3433 * Creates and starts DelayScheduler
3434 */
3435 private DelayScheduler startDelayScheduler() {
3436 DelayScheduler ds;
3437 if ((ds = delayScheduler) == null) {
3438 boolean start = false;
3439 String name = poolName + "-delayScheduler";
3440 if (workerNamePrefix == null)
3441 asyncCommonPool(); // override common parallelism zero
3442 long isShutdown = lockRunState() & SHUTDOWN;
3443 try {
3444 if (isShutdown == 0L && (ds = delayScheduler) == null) {
3445 ds = delayScheduler = new DelayScheduler(this, name);
3446 start = true;
3447 }
3448 } finally {
3449 unlockRunState();
3450 }
3451 if (start) { // start outside of lock
3452 SharedThreadContainer ctr;
3453 try {
3454 if ((ctr = container) != null)
3455 ctr.start(ds);
3456 else
3457 ds.start();
3458 } catch (RuntimeException | Error ex) { // back out
3459 lockRunState();
3460 ds = delayScheduler = null;
3461 unlockRunState();
3462 tryTerminate(false, false);
3463 if (ex instanceof Error)
3464 throw ex;
3465 }
3466 }
3467 }
3468 return ds;
3469 }
3470
3471 /**
3472 * Arranges execution of a ScheduledForkJoinTask whose delay has
3473 * elapsed
3474 */
3475 final void executeEnabledScheduledTask(ScheduledForkJoinTask<?> task) {
3476 externalSubmissionQueue(false).push(task, this, false);
3477 }
3478
3479 /**
3480 * Arranges delayed execution of a ScheduledForkJoinTask via the
3481 * DelayScheduler, creating and starting it if necessary.
3482 * @return the task
3483 */
3484 final <T> ScheduledForkJoinTask<T> scheduleDelayedTask(ScheduledForkJoinTask<T> task) {
3485 DelayScheduler ds;
3486 if (((ds = delayScheduler) == null &&
3487 (ds = startDelayScheduler()) == null) ||
3488 (runState & SHUTDOWN) != 0L)
3489 throw new RejectedExecutionException();
3490 ds.pend(task);
3491 return task;
3492 }
3493
3494 /**
3495 * Submits a one-shot task that becomes enabled for execution after the given
3496 * delay. At that point it will execute unless explicitly
3497 * cancelled, or fail to execute (eventually reporting
3498 * cancellation) when encountering resource exhaustion, or the
3499 * pool is {@link #shutdownNow}, or is {@link #shutdown} when
3500 * otherwise quiescent and {@link #cancelDelayedTasksOnShutdown}
3501 * is in effect.
3502 *
3503 * @param command the task to execute
3504 * @param delay the time from now to delay execution
3505 * @param unit the time unit of the delay parameter
3506 * @return a ForkJoinTask implementing the ScheduledFuture
3507 * interface, whose {@code get()} method will return
3508 * {@code null} upon normal completion.
3509 * @throws RejectedExecutionException if the pool is shutdown or
3510 * submission encounters resource exhaustion.
3511 * @throws NullPointerException if command or unit is null
3512 * @since 25
3513 */
3514 public ScheduledFuture<?> schedule(Runnable command,
3515 long delay, TimeUnit unit) {
3516 return scheduleDelayedTask(
3517 new ScheduledForkJoinTask<Void>(
3518 unit.toNanos(delay), 0L, false, // implicit null check of unit
3519 Objects.requireNonNull(command), null, this));
3520 }
3521
3522 /**
3523 * Submits a value-returning one-shot task that becomes enabled for execution
3524 * after the given delay. At that point it will execute unless
3525 * explicitly cancelled, or fail to execute (eventually reporting
3526 * cancellation) when encountering resource exhaustion, or the
3527 * pool is {@link #shutdownNow}, or is {@link #shutdown} when
3528 * otherwise quiescent and {@link #cancelDelayedTasksOnShutdown}
3529 * is in effect.
3530 *
3531 * @param callable the function to execute
3532 * @param delay the time from now to delay execution
3533 * @param unit the time unit of the delay parameter
3534 * @param <V> the type of the callable's result
3535 * @return a ForkJoinTask implementing the ScheduledFuture
3536 * interface, whose {@code get()} method will return the
3537 * value from the callable upon normal completion.
3538 * @throws RejectedExecutionException if the pool is shutdown or
3539 * submission encounters resource exhaustion.
3540 * @throws NullPointerException if command or unit is null
3541 * @since 25
3542 */
3543 public <V> ScheduledFuture<V> schedule(Callable<V> callable,
3544 long delay, TimeUnit unit) {
3545 return scheduleDelayedTask(
3546 new ScheduledForkJoinTask<V>(
3547 unit.toNanos(delay), 0L, false, null, // implicit null check of unit
3548 Objects.requireNonNull(callable), this));
3549 }
3550
3551 /**
3552 * Submits a periodic action that becomes enabled for execution first after the
3553 * given initial delay, and subsequently with the given period;
3554 * that is, executions will commence after
3555 * {@code initialDelay}, then {@code initialDelay + period}, then
3556 * {@code initialDelay + 2 * period}, and so on.
3557 *
3558 * <p>The sequence of task executions continues indefinitely until
3559 * one of the following exceptional completions occur:
3560 * <ul>
3561 * <li>The task is {@linkplain Future#cancel explicitly cancelled}
3562 * <li>Method {@link #shutdownNow} is called
3563 * <li>Method {@link #shutdown} is called and the pool is
3564 * otherwise quiescent, in which case existing executions continue
3565 * but subsequent executions do not.
3566 * <li>An execution or the task encounters resource exhaustion.
3567 * <li>An execution of the task throws an exception. In this case
3568 * calling {@link Future#get() get} on the returned future will throw
3569 * {@link ExecutionException}, holding the exception as its cause.
3570 * </ul>
3571 * Subsequent executions are suppressed. Subsequent calls to
3572 * {@link Future#isDone isDone()} on the returned future will
3573 * return {@code true}.
3574 *
3575 * <p>If any execution of this task takes longer than its period, then
3576 * subsequent executions may start late, but will not concurrently
3577 * execute.
3578 * @param command the task to execute
3579 * @param initialDelay the time to delay first execution
3580 * @param period the period between successive executions
3581 * @param unit the time unit of the initialDelay and period parameters
3582 * @return a ForkJoinTask implementing the ScheduledFuture
3583 * interface. The future's {@link Future#get() get()}
3584 * method will never return normally, and will throw an
3585 * exception upon task cancellation or abnormal
3586 * termination of a task execution.
3587 * @throws RejectedExecutionException if the pool is shutdown or
3588 * submission encounters resource exhaustion.
3589 * @throws NullPointerException if command or unit is null
3590 * @throws IllegalArgumentException if period less than or equal to zero
3591 * @since 25
3592 */
3593 public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,
3594 long initialDelay,
3595 long period, TimeUnit unit) {
3596 if (period <= 0L)
3597 throw new IllegalArgumentException();
3598 return scheduleDelayedTask(
3599 new ScheduledForkJoinTask<Void>(
3600 unit.toNanos(initialDelay), // implicit null check of unit
3601 unit.toNanos(period), false,
3602 Objects.requireNonNull(command), null, this));
3603 }
3604
3605 /**
3606 * Submits a periodic action that becomes enabled for execution first after the
3607 * given initial delay, and subsequently with the given delay
3608 * between the termination of one execution and the commencement of
3609 * the next.
3610 * <p>The sequence of task executions continues indefinitely until
3611 * one of the following exceptional completions occur:
3612 * <ul>
3613 * <li>The task is {@linkplain Future#cancel explicitly cancelled}
3614 * <li>Method {@link #shutdownNow} is called
3615 * <li>Method {@link #shutdown} is called and the pool is
3616 * otherwise quiescent, in which case existing executions continue
3617 * but subsequent executions do not.
3618 * <li>An execution or the task encounters resource exhaustion.
3619 * <li>An execution of the task throws an exception. In this case
3620 * calling {@link Future#get() get} on the returned future will throw
3621 * {@link ExecutionException}, holding the exception as its cause.
3622 * </ul>
3623 * Subsequent executions are suppressed. Subsequent calls to
3624 * {@link Future#isDone isDone()} on the returned future will
3625 * return {@code true}.
3626 * @param command the task to execute
3627 * @param initialDelay the time to delay first execution
3628 * @param delay the delay between the termination of one
3629 * execution and the commencement of the next
3630 * @param unit the time unit of the initialDelay and delay parameters
3631 * @return a ForkJoinTask implementing the ScheduledFuture
3632 * interface. The future's {@link Future#get() get()}
3633 * method will never return normally, and will throw an
3634 * exception upon task cancellation or abnormal
3635 * termination of a task execution.
3636 * @throws RejectedExecutionException if the pool is shutdown or
3637 * submission encounters resource exhaustion.
3638 * @throws NullPointerException if command or unit is null
3639 * @throws IllegalArgumentException if delay less than or equal to zero
3640 * @since 25
3641 */
3642 public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,
3643 long initialDelay,
3644 long delay, TimeUnit unit) {
3645 if (delay <= 0L)
3646 throw new IllegalArgumentException();
3647 return scheduleDelayedTask(
3648 new ScheduledForkJoinTask<Void>(
3649 unit.toNanos(initialDelay), // implicit null check of unit
3650 -unit.toNanos(delay), false, // negative for fixed delay
3651 Objects.requireNonNull(command), null, this));
3652 }
3653
3654 /**
3655 * Body of a task performed on timeout of another task
3656 */
3657 static final class TimeoutAction<V> implements Runnable {
3658 // set after construction, nulled after use
3659 ForkJoinTask.CallableWithTimeout<V> task;
3660 Consumer<? super ForkJoinTask<V>> action;
3661 TimeoutAction(Consumer<? super ForkJoinTask<V>> action) {
3662 this.action = action;
3663 }
3664 public void run() {
3665 ForkJoinTask.CallableWithTimeout<V> t = task;
3666 Consumer<? super ForkJoinTask<V>> a = action;
3667 task = null;
3668 action = null;
3669 if (t != null && t.status >= 0) {
3670 if (a == null)
3671 t.cancel(true);
3672 else {
3673 a.accept(t);
3674 t.interruptIfRunning(true);
3675 }
3676 }
3677 }
3678 }
3679
3680 /**
3681 * Submits a task executing the given function, cancelling the
3682 * task or performing a given timeoutAction if not completed
3683 * within the given timeout period. If the optional {@code
3684 * timeoutAction} is null, the task is cancelled (via {@code
3685 * cancel(true)}. Otherwise, the action is applied and the task
3686 * may be interrupted if running. Actions may include {@link
3687 * ForkJoinTask#complete} to set a replacement value or {@link
3688 * ForkJoinTask#completeExceptionally} to throw an appropriate
3689 * exception. Note that these can succeed only if the task has
3690 * not already completed when the timeoutAction executes.
3691 *
3692 * @param callable the function to execute
3693 * @param <V> the type of the callable's result
3694 * @param timeout the time to wait before cancelling if not completed
3695 * @param timeoutAction if nonnull, an action to perform on
3696 * timeout, otherwise the default action is to cancel using
3697 * {@code cancel(true)}.
3698 * @param unit the time unit of the timeout parameter
3699 * @return a Future that can be used to extract result or cancel
3700 * @throws RejectedExecutionException if the task cannot be
3701 * scheduled for execution
3702 * @throws NullPointerException if callable or unit is null
3703 * @since 25
3704 */
3705 public <V> ForkJoinTask<V> submitWithTimeout(Callable<V> callable,
3706 long timeout, TimeUnit unit,
3707 Consumer<? super ForkJoinTask<V>> timeoutAction) {
3708 ForkJoinTask.CallableWithTimeout<V> task; TimeoutAction<V> onTimeout;
3709 Objects.requireNonNull(callable);
3710 ScheduledForkJoinTask<Void> timeoutTask =
3711 new ScheduledForkJoinTask<Void>(
3712 unit.toNanos(timeout), 0L, true,
3713 onTimeout = new TimeoutAction<V>(timeoutAction), null, this);
3714 onTimeout.task = task =
3715 new ForkJoinTask.CallableWithTimeout<V>(callable, timeoutTask);
3716 scheduleDelayedTask(timeoutTask);
3717 return poolSubmit(true, task);
3718 }
3719
3720 /**
3721 * Arranges that scheduled tasks that are not executing and have
3722 * not already been enabled for execution will not be executed and
3723 * will be cancelled upon {@link #shutdown} (unless this pool is
3724 * the {@link #commonPool()} which never shuts down). This method
3725 * may be invoked either before {@link #shutdown} to take effect
3726 * upon the next call, or afterwards to cancel such tasks, which
3727 * may then allow termination. Note that subsequent executions of
3728 * periodic tasks are always disabled upon shutdown, so this
3729 * method applies meaningfully only to non-periodic tasks.
3730 * @since 25
3731 */
3732 public void cancelDelayedTasksOnShutdown() {
3733 DelayScheduler ds;
3734 if ((ds = delayScheduler) != null ||
3735 (ds = startDelayScheduler()) != null)
3736 ds.cancelDelayedTasksOnShutdown();
3737 }
3738
3739 /**
3740 * Returns the factory used for constructing new workers.
3741 *
3742 * @return the factory used for constructing new workers
3743 */
3744 public ForkJoinWorkerThreadFactory getFactory() {
3745 return factory;
3746 }
3747
3748 /**
3749 * Returns the handler for internal worker threads that terminate
3750 * due to unrecoverable errors encountered while executing tasks.
3751 *
3752 * @return the handler, or {@code null} if none
3753 */
3754 public UncaughtExceptionHandler getUncaughtExceptionHandler() {
3755 return ueh;
3756 }
3757
3758 /**
3759 * Returns the targeted parallelism level of this pool.
3760 *
3761 * @return the targeted parallelism level of this pool
3762 */
3763 public int getParallelism() {
3764 return Math.max(getParallelismOpaque(), 1);
3765 }
3766
3767 /**
3768 * Returns the targeted parallelism level of the common pool.
3769 *
3770 * @return the targeted parallelism level of the common pool
3771 * @since 1.8
3772 */
3773 public static int getCommonPoolParallelism() {
3774 return common.getParallelism();
3775 }
3776
3777 /**
3778 * Returns the number of worker threads that have started but not
3779 * yet terminated. The result returned by this method may differ
3780 * from {@link #getParallelism} when threads are created to
3781 * maintain parallelism when others are cooperatively blocked.
3782 *
3783 * @return the number of worker threads
3784 */
3785 public int getPoolSize() {
3786 return (short)(ctl >>> TC_SHIFT);
3787 }
3788
3789 /**
3790 * Returns {@code true} if this pool uses local first-in-first-out
3791 * scheduling mode for forked tasks that are never joined.
3792 *
3793 * @return {@code true} if this pool uses async mode
3794 */
3795 public boolean getAsyncMode() {
3796 return (config & FIFO) != 0;
3797 }
3798
3799 /**
3800 * Returns an estimate of the number of worker threads that are
3801 * not blocked waiting to join tasks or for other managed
3802 * synchronization. This method may overestimate the
3803 * number of running threads.
3804 *
3805 * @return the number of worker threads
3806 */
3807 public int getRunningThreadCount() {
3808 WorkQueue[] qs; WorkQueue q;
3809 int rc = 0;
3810 if ((runState & TERMINATED) == 0L && (qs = queues) != null) {
3811 for (int i = 1; i < qs.length; i += 2) {
3812 if ((q = qs[i]) != null && q.isApparentlyUnblocked())
3813 ++rc;
3814 }
3815 }
3816 return rc;
3817 }
3818
3819 /**
3820 * Returns an estimate of the number of threads that are currently
3821 * stealing or executing tasks. This method may overestimate the
3822 * number of active threads.
3823 *
3824 * @return the number of active threads
3825 */
3826 public int getActiveThreadCount() {
3827 return Math.max((short)(ctl >>> RC_SHIFT), 0);
3828 }
3829
3830 /**
3831 * Returns {@code true} if all worker threads are currently idle.
3832 * An idle worker is one that cannot obtain a task to execute
3833 * because none are available to steal from other threads, and
3834 * there are no pending submissions to the pool. This method is
3835 * conservative; it might not return {@code true} immediately upon
3836 * idleness of all threads, but will eventually become true if
3837 * threads remain inactive.
3838 *
3839 * @return {@code true} if all threads are currently idle
3840 */
3841 public boolean isQuiescent() {
3842 return quiescent() >= 0;
3843 }
3844
3845 /**
3846 * Returns an estimate of the total number of completed tasks that
3847 * were executed by a thread other than their submitter. The
3848 * reported value underestimates the actual total number of steals
3849 * when the pool is not quiescent. This value may be useful for
3850 * monitoring and tuning fork/join programs: in general, steal
3851 * counts should be high enough to keep threads busy, but low
3852 * enough to avoid overhead and contention across threads.
3853 *
3854 * @return the number of steals
3855 */
3856 public long getStealCount() {
3857 long count = stealCount;
3858 WorkQueue[] qs; WorkQueue q;
3859 if ((qs = queues) != null) {
3860 for (int i = 1; i < qs.length; i += 2) {
3861 if ((q = qs[i]) != null)
3862 count += (long)q.nsteals & 0xffffffffL;
3863 }
3864 }
3865 return count;
3866 }
3867
3868 /**
3869 * Returns an estimate of the total number of tasks currently held
3870 * in queues by worker threads (but not including tasks submitted
3871 * to the pool that have not begun executing). This value is only
3872 * an approximation, obtained by iterating across all threads in
3873 * the pool. This method may be useful for tuning task
3874 * granularities.The returned count does not include scheduled
3875 * tasks that are not yet ready to execute, which are reported
3876 * separately by method {@link getDelayedTaskCount}.
3877 *
3878 * @return the number of queued tasks
3879 * @see ForkJoinWorkerThread#getQueuedTaskCount()
3880 */
3881 public long getQueuedTaskCount() {
3882 WorkQueue[] qs; WorkQueue q;
3883 long count = 0;
3884 if ((runState & TERMINATED) == 0L && (qs = queues) != null) {
3885 for (int i = 1; i < qs.length; i += 2) {
3886 if ((q = qs[i]) != null)
3887 count += q.queueSize();
3888 }
3889 }
3890 return count;
3891 }
3892
3893 /**
3894 * Returns an estimate of the number of tasks submitted to this
3895 * pool that have not yet begun executing. This method may take
3896 * time proportional to the number of submissions.
3897 *
3898 * @return the number of queued submissions
3899 */
3900 public int getQueuedSubmissionCount() {
3901 WorkQueue[] qs; WorkQueue q;
3902 int count = 0;
3903 if ((runState & TERMINATED) == 0L && (qs = queues) != null) {
3904 for (int i = 0; i < qs.length; i += 2) {
3905 if ((q = qs[i]) != null)
3906 count += q.queueSize();
3907 }
3908 }
3909 return count;
3910 }
3911
3912 /**
3913 * Returns an estimate of the number of delayed (including
3914 * periodic) tasks scheduled in this pool that are not yet ready
3915 * to submit for execution. The returned value is inaccurate while
3916 * delayed tasks are being processed.
3917 *
3918 * @return an estimate of the number of delayed tasks
3919 * @since 25
3920 */
3921 public long getDelayedTaskCount() {
3922 DelayScheduler ds;
3923 return ((ds = delayScheduler) == null ? 0 : ds.lastStableSize());
3924 }
3925
3926 /**
3927 * Returns {@code true} if there are any tasks submitted to this
3928 * pool that have not yet begun executing.
3929 *
3930 * @return {@code true} if there are any queued submissions
3931 */
3932 public boolean hasQueuedSubmissions() {
3933 WorkQueue[] qs; WorkQueue q;
3934 if ((runState & STOP) == 0L && (qs = queues) != null) {
3935 for (int i = 0; i < qs.length; i += 2) {
3936 if ((q = qs[i]) != null && q.queueSize() > 0)
3937 return true;
3938 }
3939 }
3940 return false;
3941 }
3942
3943 /**
3944 * Removes and returns the next unexecuted submission if one is
3945 * available. This method may be useful in extensions to this
3946 * class that re-assign work in systems with multiple pools.
3947 *
3948 * @return the next submission, or {@code null} if none
3949 */
3950 protected ForkJoinTask<?> pollSubmission() {
3951 return pollScan(true);
3952 }
3953
3954 /**
3955 * Removes all available unexecuted submitted and forked tasks
3956 * from scheduling queues and adds them to the given collection,
3957 * without altering their execution status. These may include
3958 * artificially generated or wrapped tasks. This method is
3959 * designed to be invoked only when the pool is known to be
3960 * quiescent. Invocations at other times may not remove all
3961 * tasks. A failure encountered while attempting to add elements
3962 * to collection {@code c} may result in elements being in
3963 * neither, either or both collections when the associated
3964 * exception is thrown. The behavior of this operation is
3965 * undefined if the specified collection is modified while the
3966 * operation is in progress.
3967 *
3968 * @param c the collection to transfer elements into
3969 * @return the number of elements transferred
3970 */
3971 protected int drainTasksTo(Collection<? super ForkJoinTask<?>> c) {
3972 int count = 0;
3973 for (ForkJoinTask<?> t; (t = pollScan(false)) != null; ) {
3974 c.add(t);
3975 ++count;
3976 }
3977 return count;
3978 }
3979
3980 /**
3981 * Returns a string identifying this pool, as well as its state,
3982 * including indications of run state, parallelism level, and
3983 * worker and task counts.
3984 *
3985 * @return a string identifying this pool, as well as its state
3986 */
3987 public String toString() {
3988 // Use a single pass through queues to collect counts
3989 DelayScheduler ds;
3990 long e = runState;
3991 long st = stealCount;
3992 long qt = 0L, ss = 0L; int rc = 0;
3993 WorkQueue[] qs; WorkQueue q;
3994 if ((qs = queues) != null) {
3995 for (int i = 0; i < qs.length; ++i) {
3996 if ((q = qs[i]) != null) {
3997 int size = q.queueSize();
3998 if ((i & 1) == 0)
3999 ss += size;
4000 else {
4001 qt += size;
4002 st += (long)q.nsteals & 0xffffffffL;
4003 if (q.isApparentlyUnblocked())
4004 ++rc;
4005 }
4006 }
4007 }
4008 }
4009 String delayed = ((ds = delayScheduler) == null ? "" :
4010 ", delayed = " + ds.lastStableSize());
4011 int pc = parallelism;
4012 long c = ctl;
4013 int tc = (short)(c >>> TC_SHIFT);
4014 int ac = (short)(c >>> RC_SHIFT);
4015 if (ac < 0) // ignore transient negative
4016 ac = 0;
4017 String level = ((e & TERMINATED) != 0L ? "Terminated" :
4018 (e & STOP) != 0L ? "Terminating" :
4019 (e & SHUTDOWN) != 0L ? "Shutting down" :
4020 "Running");
4021 return super.toString() +
4022 "[" + level +
4023 ", parallelism = " + pc +
4024 ", size = " + tc +
4025 ", active = " + ac +
4026 ", running = " + rc +
4027 ", steals = " + st +
4028 ", tasks = " + qt +
4029 ", submissions = " + ss +
4030 delayed +
4031 "]";
4032 }
4033
4034 /**
4035 * Possibly initiates an orderly shutdown in which previously
4036 * submitted tasks are executed, but no new tasks will be
4037 * accepted. Invocation has no effect on execution state if this
4038 * is the {@link #commonPool()}, and no additional effect if
4039 * already shut down. Tasks that are in the process of being
4040 * submitted concurrently during the course of this method may or
4041 * may not be rejected.
4042 */
4043 public void shutdown() {
4044 if (workerNamePrefix != null) // not common pool
4045 tryTerminate(false, true);
4046 }
4047
4048 /**
4049 * Possibly attempts to cancel and/or stop all tasks, and reject
4050 * all subsequently submitted tasks. Invocation has no effect on
4051 * execution state if this is the {@link #commonPool()}, and no
4052 * additional effect if already shut down. Otherwise, tasks that
4053 * are in the process of being submitted or executed concurrently
4054 * during the course of this method may or may not be
4055 * rejected. This method cancels both existing and unexecuted
4056 * tasks, in order to permit termination in the presence of task
4057 * dependencies. So the method always returns an empty list
4058 * (unlike the case for some other Executors).
4059 *
4060 * @return an empty list
4061 */
4062 public List<Runnable> shutdownNow() {
4063 if (workerNamePrefix != null) // not common pool
4064 tryTerminate(true, true);
4065 return Collections.emptyList();
4066 }
4067
4068 /**
4069 * Returns {@code true} if all tasks have completed following shut down.
4070 *
4071 * @return {@code true} if all tasks have completed following shut down
4072 */
4073 public boolean isTerminated() {
4074 return (tryTerminate(false, false) & TERMINATED) != 0;
4075 }
4076
4077 /**
4078 * Returns {@code true} if the process of termination has
4079 * commenced but not yet completed. This method may be useful for
4080 * debugging. A return of {@code true} reported a sufficient
4081 * period after shutdown may indicate that submitted tasks have
4082 * ignored or suppressed interruption, or are waiting for I/O,
4083 * causing this executor not to properly terminate. (See the
4084 * advisory notes for class {@link ForkJoinTask} stating that
4085 * tasks should not normally entail blocking operations. But if
4086 * they do, they must abort them on interrupt.)
4087 *
4088 * @return {@code true} if terminating but not yet terminated
4089 */
4090 public boolean isTerminating() {
4091 return (tryTerminate(false, false) & (STOP | TERMINATED)) == STOP;
4092 }
4093
4094 /**
4095 * Returns {@code true} if this pool has been shut down.
4096 *
4097 * @return {@code true} if this pool has been shut down
4098 */
4099 public boolean isShutdown() {
4100 return (runState & SHUTDOWN) != 0L;
4101 }
4102
4103 /**
4104 * Blocks until all tasks have completed execution after a
4105 * shutdown request, or the timeout occurs, or the current thread
4106 * is interrupted, whichever happens first. Because the {@link
4107 * #commonPool()} never terminates until program shutdown, when
4108 * applied to the common pool, this method is equivalent to {@link
4109 * #awaitQuiescence(long, TimeUnit)} but always returns {@code false}.
4110 *
4111 * @param timeout the maximum time to wait
4112 * @param unit the time unit of the timeout argument
4113 * @return {@code true} if this executor terminated and
4114 * {@code false} if the timeout elapsed before termination
4115 * @throws InterruptedException if interrupted while waiting
4116 */
4117 public boolean awaitTermination(long timeout, TimeUnit unit)
4118 throws InterruptedException {
4119 long nanos = unit.toNanos(timeout);
4120 CountDownLatch done;
4121 if (workerNamePrefix == null) { // is common pool
4122 if (helpQuiescePool(this, nanos, true) < 0)
4123 throw new InterruptedException();
4124 return false;
4125 }
4126 else if ((tryTerminate(false, false) & TERMINATED) != 0 ||
4127 (done = terminationSignal()) == null ||
4128 (runState & TERMINATED) != 0L)
4129 return true;
4130 else
4131 return done.await(nanos, TimeUnit.NANOSECONDS);
4132 }
4133
4134 /**
4135 * If called by a ForkJoinTask operating in this pool, equivalent
4136 * in effect to {@link ForkJoinTask#helpQuiesce}. Otherwise,
4137 * waits and/or attempts to assist performing tasks until this
4138 * pool {@link #isQuiescent} or the indicated timeout elapses.
4139 *
4140 * @param timeout the maximum time to wait
4141 * @param unit the time unit of the timeout argument
4142 * @return {@code true} if quiescent; {@code false} if the
4143 * timeout elapsed.
4144 */
4145 public boolean awaitQuiescence(long timeout, TimeUnit unit) {
4146 return (helpQuiescePool(this, unit.toNanos(timeout), false) > 0);
4147 }
4148
4149 /**
4150 * Unless this is the {@link #commonPool()}, initiates an orderly
4151 * shutdown in which previously submitted tasks are executed, but
4152 * no new tasks will be accepted, and waits until all tasks have
4153 * completed execution and the executor has terminated.
4154 *
4155 * <p> If already terminated, or this is the {@link
4156 * #commonPool()}, this method has no effect on execution, and
4157 * does not wait. Otherwise, if interrupted while waiting, this
4158 * method stops all executing tasks as if by invoking {@link
4159 * #shutdownNow()}. It then continues to wait until all actively
4160 * executing tasks have completed. Tasks that were awaiting
4161 * execution are not executed. The interrupted status will be
4162 * re-asserted before this method returns.
4163 *
4164 * @since 19
4165 */
4166 @Override
4167 public void close() {
4168 if (workerNamePrefix != null) {
4169 CountDownLatch done = null;
4170 boolean interrupted = false;
4171 while ((tryTerminate(interrupted, true) & TERMINATED) == 0) {
4172 if (done == null)
4173 done = terminationSignal();
4174 else {
4175 try {
4176 done.await();
4177 break;
4178 } catch (InterruptedException ex) {
4179 interrupted = true;
4180 }
4181 }
4182 }
4183 if (interrupted)
4184 Thread.currentThread().interrupt();
4185 }
4186 }
4187
4188 /**
4189 * Interface for extending managed parallelism for tasks running
4190 * in {@link ForkJoinPool}s.
4191 *
4192 * <p>A {@code ManagedBlocker} provides two methods. Method
4193 * {@link #isReleasable} must return {@code true} if blocking is
4194 * not necessary. Method {@link #block} blocks the current thread
4195 * if necessary (perhaps internally invoking {@code isReleasable}
4196 * before actually blocking). These actions are performed by any
4197 * thread invoking {@link
4198 * ForkJoinPool#managedBlock(ManagedBlocker)}. The unusual
4199 * methods in this API accommodate synchronizers that may, but
4200 * don't usually, block for long periods. Similarly, they allow
4201 * more efficient internal handling of cases in which additional
4202 * workers may be, but usually are not, needed to ensure
4203 * sufficient parallelism. Toward this end, implementations of
4204 * method {@code isReleasable} must be amenable to repeated
4205 * invocation. Neither method is invoked after a prior invocation
4206 * of {@code isReleasable} or {@code block} returns {@code true}.
4207 *
4208 * <p>For example, here is a ManagedBlocker based on a
4209 * ReentrantLock:
4210 * <pre> {@code
4211 * class ManagedLocker implements ManagedBlocker {
4212 * final ReentrantLock lock;
4213 * boolean hasLock = false;
4214 * ManagedLocker(ReentrantLock lock) { this.lock = lock; }
4215 * public boolean block() {
4216 * if (!hasLock)
4217 * lock.lock();
4218 * return true;
4219 * }
4220 * public boolean isReleasable() {
4221 * return hasLock || (hasLock = lock.tryLock());
4222 * }
4223 * }}</pre>
4224 *
4225 * <p>Here is a class that possibly blocks waiting for an
4226 * item on a given queue:
4227 * <pre> {@code
4228 * class QueueTaker<E> implements ManagedBlocker {
4229 * final BlockingQueue<E> queue;
4230 * volatile E item = null;
4231 * QueueTaker(BlockingQueue<E> q) { this.queue = q; }
4232 * public boolean block() throws InterruptedException {
4233 * if (item == null)
4234 * item = queue.take();
4235 * return true;
4236 * }
4237 * public boolean isReleasable() {
4238 * return item != null || (item = queue.poll()) != null;
4239 * }
4240 * public E getItem() { // call after pool.managedBlock completes
4241 * return item;
4242 * }
4243 * }}</pre>
4244 */
4245 public static interface ManagedBlocker {
4246 /**
4247 * Possibly blocks the current thread, for example waiting for
4248 * a lock or condition.
4249 *
4250 * @return {@code true} if no additional blocking is necessary
4251 * (i.e., if isReleasable would return true)
4252 * @throws InterruptedException if interrupted while waiting
4253 * (the method is not required to do so, but is allowed to)
4254 */
4255 boolean block() throws InterruptedException;
4256
4257 /**
4258 * Returns {@code true} if blocking is unnecessary.
4259 * @return {@code true} if blocking is unnecessary
4260 */
4261 boolean isReleasable();
4262 }
4263
4264 /**
4265 * Runs the given possibly blocking task. When {@linkplain
4266 * ForkJoinTask#inForkJoinPool() running in a ForkJoinPool}, this
4267 * method possibly arranges for a spare thread to be activated if
4268 * necessary to ensure sufficient parallelism while the current
4269 * thread is blocked in {@link ManagedBlocker#block blocker.block()}.
4270 *
4271 * <p>This method repeatedly calls {@code blocker.isReleasable()} and
4272 * {@code blocker.block()} until either method returns {@code true}.
4273 * Every call to {@code blocker.block()} is preceded by a call to
4274 * {@code blocker.isReleasable()} that returned {@code false}.
4275 *
4276 * <p>If not running in a ForkJoinPool, this method is
4277 * behaviorally equivalent to
4278 * <pre> {@code
4279 * while (!blocker.isReleasable())
4280 * if (blocker.block())
4281 * break;}</pre>
4282 *
4283 * If running in a ForkJoinPool, the pool may first be expanded to
4284 * ensure sufficient parallelism available during the call to
4285 * {@code blocker.block()}.
4286 *
4287 * @param blocker the blocker task
4288 * @throws InterruptedException if {@code blocker.block()} did so
4289 */
4290 public static void managedBlock(ManagedBlocker blocker)
4291 throws InterruptedException {
4292 Thread t; ForkJoinPool p;
4293 if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread &&
4294 (p = ((ForkJoinWorkerThread)t).pool) != null)
4295 p.compensatedBlock(blocker);
4296 else
4297 unmanagedBlock(blocker);
4298 }
4299
4300 /** ManagedBlock for ForkJoinWorkerThreads */
4301 private void compensatedBlock(ManagedBlocker blocker)
4302 throws InterruptedException {
4303 Objects.requireNonNull(blocker);
4304 for (;;) {
4305 int comp; boolean done;
4306 long c = ctl;
4307 if (blocker.isReleasable())
4308 break;
4309 if ((runState & STOP) != 0L)
4310 throw new InterruptedException();
4311 if ((comp = tryCompensate(c)) >= 0) {
4312 try {
4313 done = blocker.block();
4314 } finally {
4315 if (comp > 0)
4316 getAndAddCtl(RC_UNIT);
4317 }
4318 if (done)
4319 break;
4320 }
4321 }
4322 }
4323
4324 /**
4325 * Invokes tryCompensate to create or re-activate a spare thread to
4326 * compensate for a thread that performs a blocking operation. When the
4327 * blocking operation is done then endCompensatedBlock must be invoked
4328 * with the value returned by this method to re-adjust the parallelism.
4329 * @return value to use in endCompensatedBlock
4330 */
4331 final long beginCompensatedBlock() {
4332 int c;
4333 do {} while ((c = tryCompensate(ctl)) < 0);
4334 return (c == 0) ? 0L : RC_UNIT;
4335 }
4336
4337 /**
4338 * Re-adjusts parallelism after a blocking operation completes.
4339 * @param post value from beginCompensatedBlock
4340 */
4341 void endCompensatedBlock(long post) {
4342 if (post > 0L) {
4343 getAndAddCtl(post);
4344 }
4345 }
4346
4347 /** ManagedBlock for external threads */
4348 private static void unmanagedBlock(ManagedBlocker blocker)
4349 throws InterruptedException {
4350 Objects.requireNonNull(blocker);
4351 do {} while (!blocker.isReleasable() && !blocker.block());
4352 }
4353
4354 @Override
4355 protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
4356 Objects.requireNonNull(runnable);
4357 return (Thread.currentThread() instanceof ForkJoinWorkerThread) ?
4358 new ForkJoinTask.AdaptedRunnable<T>(runnable, value) :
4359 new ForkJoinTask.AdaptedInterruptibleRunnable<T>(runnable, value);
4360 }
4361
4362 @Override
4363 protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
4364 Objects.requireNonNull(callable);
4365 return (Thread.currentThread() instanceof ForkJoinWorkerThread) ?
4366 new ForkJoinTask.AdaptedCallable<T>(callable) :
4367 new ForkJoinTask.AdaptedInterruptibleCallable<T>(callable);
4368 }
4369
4370 static {
4371 U = Unsafe.getUnsafe();
4372 Class<ForkJoinPool> klass = ForkJoinPool.class;
4373 try {
4374 Field poolIdsField = klass.getDeclaredField("poolIds");
4375 POOLIDS_BASE = U.staticFieldBase(poolIdsField);
4376 POOLIDS = U.staticFieldOffset(poolIdsField);
4377 } catch (NoSuchFieldException e) {
4378 throw new ExceptionInInitializerError(e);
4379 }
4380 CTL = U.objectFieldOffset(klass, "ctl");
4381 RUNSTATE = U.objectFieldOffset(klass, "runState");
4382 PARALLELISM = U.objectFieldOffset(klass, "parallelism");
4383 THREADIDS = U.objectFieldOffset(klass, "threadIds");
4384 TERMINATION = U.objectFieldOffset(klass, "termination");
4385 Class<ForkJoinTask[]> aklass = ForkJoinTask[].class;
4386 ABASE = U.arrayBaseOffset(aklass);
4387 int scale = U.arrayIndexScale(aklass);
4388 ASHIFT = 31 - Integer.numberOfLeadingZeros(scale);
4389 if ((scale & (scale - 1)) != 0)
4390 throw new Error("array index scale not a power of two");
4391
4392 Class<?> dep = LockSupport.class; // ensure loaded
4393 // allow access to non-public methods
4394 JLA = SharedSecrets.getJavaLangAccess();
4395 SharedSecrets.setJavaUtilConcurrentFJPAccess(
4396 new JavaUtilConcurrentFJPAccess() {
4397 @Override
4398 public long beginCompensatedBlock(ForkJoinPool pool) {
4399 return pool.beginCompensatedBlock();
4400 }
4401 public void endCompensatedBlock(ForkJoinPool pool, long post) {
4402 pool.endCompensatedBlock(post);
4403 }
4404 });
4405 defaultForkJoinWorkerThreadFactory =
4406 new DefaultForkJoinWorkerThreadFactory();
4407 common = new ForkJoinPool((byte)0);
4408 }
4409 }