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 deactivate, 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, along
944 * with status and bookkeeping fields written (mostly) by owners,
945 * that otherwise interfere with reading array and base
946 * fields. There are other variables commonly contributing to
947 * false-sharing-related performance issues (including fields of
948 * class Thread), but we can't do much about this except try to
949 * 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 // fields otherwise causing more unnecessary false-sharing cache misses
1182 @jdk.internal.vm.annotation.Contended("w")
1183 int top; // index of next slot for push
1184 @jdk.internal.vm.annotation.Contended("w")
1185 volatile int phase; // versioned active status
1186 @jdk.internal.vm.annotation.Contended("w")
1187 int stackPred; // pool stack (ctl) predecessor link
1188 @jdk.internal.vm.annotation.Contended("w")
1189 volatile int parking; // nonzero if parked in awaitWork
1190 @jdk.internal.vm.annotation.Contended("w")
1191 volatile int source; // source queue id (or DROPPED)
1192 @jdk.internal.vm.annotation.Contended("w")
1193 int nsteals; // number of steals from other queues
1194
1195 // Support for atomic operations
1196 private static final Unsafe U;
1197 private static final long PHASE;
1198 private static final long BASE;
1199 private static final long TOP;
1200 private static final long ARRAY;
1201
1202 final void updateBase(int v) {
1203 U.putIntVolatile(this, BASE, v);
1204 }
1205 final void updateTop(int v) {
1206 U.putIntOpaque(this, TOP, v);
1207 }
1208 final void updateArray(ForkJoinTask<?>[] a) {
1209 U.getAndSetReference(this, ARRAY, a);
1210 }
1211 final void unlockPhase() {
1212 U.getAndAddInt(this, PHASE, IDLE);
1213 }
1214 final boolean tryLockPhase() { // seqlock acquire
1215 int p;
1216 return (((p = phase) & IDLE) != 0 &&
1217 U.compareAndSetInt(this, PHASE, p, p + IDLE));
1218 }
1219
1220 /**
1221 * Constructor. For internal queues, most fields are initialized
1222 * upon thread start in pool.registerWorker.
1223 */
1224 WorkQueue(ForkJoinWorkerThread owner, int id, int cfg,
1225 boolean clearThreadLocals) {
1226 this.config = (clearThreadLocals) ? cfg | CLEAR_TLS : cfg;
1227 if ((this.owner = owner) == null) {
1228 array = new ForkJoinTask<?>[INITIAL_QUEUE_CAPACITY];
1229 phase = id | IDLE;
1230 }
1231 }
1232
1233 /**
1234 * Returns an exportable index (used by ForkJoinWorkerThread).
1235 */
1236 final int getPoolIndex() {
1237 return (phase & 0xffff) >>> 1; // ignore odd/even tag bit
1238 }
1239
1240 /**
1241 * Returns the approximate number of tasks in the queue.
1242 */
1243 final int queueSize() {
1244 int unused = phase; // for ordering effect
1245 return Math.max(top - base, 0); // ignore transient negative
1246 }
1247
1248 /**
1249 * Pushes a task. Called only by owner or if already locked
1250 *
1251 * @param task the task; no-op if null
1252 * @param pool the pool to signal if was previously empty, else null
1253 * @param internal if caller owns this queue
1254 * @throws RejectedExecutionException if array could not be resized
1255 */
1256 final void push(ForkJoinTask<?> task, ForkJoinPool pool, boolean internal) {
1257 int s = top, b = base, m, cap, room; ForkJoinTask<?>[] a, na;
1258 if ((a = array) != null && (cap = a.length) > 0) { // else disabled
1259 int k = (m = cap - 1) & s;
1260 if ((room = m - (s - b)) >= 0) {
1261 top = s + 1;
1262 long pos = slotOffset(k);
1263 if (!internal)
1264 U.putReference(a, pos, task); // inside lock
1265 else
1266 U.getAndSetReference(a, pos, task); // fully fenced
1267 if (room == 0 && (na = growArray(a, cap, s)) != null)
1268 k = ((a = na).length - 1) & s; // resize
1269 }
1270 if (!internal)
1271 unlockPhase();
1272 if (room < 0)
1273 throw new RejectedExecutionException("Queue capacity exceeded");
1274 if (pool != null &&
1275 (room == 0 ||
1276 U.getReferenceAcquire(a, slotOffset(m & (s - 1))) == null))
1277 pool.signalWork(a, k); // may have appeared empty
1278 }
1279 }
1280
1281 /**
1282 * Resizes the queue array unless out of memory.
1283 * @param a old array
1284 * @param cap old array capacity
1285 * @param s current top
1286 * @return new array, or null on failure
1287 */
1288 private ForkJoinTask<?>[] growArray(ForkJoinTask<?>[] a, int cap, int s) {
1289 int newCap = (cap >= 1 << 16) ? cap << 1 : cap << 2;
1290 ForkJoinTask<?>[] newArray = null;
1291 if (a != null && a.length == cap && cap > 0 && newCap > 0) {
1292 try {
1293 newArray = new ForkJoinTask<?>[newCap];
1294 } catch (OutOfMemoryError ex) {
1295 }
1296 if (newArray != null) { // else throw on next push
1297 int mask = cap - 1, newMask = newCap - 1;
1298 for (int k = s, j = cap; j > 0; --j, --k) {
1299 ForkJoinTask<?> u; // poll old, push to new
1300 if ((u = (ForkJoinTask<?>)U.getAndSetReference(
1301 a, slotOffset(k & mask), null)) == null)
1302 break; // lost to pollers
1303 newArray[k & newMask] = u;
1304 }
1305 updateArray(newArray); // fully fenced
1306 }
1307 }
1308 return newArray;
1309 }
1310
1311 /**
1312 * Takes next task, if one exists, in lifo order.
1313 */
1314 private ForkJoinTask<?> localPop() {
1315 ForkJoinTask<?> t = null;
1316 int s = top - 1, cap; long k; ForkJoinTask<?>[] a;
1317 if ((a = array) != null && (cap = a.length) > 0 &&
1318 U.getReference(a, k = slotOffset((cap - 1) & s)) != null &&
1319 (t = (ForkJoinTask<?>)U.getAndSetReference(a, k, null)) != null)
1320 updateTop(s);
1321 return t;
1322 }
1323
1324 /**
1325 * Takes next task, if one exists, in fifo order.
1326 */
1327 private ForkJoinTask<?> localPoll() {
1328 ForkJoinTask<?> t = null;
1329 int p = top, cap; ForkJoinTask<?>[] a;
1330 if ((a = array) != null && (cap = a.length) > 0) {
1331 for (int b = base; p - b > 0; ) {
1332 int nb = b + 1;
1333 long k = slotOffset((cap - 1) & b);
1334 if (U.getReference(a, k) == null) {
1335 if (nb == p)
1336 break; // else base is lagging
1337 while (b == (b = U.getIntAcquire(this, BASE)))
1338 Thread.onSpinWait(); // spin to reduce memory traffic
1339 }
1340 else if ((t = (ForkJoinTask<?>)
1341 U.getAndSetReference(a, k, null)) != null) {
1342 updateBase(nb);
1343 break;
1344 }
1345 else
1346 b = base;
1347 }
1348 }
1349 return t;
1350 }
1351
1352 /**
1353 * Takes next task, if one exists, using configured mode.
1354 */
1355 final ForkJoinTask<?> nextLocalTask() {
1356 return (config & FIFO) == 0 ? localPop() : localPoll();
1357 }
1358
1359 /**
1360 * Pops the given task only if it is at the current top.
1361 * @param task the task. Caller must ensure non-null.
1362 * @param internal if caller owns this queue
1363 */
1364 final boolean tryUnpush(ForkJoinTask<?> task, boolean internal) {
1365 boolean taken = false;
1366 ForkJoinTask<?>[] a = array;
1367 int p = top, s = p - 1, cap; long k;
1368 if (a != null && (cap = a.length) > 0 &&
1369 U.getReference(a, k = slotOffset((cap - 1) & s)) == task &&
1370 (internal || tryLockPhase())) {
1371 if (top == p && U.compareAndSetReference(a, k, task, null)) {
1372 taken = true;
1373 updateTop(s);
1374 }
1375 if (!internal)
1376 unlockPhase();
1377 }
1378 return taken;
1379 }
1380
1381 /**
1382 * Returns next task, if one exists, in order specified by mode.
1383 */
1384 final ForkJoinTask<?> peek() {
1385 ForkJoinTask<?>[] a = array;
1386 int b = base, cfg = config, p = top, cap;
1387 if (p != b && a != null && (cap = a.length) > 0) {
1388 if ((cfg & FIFO) == 0)
1389 return a[(cap - 1) & (p - 1)];
1390 else { // skip over in-progress removals
1391 ForkJoinTask<?> t;
1392 for ( ; p - b > 0; ++b) {
1393 if ((t = a[(cap - 1) & b]) != null)
1394 return t;
1395 }
1396 }
1397 }
1398 return null;
1399 }
1400
1401 /**
1402 * Polls for a task. Used only by non-owners.
1403 */
1404 final ForkJoinTask<?> poll() {
1405 for (int pb = -1, b; ; pb = b) { // track progress
1406 ForkJoinTask<?> t; int cap, nb; long k; ForkJoinTask<?>[] a;
1407 if ((a = array) == null || (cap = a.length) <= 0)
1408 break;
1409 t = (ForkJoinTask<?>)U.getReferenceAcquire(
1410 a, k = slotOffset((cap - 1) & (b = base)));
1411 Object u = U.getReference( // next slot
1412 a, slotOffset((cap - 1) & (nb = b + 1)));
1413 if (base != b) // inconsistent
1414 ;
1415 else if (t == null) {
1416 if (u == null && top - b <= 0)
1417 break; // empty
1418 if (pb == b)
1419 Thread.onSpinWait(); // stalled
1420 }
1421 else if (U.compareAndSetReference(a, k, t, null)) {
1422 updateBase(nb);
1423 return t;
1424 }
1425 }
1426 return null;
1427 }
1428
1429 // specialized execution methods
1430
1431 /**
1432 * Runs the given task, as well as remaining local tasks.
1433 */
1434 final void topLevelExec(ForkJoinTask<?> task, int cfg) {
1435 int fifo = cfg & FIFO, clr = cfg & CLEAR_TLS;
1436 while (task != null) {
1437 task.doExec();
1438 task = null;
1439 int p = top, cap; ForkJoinTask<?>[] a;
1440 if ((a = array) == null || (cap = a.length) <= 0)
1441 break;
1442 if (fifo == 0) { // specialized localPop
1443 int s = p - 1; long k;
1444 if (U.getReference(
1445 a, k = slotOffset((cap - 1) & s)) != null &&
1446 (task = (ForkJoinTask<?>)
1447 U.getAndSetReference(a, k, null)) != null) {
1448 top = s;
1449 }
1450 } else { // specialized localPoll
1451 for (int b = base; p - b > 0; ) {
1452 int nb = b + 1;
1453 if ((task = (ForkJoinTask<?>)U.getAndSetReference(
1454 a, slotOffset((cap - 1) & b), null)) != null) {
1455 base = nb;
1456 break;
1457 }
1458 if (nb == p)
1459 break;
1460 while (b == (b = U.getIntAcquire(this, BASE)))
1461 Thread.onSpinWait();
1462 }
1463 }
1464 }
1465 }
1466
1467 /**
1468 * Deep form of tryUnpush: Traverses from top and removes and
1469 * runs task if present.
1470 */
1471 final void tryRemoveAndExec(ForkJoinTask<?> task, boolean internal) {
1472 ForkJoinTask<?>[] a = array;
1473 int b = base, p = top, s = p - 1, d = p - b, cap;
1474 if (a != null && (cap = a.length) > 0) {
1475 for (int m = cap - 1, i = s; d > 0; --i, --d) {
1476 long k; boolean taken;
1477 ForkJoinTask<?> t = (ForkJoinTask<?>)U.getReference(
1478 a, k = slotOffset(i & m));
1479 if (t == null)
1480 break;
1481 if (t == task) {
1482 if (!internal && !tryLockPhase())
1483 break; // fail if locked
1484 if (taken =
1485 (top == p &&
1486 U.compareAndSetReference(a, k, task, null))) {
1487 if (i == s) // act as pop
1488 updateTop(s);
1489 else if (i == base) // act as poll
1490 updateBase(i + 1);
1491 else { // swap with top
1492 U.putReferenceVolatile(
1493 a, k, (ForkJoinTask<?>)
1494 U.getAndSetReference(
1495 a, slotOffset(s & m), null));
1496 updateTop(s);
1497 }
1498 }
1499 if (!internal)
1500 unlockPhase();
1501 if (taken)
1502 task.doExec();
1503 break;
1504 }
1505 }
1506 }
1507 }
1508
1509 /**
1510 * Tries to pop and run tasks within the target's computation
1511 * until done, not found, or limit exceeded.
1512 *
1513 * @param task root of computation
1514 * @param limit max runs, or zero for no limit
1515 * @return task status if known to be done
1516 */
1517 final int helpComplete(ForkJoinTask<?> task, boolean internal, int limit) {
1518 int status = 0;
1519 if (task != null) {
1520 outer: for (;;) {
1521 ForkJoinTask<?>[] a; boolean taken; Object o;
1522 int stat, p, s, cap;
1523 if ((stat = task.status) < 0) {
1524 status = stat;
1525 break;
1526 }
1527 if ((a = array) == null || (cap = a.length) <= 0)
1528 break;
1529 long k = slotOffset((cap - 1) & (s = (p = top) - 1));
1530 if (!((o = U.getReference(a, k)) instanceof CountedCompleter))
1531 break;
1532 CountedCompleter<?> t = (CountedCompleter<?>)o, f = t;
1533 for (int steps = cap;;) { // bound path
1534 if (f == task)
1535 break;
1536 if ((f = f.completer) == null || --steps == 0)
1537 break outer;
1538 }
1539 if (!internal && !tryLockPhase())
1540 break;
1541 if (taken =
1542 (top == p &&
1543 U.compareAndSetReference(a, k, t, null)))
1544 updateTop(s);
1545 if (!internal)
1546 unlockPhase();
1547 if (!taken)
1548 break;
1549 t.doExec();
1550 if (limit != 0 && --limit == 0)
1551 break;
1552 }
1553 }
1554 return status;
1555 }
1556
1557 /**
1558 * Tries to poll and run AsynchronousCompletionTasks until
1559 * none found or blocker is released
1560 *
1561 * @param blocker the blocker
1562 */
1563 final void helpAsyncBlocker(ManagedBlocker blocker) {
1564 for (;;) {
1565 ForkJoinTask<?> t; ForkJoinTask<?>[] a; int b, cap; long k;
1566 if ((a = array) == null || (cap = a.length) <= 0)
1567 break;
1568 t = (ForkJoinTask<?>)U.getReferenceAcquire(
1569 a, k = slotOffset((cap - 1) & (b = base)));
1570 if (t == null) {
1571 if (top - b <= 0)
1572 break;
1573 }
1574 else if (!(t instanceof CompletableFuture
1575 .AsynchronousCompletionTask))
1576 break;
1577 if (blocker != null && blocker.isReleasable())
1578 break;
1579 if (base == b && t != null &&
1580 U.compareAndSetReference(a, k, t, null)) {
1581 updateBase(b + 1);
1582 t.doExec();
1583 }
1584 }
1585 }
1586
1587 // misc
1588
1589 /**
1590 * Cancels all local tasks. Called only by owner.
1591 */
1592 final void cancelTasks() {
1593 for (ForkJoinTask<?> t; (t = localPop()) != null; ) {
1594 try {
1595 t.cancel(false);
1596 } catch (Throwable ignore) {
1597 }
1598 }
1599 }
1600
1601 /**
1602 * Returns true if internal and not known to be blocked.
1603 */
1604 final boolean isApparentlyUnblocked() {
1605 Thread wt; Thread.State s;
1606 return ((wt = owner) != null && (phase & IDLE) != 0 &&
1607 (s = wt.getState()) != Thread.State.BLOCKED &&
1608 s != Thread.State.WAITING &&
1609 s != Thread.State.TIMED_WAITING);
1610 }
1611
1612 static {
1613 U = Unsafe.getUnsafe();
1614 Class<WorkQueue> klass = WorkQueue.class;
1615 PHASE = U.objectFieldOffset(klass, "phase");
1616 BASE = U.objectFieldOffset(klass, "base");
1617 TOP = U.objectFieldOffset(klass, "top");
1618 ARRAY = U.objectFieldOffset(klass, "array");
1619 }
1620 }
1621
1622 // static fields (initialized in static initializer below)
1623
1624 /**
1625 * Creates a new ForkJoinWorkerThread. This factory is used unless
1626 * overridden in ForkJoinPool constructors.
1627 */
1628 public static final ForkJoinWorkerThreadFactory
1629 defaultForkJoinWorkerThreadFactory;
1630
1631 /**
1632 * Common (static) pool. Non-null for public use unless a static
1633 * construction exception, but internal usages null-check on use
1634 * to paranoically avoid potential initialization circularities
1635 * as well as to simplify generated code.
1636 */
1637 static final ForkJoinPool common;
1638
1639 /**
1640 * Sequence number for creating worker names
1641 */
1642 private static volatile int poolIds;
1643
1644 /**
1645 * For VirtualThread intrinsics
1646 */
1647 private static final JavaLangAccess JLA;
1648
1649 // fields declared in order of their likely layout on most VMs
1650 volatile CountDownLatch termination; // lazily constructed
1651 final Predicate<? super ForkJoinPool> saturate;
1652 final ForkJoinWorkerThreadFactory factory;
1653 final UncaughtExceptionHandler ueh; // per-worker UEH
1654 final SharedThreadContainer container;
1655 final String workerNamePrefix; // null for common pool
1656 final String poolName;
1657 volatile DelayScheduler delayScheduler; // lazily constructed
1658 WorkQueue[] queues; // main registry
1659 volatile long runState; // versioned, lockable
1660 final long keepAlive; // milliseconds before dropping if idle
1661 final long config; // static configuration bits
1662 volatile long stealCount; // collects worker nsteals
1663 volatile long threadIds; // for worker thread names
1664
1665 @jdk.internal.vm.annotation.Contended("fjpctl") // segregate
1666 volatile long ctl; // main pool control
1667 @jdk.internal.vm.annotation.Contended("fjpctl") // colocate
1668 int parallelism; // target number of workers
1669
1670 // Support for atomic operations
1671 private static final Unsafe U;
1672 private static final long CTL;
1673 private static final long RUNSTATE;
1674 private static final long PARALLELISM;
1675 private static final long THREADIDS;
1676 private static final long TERMINATION;
1677 private static final Object POOLIDS_BASE;
1678 private static final long POOLIDS;
1679
1680 private boolean compareAndSetCtl(long c, long v) {
1681 return U.compareAndSetLong(this, CTL, c, v);
1682 }
1683 private long compareAndExchangeCtl(long c, long v) {
1684 return U.compareAndExchangeLong(this, CTL, c, v);
1685 }
1686 private long getAndAddCtl(long v) {
1687 return U.getAndAddLong(this, CTL, v);
1688 }
1689 private long incrementThreadIds() {
1690 return U.getAndAddLong(this, THREADIDS, 1L);
1691 }
1692 private static int getAndAddPoolIds(int x) {
1693 return U.getAndAddInt(POOLIDS_BASE, POOLIDS, x);
1694 }
1695 private int getAndSetParallelism(int v) {
1696 return U.getAndSetInt(this, PARALLELISM, v);
1697 }
1698 private int getParallelismOpaque() {
1699 return U.getIntOpaque(this, PARALLELISM);
1700 }
1701 private CountDownLatch cmpExTerminationSignal(CountDownLatch x) {
1702 return (CountDownLatch)
1703 U.compareAndExchangeReference(this, TERMINATION, null, x);
1704 }
1705
1706 // runState operations
1707
1708 private long getAndBitwiseOrRunState(long v) { // for status bits
1709 return U.getAndBitwiseOrLong(this, RUNSTATE, v);
1710 }
1711 private boolean casRunState(long c, long v) {
1712 return U.compareAndSetLong(this, RUNSTATE, c, v);
1713 }
1714 private void unlockRunState() { // increment lock bit
1715 U.getAndAddLong(this, RUNSTATE, RS_LOCK);
1716 }
1717 private long lockRunState() { // lock and return current state
1718 long s, u; // locked when RS_LOCK set
1719 if (((s = runState) & RS_LOCK) == 0L && casRunState(s, u = s + RS_LOCK))
1720 return u;
1721 else
1722 return spinLockRunState();
1723 }
1724 private long spinLockRunState() { // spin/sleep
1725 for (int waits = 0;;) {
1726 long s, u;
1727 if (((s = runState) & RS_LOCK) == 0L) {
1728 if (casRunState(s, u = s + RS_LOCK))
1729 return u;
1730 waits = 0;
1731 } else if (waits < SPIN_WAITS) {
1732 ++waits;
1733 Thread.onSpinWait();
1734 } else {
1735 if (waits < MIN_SLEEP)
1736 waits = MIN_SLEEP;
1737 LockSupport.parkNanos(this, (long)waits);
1738 if (waits < MAX_SLEEP)
1739 waits <<= 1;
1740 }
1741 }
1742 }
1743
1744 static boolean poolIsStopping(ForkJoinPool p) { // Used by ForkJoinTask
1745 return p != null && (p.runState & STOP) != 0L;
1746 }
1747
1748 // Creating, registering, and deregistering workers
1749
1750 /**
1751 * Tries to construct and start one worker. Assumes that total
1752 * count has already been incremented as a reservation. Invokes
1753 * deregisterWorker on any failure.
1754 *
1755 * @return true if successful
1756 */
1757 private boolean createWorker() {
1758 ForkJoinWorkerThreadFactory fac = factory;
1759 SharedThreadContainer ctr = container;
1760 Throwable ex = null;
1761 ForkJoinWorkerThread wt = null;
1762 try {
1763 if ((runState & STOP) == 0L && // avoid construction if terminating
1764 fac != null && (wt = fac.newThread(this)) != null) {
1765 if (ctr != null)
1766 ctr.start(wt);
1767 else
1768 wt.start();
1769 return true;
1770 }
1771 } catch (Throwable rex) {
1772 ex = rex;
1773 }
1774 deregisterWorker(wt, ex);
1775 return false;
1776 }
1777
1778 /**
1779 * Provides a name for ForkJoinWorkerThread constructor.
1780 */
1781 final String nextWorkerThreadName() {
1782 String prefix = workerNamePrefix;
1783 long tid = incrementThreadIds() + 1L;
1784 if (prefix == null) // commonPool has no prefix
1785 prefix = "ForkJoinPool.commonPool-worker-";
1786 return prefix.concat(Long.toString(tid));
1787 }
1788
1789 /**
1790 * Finishes initializing and records internal queue.
1791 *
1792 * @param w caller's WorkQueue
1793 */
1794 final void registerWorker(WorkQueue w) {
1795 if (w != null) {
1796 w.array = new ForkJoinTask<?>[INITIAL_QUEUE_CAPACITY];
1797 ThreadLocalRandom.localInit();
1798 int seed = w.stackPred = ThreadLocalRandom.getProbe();
1799 int phaseSeq = seed & ~((IDLE << 1) - 1); // initial phase tag
1800 int id = ((seed << 1) | 1) & SMASK; // base of linear-probe-like scan
1801 long stop = lockRunState() & STOP;
1802 try {
1803 WorkQueue[] qs; int n;
1804 if (stop == 0L && (qs = queues) != null && (n = qs.length) > 0) {
1805 for (int k = n, m = n - 1; ; id += 2) {
1806 if (qs[id &= m] == null)
1807 break;
1808 if ((k -= 2) <= 0) {
1809 id |= n;
1810 break;
1811 }
1812 }
1813 w.phase = id | phaseSeq; // now publishable
1814 if (id < n)
1815 qs[id] = w;
1816 else { // expand
1817 int an = n << 1, am = an - 1;
1818 WorkQueue[] as = new WorkQueue[an];
1819 as[id & am] = w;
1820 for (int j = 1; j < n; j += 2)
1821 as[j] = qs[j];
1822 for (int j = 0; j < n; j += 2) {
1823 WorkQueue q; // shared queues may move
1824 if ((q = qs[j]) != null)
1825 as[q.phase & EXTERNAL_ID_MASK & am] = q;
1826 }
1827 U.storeFence(); // fill before publish
1828 queues = as;
1829 }
1830 }
1831 } finally {
1832 unlockRunState();
1833 }
1834 }
1835 }
1836
1837 /**
1838 * Final callback from terminating worker, as well as upon failure
1839 * to construct or start a worker. Removes record of worker from
1840 * array, and adjusts counts. If pool is shutting down, tries to
1841 * complete termination.
1842 *
1843 * @param wt the worker thread, or null if construction failed
1844 * @param ex the exception causing failure, or null if none
1845 */
1846 final void deregisterWorker(ForkJoinWorkerThread wt, Throwable ex) {
1847 WorkQueue w = null; // null if not created
1848 int phase = 0; // 0 if not registered
1849 if (wt != null && (w = wt.workQueue) != null &&
1850 (phase = w.phase) != 0 && (phase & IDLE) != 0)
1851 releaseWaiters(); // ensure released
1852 if (w == null || w.source != DROPPED) {
1853 long c = ctl; // decrement counts
1854 do {} while (c != (c = compareAndExchangeCtl(
1855 c, ((RC_MASK & (c - RC_UNIT)) |
1856 (TC_MASK & (c - TC_UNIT)) |
1857 (LMASK & c)))));
1858 }
1859 if (phase != 0 && w != null) { // remove index unless terminating
1860 long ns = w.nsteals & 0xffffffffL;
1861 if ((runState & STOP) == 0L) {
1862 WorkQueue[] qs; int n, i;
1863 if ((lockRunState() & STOP) == 0L &&
1864 (qs = queues) != null && (n = qs.length) > 0 &&
1865 qs[i = phase & SMASK & (n - 1)] == w) {
1866 qs[i] = null;
1867 stealCount += ns; // accumulate steals
1868 }
1869 unlockRunState();
1870 }
1871 }
1872 if ((tryTerminate(false, false) & STOP) == 0L &&
1873 phase != 0 && w != null && w.source != DROPPED) {
1874 w.cancelTasks(); // clean queue
1875 signalWork(null, 0); // possibly replace
1876 }
1877 if (ex != null)
1878 ForkJoinTask.rethrow(ex);
1879 }
1880
1881 /**
1882 * Releases an idle worker, or creates one if not enough exist,
1883 * giving up if array a is nonnull and task at a[k] already taken.
1884 */
1885 final void signalWork(ForkJoinTask<?>[] a, int k) {
1886 int pc = parallelism;
1887 for (long c = ctl;;) {
1888 WorkQueue[] qs = queues;
1889 long ac = (c + RC_UNIT) & RC_MASK, nc;
1890 int sp = (int)c, i = sp & SMASK;
1891 if ((short)(c >>> RC_SHIFT) >= pc)
1892 break;
1893 if (qs == null)
1894 break;
1895 if (qs.length <= i)
1896 break;
1897 WorkQueue w = qs[i], v = null;
1898 if (sp == 0) {
1899 if ((short)(c >>> TC_SHIFT) >= pc)
1900 break;
1901 nc = ((c + TC_UNIT) & TC_MASK) | ac;
1902 }
1903 else if ((v = w) == null)
1904 break;
1905 else
1906 nc = (v.stackPred & LMASK) | (c & TC_MASK) | ac;
1907 if (a != null && k < a.length && k >= 0 && a[k] == null)
1908 break;
1909 if (c == (c = ctl) && c == (c = compareAndExchangeCtl(c, nc))) {
1910 if (v == null)
1911 createWorker();
1912 else {
1913 v.phase = sp;
1914 if (v.parking != 0)
1915 U.unpark(v.owner);
1916 }
1917 break;
1918 }
1919 }
1920 }
1921
1922 /**
1923 * Releases all waiting workers. Called only during shutdown.
1924 */
1925 private void releaseWaiters() {
1926 for (long c = ctl;;) {
1927 WorkQueue[] qs; WorkQueue v; int sp, i;
1928 if ((sp = (int)c) == 0 || (qs = queues) == null ||
1929 qs.length <= (i = sp & SMASK) || (v = qs[i]) == null)
1930 break;
1931 if (c == (c = compareAndExchangeCtl(
1932 c, ((UMASK & (c + RC_UNIT)) | (c & TC_MASK) |
1933 (v.stackPred & LMASK))))) {
1934 v.phase = sp;
1935 if (v.parking != 0)
1936 U.unpark(v.owner);
1937 }
1938 }
1939 }
1940
1941 /**
1942 * Internal version of isQuiescent and related functionality.
1943 * @return positive if stopping, nonnegative if terminating or all
1944 * workers are inactive and submission queues are empty and
1945 * unlocked; if so, setting STOP if shutdown is enabled
1946 */
1947 private int quiescent() {
1948 for (;;) {
1949 long phaseSum = 0L;
1950 boolean swept = false;
1951 for (long e, prevRunState = 0L; ; prevRunState = e) {
1952 DelayScheduler ds;
1953 long c = ctl;
1954 if (((e = runState) & STOP) != 0L)
1955 return 1; // terminating
1956 else if ((c & RC_MASK) > 0L)
1957 return -1; // at least one active
1958 else if (!swept || e != prevRunState || (e & RS_LOCK) != 0) {
1959 long sum = c;
1960 WorkQueue[] qs = queues;
1961 int n = (qs == null) ? 0 : qs.length;
1962 for (int i = 0; i < n; ++i) { // scan queues
1963 WorkQueue q;
1964 if ((q = qs[i]) != null) {
1965 int p = q.phase, s = q.top, b = q.base;
1966 sum += (p & 0xffffffffL) | ((long)b << 32);
1967 if ((p & IDLE) == 0 || s - b > 0)
1968 return -1;
1969 }
1970 }
1971 swept = (phaseSum == (phaseSum = sum));
1972 }
1973 else if ((e & SHUTDOWN) == 0)
1974 return 0;
1975 else if ((ds = delayScheduler) != null && !ds.canShutDown())
1976 return 0;
1977 else if (compareAndSetCtl(c, c) && casRunState(e, e | STOP))
1978 return 1; // enable termination
1979 else
1980 break; // restart
1981 }
1982 }
1983 }
1984
1985 /**
1986 * Top-level runloop for workers, called by ForkJoinWorkerThread.run.
1987 * See above for explanation.
1988 *
1989 * @param w caller's WorkQueue (may be null on failed initialization)
1990 */
1991 final void runWorker(WorkQueue w) {
1992 if (w != null && w.phase != 0) { // else unregistered
1993 WorkQueue[] qs;
1994 int cfg = w.config, r = w.stackPred; // seed from registerWorker
1995 int rescans = 0, inactive = 0, taken = 0, n;
1996 while ((runState & STOP) == 0L && (qs = queues) != null &&
1997 (n = qs.length) > 0) {
1998 int i = r, step = (r >>> 16) | 1;
1999 r ^= r << 13; r ^= r >>> 17; r ^= r << 5; // xorshift
2000 scan: for (int j = n; j != 0; --j, i += step) {
2001 WorkQueue q; int qid;
2002 if ((q = qs[qid = i & (n - 1)]) != null) {
2003 ForkJoinTask<?>[] a; int cap; // poll queue
2004 while ((a = q.array) != null && (cap = a.length) > 0) {
2005 int b, nb, nk; long bp; ForkJoinTask<?> t;
2006 t = (ForkJoinTask<?>)U.getReferenceAcquire(
2007 a, bp = slotOffset((cap - 1) & (b = q.base)));
2008 if (q.base != b)
2009 continue; // inconsistent
2010 long np = slotOffset(nk = (nb = b + 1) & (cap - 1));
2011 if (t == null) {
2012 if (q.array != a) // resized
2013 continue;
2014 if (rescans > 0) // ran or stalled
2015 break scan;
2016 if (U.getReference(a, np) != null ||
2017 (rescans < 0 &&
2018 (U.getReferenceAcquire(a, bp) != null ||
2019 q.top != q.base))) {
2020 rescans = 1; // may be stalled
2021 continue;
2022 }
2023 break; // probably empty
2024 }
2025 else if (inactive != 0) {
2026 if ((inactive = tryReactivate(w)) != 0) {
2027 rescans = 1; // can't take yet
2028 break scan;
2029 }
2030 }
2031 else if (U.compareAndSetReference(a, bp, t, null)) {
2032 q.base = nb;
2033 Object nt = U.getReferenceAcquire(a, np);
2034 w.source = qid;
2035 rescans = 1;
2036 ++taken;
2037 if (nt != null && // confirm a[nk]
2038 U.getReferenceAcquire(a, np) == nt)
2039 signalWork(a, nk); // propagate
2040 w.topLevelExec(t, cfg);
2041 }
2042 }
2043 }
2044 }
2045 if (rescans >= 0)
2046 --rescans;
2047 else if (inactive == 0) {
2048 if ((inactive = deactivate(w, taken)) != 0)
2049 taken = 0;
2050 }
2051 else if (awaitWork(w) == 0)
2052 inactive = rescans = 0;
2053 else
2054 break;
2055 }
2056 }
2057 }
2058
2059 /**
2060 * Tries to deactivate worker, keeping active on contention
2061 *
2062 * @param w the work queue
2063 * @param taken nonzero if stole tasks since last deactivation
2064 * @return nonzero if inactive
2065 */
2066 private int deactivate(WorkQueue w, int taken) {
2067 int inactive = 0, phase;
2068 if (w != null && (inactive = (phase = w.phase) & IDLE) == 0) {
2069 long sp = (phase + (IDLE << 1)) & LMASK, pc, c;
2070 w.phase = phase | IDLE;
2071 w.stackPred = (int)(pc = ctl); // set ctl stack link
2072 if (!compareAndSetCtl( // try to enqueue
2073 pc, c = ((pc - RC_UNIT) & UMASK) | sp))
2074 w.phase = phase; // back out on contention
2075 else {
2076 if (taken != 0)
2077 w.nsteals += taken;
2078 if (((c & RC_MASK) == 0L && quiescent() > 0) || taken == 0)
2079 inactive = w.phase & IDLE; // check quiescent termination
2080 else { // spin for approx 1 scan cost
2081 int tc = (short)(c >>> TC_SHIFT);
2082 int spins = Math.max((tc << 1) + tc, SPIN_WAITS);
2083 while ((inactive = w.phase & IDLE) != 0 && --spins != 0)
2084 Thread.onSpinWait();
2085 }
2086 }
2087 }
2088 return inactive;
2089 }
2090
2091 /**
2092 * Reactivates worker w if it is currently top of ctl stack
2093 *
2094 * @param w the work queue
2095 * @return 0 if now active
2096 */
2097 private int tryReactivate(WorkQueue w) {
2098 int inactive = 0;
2099 if (w != null) { // always true; hoist checks
2100 int sp = w.stackPred, phase, activePhase; long c;
2101 if ((inactive = (phase = w.phase) & IDLE) != 0 &&
2102 (int)(c = ctl) == (activePhase = phase + IDLE) &&
2103 compareAndSetCtl(c, (sp & LMASK) | ((c + RC_UNIT) & UMASK))) {
2104 w.phase = activePhase;
2105 inactive = 0;
2106 }
2107 }
2108 return inactive;
2109 }
2110
2111 /**
2112 * Awaits signal or termination.
2113 *
2114 * @param w the work queue
2115 * @return 0 if now active
2116 */
2117 private int awaitWork(WorkQueue w) {
2118 int inactive = 0, phase;
2119 if (w != null) { // always true; hoist checks
2120 long waitTime = (w.source == INVALID_ID) ? 0L : keepAlive;
2121 if ((inactive = (phase = w.phase) & IDLE) != 0) {
2122 LockSupport.setCurrentBlocker(this);
2123 int activePhase = phase + IDLE;
2124 for (long deadline = 0L;;) {
2125 Thread.interrupted(); // clear status
2126 if ((runState & STOP) != 0L)
2127 break;
2128 boolean trimmable = false; // use timed wait if trimmable
2129 long d = 0L, c;
2130 if (((c = ctl) & RC_MASK) == 0L && (int)c == activePhase) {
2131 long now = System.currentTimeMillis();
2132 if (deadline == 0L)
2133 deadline = waitTime + now;
2134 if (deadline - now <= TIMEOUT_SLOP) {
2135 if (tryTrim(w, c, activePhase))
2136 break;
2137 continue; // lost race to trim
2138 }
2139 d = deadline;
2140 trimmable = true;
2141 }
2142 w.parking = 1; // enable unpark and recheck
2143 if ((inactive = w.phase & IDLE) != 0)
2144 U.park(trimmable, d);
2145 w.parking = 0; // close unpark window
2146 if (inactive == 0 || (inactive = w.phase & IDLE) == 0)
2147 break;
2148 }
2149 LockSupport.setCurrentBlocker(null);
2150 }
2151 }
2152 return inactive;
2153 }
2154
2155 /**
2156 * Tries to remove and deregister worker after timeout, and release
2157 * another to do the same unless new tasks are found.
2158 */
2159 private boolean tryTrim(WorkQueue w, long c, int activePhase) {
2160 if (w != null) {
2161 int vp, i; WorkQueue[] vs; WorkQueue v;
2162 long nc = ((w.stackPred & LMASK) |
2163 ((RC_MASK & c) | (TC_MASK & (c - TC_UNIT))));
2164 if (compareAndSetCtl(c, nc)) {
2165 w.source = DROPPED;
2166 w.phase = activePhase;
2167 if ((vp = (int)nc) != 0 && (vs = queues) != null &&
2168 vs.length > (i = vp & SMASK) && (v = vs[i]) != null &&
2169 compareAndSetCtl( // try to wake up next waiter
2170 nc, ((v.stackPred & LMASK) |
2171 ((UMASK & (nc + RC_UNIT)) | (nc & TC_MASK))))) {
2172 v.source = INVALID_ID; // enable cascaded timeouts
2173 v.phase = vp;
2174 U.unpark(v.owner);
2175 }
2176 return true;
2177 }
2178 }
2179 return false;
2180 }
2181
2182 /**
2183 * Scans for and returns a polled task, if available. Used only
2184 * for untracked polls. Begins scan at a random index to avoid
2185 * systematic unfairness.
2186 *
2187 * @param submissionsOnly if true, only scan submission queues
2188 */
2189 private ForkJoinTask<?> pollScan(boolean submissionsOnly) {
2190 if ((runState & STOP) == 0L) {
2191 WorkQueue[] qs; int n; WorkQueue q; ForkJoinTask<?> t;
2192 int r = ThreadLocalRandom.nextSecondarySeed();
2193 if (submissionsOnly) // even indices only
2194 r &= ~1;
2195 int step = (submissionsOnly) ? 2 : 1;
2196 if ((qs = queues) != null && (n = qs.length) > 0) {
2197 for (int i = n; i > 0; i -= step, r += step) {
2198 if ((q = qs[r & (n - 1)]) != null &&
2199 (t = q.poll()) != null)
2200 return t;
2201 }
2202 }
2203 }
2204 return null;
2205 }
2206
2207 /**
2208 * Tries to decrement counts (sometimes implicitly) and possibly
2209 * arrange for a compensating worker in preparation for
2210 * blocking. May fail due to interference, in which case -1 is
2211 * returned so caller may retry. A zero return value indicates
2212 * that the caller doesn't need to re-adjust counts when later
2213 * unblocked.
2214 *
2215 * @param c incoming ctl value
2216 * @return UNCOMPENSATE: block then adjust, 0: block, -1 : retry
2217 */
2218 private int tryCompensate(long c) {
2219 Predicate<? super ForkJoinPool> sat;
2220 long b = config;
2221 int pc = parallelism, // unpack fields
2222 minActive = (short)(b >>> RC_SHIFT),
2223 maxTotal = (short)(b >>> TC_SHIFT) + pc,
2224 active = (short)(c >>> RC_SHIFT),
2225 total = (short)(c >>> TC_SHIFT),
2226 sp = (int)c,
2227 stat = -1; // default retry return
2228 if (sp != 0 && active <= pc) { // activate idle worker
2229 WorkQueue[] qs; WorkQueue v; int i;
2230 if ((qs = queues) != null && qs.length > (i = sp & SMASK) &&
2231 (v = qs[i]) != null &&
2232 compareAndSetCtl(c, (c & UMASK) | (v.stackPred & LMASK))) {
2233 v.phase = sp;
2234 if (v.parking != 0)
2235 U.unpark(v.owner);
2236 stat = UNCOMPENSATE;
2237 }
2238 }
2239 else if (active > minActive && total >= pc) { // reduce active workers
2240 if (compareAndSetCtl(c, ((c - RC_UNIT) & RC_MASK) | (c & ~RC_MASK)))
2241 stat = UNCOMPENSATE;
2242 }
2243 else if (total < maxTotal && total < MAX_CAP) { // try to expand pool
2244 long nc = ((c + TC_UNIT) & TC_MASK) | (c & ~TC_MASK);
2245 if ((runState & STOP) != 0L) // terminating
2246 stat = 0;
2247 else if (compareAndSetCtl(c, nc))
2248 stat = createWorker() ? UNCOMPENSATE : 0;
2249 }
2250 else if (!compareAndSetCtl(c, c)) // validate
2251 ;
2252 else if ((sat = saturate) != null && sat.test(this))
2253 stat = 0;
2254 else
2255 throw new RejectedExecutionException(
2256 "Thread limit exceeded replacing blocked worker");
2257 return stat;
2258 }
2259
2260 /**
2261 * Readjusts RC count; called from ForkJoinTask after blocking.
2262 */
2263 final void uncompensate() {
2264 getAndAddCtl(RC_UNIT);
2265 }
2266
2267 /**
2268 * Helps if possible until the given task is done. Processes
2269 * compatible local tasks and scans other queues for task produced
2270 * by w's stealers; returning compensated blocking sentinel if
2271 * none are found.
2272 *
2273 * @param task the task
2274 * @param w caller's WorkQueue
2275 * @param internal true if w is owned by a ForkJoinWorkerThread
2276 * @return task status on exit, or UNCOMPENSATE for compensated blocking
2277 */
2278 final int helpJoin(ForkJoinTask<?> task, WorkQueue w, boolean internal) {
2279 if (w != null)
2280 w.tryRemoveAndExec(task, internal);
2281 int s = 0;
2282 if (task != null && (s = task.status) >= 0 && internal && w != null) {
2283 int wid = w.phase & SMASK, r = wid + 2, wsrc = w.source;
2284 long sctl = 0L; // track stability
2285 outer: for (boolean rescan = true;;) {
2286 if ((s = task.status) < 0)
2287 break;
2288 if (!rescan) {
2289 if ((runState & STOP) != 0L)
2290 break;
2291 if (sctl == (sctl = ctl) && (s = tryCompensate(sctl)) >= 0)
2292 break;
2293 }
2294 rescan = false;
2295 WorkQueue[] qs = queues;
2296 int n = (qs == null) ? 0 : qs.length;
2297 scan: for (int l = n >>> 1; l > 0; --l, r += 2) {
2298 int j; WorkQueue q;
2299 if ((q = qs[j = r & SMASK & (n - 1)]) != null) {
2300 for (;;) {
2301 ForkJoinTask<?> t; ForkJoinTask<?>[] a;
2302 boolean eligible = false;
2303 int sq = q.source, b, cap; long k;
2304 if ((a = q.array) == null || (cap = a.length) <= 0)
2305 break;
2306 t = (ForkJoinTask<?>)U.getReferenceAcquire(
2307 a, k = slotOffset((cap - 1) & (b = q.base)));
2308 if (t == task)
2309 eligible = true;
2310 else if (t != null) { // check steal chain
2311 for (int v = sq, d = cap;;) {
2312 WorkQueue p;
2313 if (v == wid) {
2314 eligible = true;
2315 break;
2316 }
2317 if ((v & 1) == 0 || // external or none
2318 --d < 0 || // bound depth
2319 (p = qs[v & (n - 1)]) == null)
2320 break;
2321 v = p.source;
2322 }
2323 }
2324 if ((s = task.status) < 0)
2325 break outer; // validate
2326 if (q.source == sq && q.base == b &&
2327 U.getReference(a, k) == t) {
2328 if (!eligible) { // revisit if nonempty
2329 if (!rescan && t == null && q.top - b > 0)
2330 rescan = true;
2331 break;
2332 }
2333 if (U.compareAndSetReference(a, k, t, null)) {
2334 q.base = b + 1;
2335 w.source = j; // volatile write
2336 t.doExec();
2337 w.source = wsrc;
2338 rescan = true; // restart at index r
2339 break scan;
2340 }
2341 }
2342 }
2343 }
2344 }
2345 }
2346 }
2347 return s;
2348 }
2349
2350 /**
2351 * Version of helpJoin for CountedCompleters.
2352 *
2353 * @param task root of computation (only called when a CountedCompleter)
2354 * @param w caller's WorkQueue
2355 * @param internal true if w is owned by a ForkJoinWorkerThread
2356 * @return task status on exit, or UNCOMPENSATE for compensated blocking
2357 */
2358 final int helpComplete(ForkJoinTask<?> task, WorkQueue w, boolean internal) {
2359 int s = 0;
2360 if (task != null && (s = task.status) >= 0 && w != null) {
2361 int r = w.phase + 1; // for indexing
2362 long sctl = 0L; // track stability
2363 outer: for (boolean rescan = true, locals = true;;) {
2364 if (locals && (s = w.helpComplete(task, internal, 0)) < 0)
2365 break;
2366 if ((s = task.status) < 0)
2367 break;
2368 if (!rescan) {
2369 if ((runState & STOP) != 0L)
2370 break;
2371 if (sctl == (sctl = ctl) &&
2372 (!internal || (s = tryCompensate(sctl)) >= 0))
2373 break;
2374 }
2375 rescan = locals = false;
2376 WorkQueue[] qs = queues;
2377 int n = (qs == null) ? 0 : qs.length;
2378 scan: for (int l = n; l > 0; --l, ++r) {
2379 int j; WorkQueue q;
2380 if ((q = qs[j = r & SMASK & (n - 1)]) != null) {
2381 for (;;) {
2382 ForkJoinTask<?> t; ForkJoinTask<?>[] a;
2383 int b, cap, nb; long k;
2384 boolean eligible = false;
2385 if ((a = q.array) == null || (cap = a.length) <= 0)
2386 break;
2387 t = (ForkJoinTask<?>)U.getReferenceAcquire(
2388 a, k = slotOffset((cap - 1) & (b = q.base)));
2389 if (t instanceof CountedCompleter) {
2390 CountedCompleter<?> f = (CountedCompleter<?>)t;
2391 for (int steps = cap; steps > 0; --steps) {
2392 if (f == task) {
2393 eligible = true;
2394 break;
2395 }
2396 if ((f = f.completer) == null)
2397 break;
2398 }
2399 }
2400 if ((s = task.status) < 0) // validate
2401 break outer;
2402 if (q.base == b) {
2403 if (eligible) {
2404 if (U.compareAndSetReference(
2405 a, k, t, null)) {
2406 q.updateBase(b + 1);
2407 t.doExec();
2408 locals = rescan = true;
2409 break scan;
2410 }
2411 }
2412 else if (U.getReference(a, k) == t) {
2413 if (!rescan && t == null && q.top - b > 0)
2414 rescan = true; // revisit
2415 break;
2416 }
2417 }
2418 }
2419 }
2420 }
2421 }
2422 }
2423 return s;
2424 }
2425
2426 /**
2427 * Runs tasks until all workers are inactive and no tasks are
2428 * found. Rather than blocking when tasks cannot be found, rescans
2429 * until all others cannot find tasks either.
2430 *
2431 * @param nanos max wait time (Long.MAX_VALUE if effectively untimed)
2432 * @param interruptible true if return on interrupt
2433 * @return positive if quiescent, negative if interrupted, else 0
2434 */
2435 private int helpQuiesce(WorkQueue w, long nanos, boolean interruptible) {
2436 int phase; // w.phase inactive bit set when temporarily quiescent
2437 if (w == null || ((phase = w.phase) & IDLE) != 0)
2438 return 0;
2439 int wsrc = w.source;
2440 long startTime = System.nanoTime();
2441 long maxSleep = Math.min(nanos >>> 8, MAX_SLEEP); // approx 1% nanos
2442 long prevSum = 0L;
2443 int activePhase = phase, inactivePhase = phase + IDLE;
2444 int r = phase + 1, waits = 0, returnStatus = 1;
2445 boolean locals = true;
2446 for (long e = runState;;) {
2447 if ((e & STOP) != 0L)
2448 break; // terminating
2449 if (interruptible && Thread.interrupted()) {
2450 returnStatus = -1;
2451 break;
2452 }
2453 if (locals) { // run local tasks before (re)polling
2454 locals = false;
2455 for (ForkJoinTask<?> u; (u = w.nextLocalTask()) != null;)
2456 u.doExec();
2457 }
2458 WorkQueue[] qs = queues;
2459 int n = (qs == null) ? 0 : qs.length;
2460 long phaseSum = 0L;
2461 boolean rescan = false, busy = false;
2462 scan: for (int l = n; l > 0; --l, ++r) {
2463 int j; WorkQueue q;
2464 if ((q = qs[j = r & SMASK & (n - 1)]) != null && q != w) {
2465 for (;;) {
2466 ForkJoinTask<?> t; ForkJoinTask<?>[] a;
2467 int b, cap; long k;
2468 if ((a = q.array) == null || (cap = a.length) <= 0)
2469 break;
2470 t = (ForkJoinTask<?>)U.getReferenceAcquire(
2471 a, k = slotOffset((cap - 1) & (b = q.base)));
2472 if (t != null && phase == inactivePhase) // reactivate
2473 w.phase = phase = activePhase;
2474 if (q.base == b && U.getReference(a, k) == t) {
2475 int nb = b + 1;
2476 if (t == null) {
2477 if (!rescan) {
2478 int qp = q.phase, mq = qp & (IDLE | 1);
2479 phaseSum += qp;
2480 if (mq == 0 || q.top - b > 0)
2481 rescan = true;
2482 else if (mq == 1)
2483 busy = true;
2484 }
2485 break;
2486 }
2487 if (U.compareAndSetReference(a, k, t, null)) {
2488 q.base = nb;
2489 w.source = j; // volatile write
2490 t.doExec();
2491 w.source = wsrc;
2492 rescan = locals = true;
2493 break scan;
2494 }
2495 }
2496 }
2497 }
2498 }
2499 if (e != (e = runState) || prevSum != (prevSum = phaseSum) ||
2500 rescan || (e & RS_LOCK) != 0L)
2501 ; // inconsistent
2502 else if (!busy)
2503 break;
2504 else if (phase == activePhase) {
2505 waits = 0; // recheck, then sleep
2506 w.phase = phase = inactivePhase;
2507 }
2508 else if (System.nanoTime() - startTime > nanos) {
2509 returnStatus = 0; // timed out
2510 break;
2511 }
2512 else if (waits == 0) // same as spinLockRunState except
2513 waits = MIN_SLEEP; // with rescan instead of onSpinWait
2514 else {
2515 LockSupport.parkNanos(this, (long)waits);
2516 if (waits < maxSleep)
2517 waits <<= 1;
2518 }
2519 }
2520 w.phase = activePhase;
2521 return returnStatus;
2522 }
2523
2524 /**
2525 * Helps quiesce from external caller until done, interrupted, or timeout
2526 *
2527 * @param nanos max wait time (Long.MAX_VALUE if effectively untimed)
2528 * @param interruptible true if return on interrupt
2529 * @return positive if quiescent, negative if interrupted, else 0
2530 */
2531 private int externalHelpQuiesce(long nanos, boolean interruptible) {
2532 if (quiescent() < 0) {
2533 long startTime = System.nanoTime();
2534 long maxSleep = Math.min(nanos >>> 8, MAX_SLEEP);
2535 for (int waits = 0;;) {
2536 ForkJoinTask<?> t;
2537 if (interruptible && Thread.interrupted())
2538 return -1;
2539 else if ((t = pollScan(false)) != null) {
2540 waits = 0;
2541 t.doExec();
2542 }
2543 else if (quiescent() >= 0)
2544 break;
2545 else if (System.nanoTime() - startTime > nanos)
2546 return 0;
2547 else if (waits == 0)
2548 waits = MIN_SLEEP;
2549 else {
2550 LockSupport.parkNanos(this, (long)waits);
2551 if (waits < maxSleep)
2552 waits <<= 1;
2553 }
2554 }
2555 }
2556 return 1;
2557 }
2558
2559 /**
2560 * Helps quiesce from either internal or external caller
2561 *
2562 * @param pool the pool to use, or null if any
2563 * @param nanos max wait time (Long.MAX_VALUE if effectively untimed)
2564 * @param interruptible true if return on interrupt
2565 * @return positive if quiescent, negative if interrupted, else 0
2566 */
2567 static final int helpQuiescePool(ForkJoinPool pool, long nanos,
2568 boolean interruptible) {
2569 Thread t; ForkJoinPool p; ForkJoinWorkerThread wt;
2570 if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread &&
2571 (p = (wt = (ForkJoinWorkerThread)t).pool) != null &&
2572 (p == pool || pool == null))
2573 return p.helpQuiesce(wt.workQueue, nanos, interruptible);
2574 else if ((p = pool) != null || (p = common) != null)
2575 return p.externalHelpQuiesce(nanos, interruptible);
2576 else
2577 return 0;
2578 }
2579
2580 /**
2581 * Gets and removes a local or stolen task for the given worker.
2582 *
2583 * @return a task, if available
2584 */
2585 final ForkJoinTask<?> nextTaskFor(WorkQueue w) {
2586 ForkJoinTask<?> t;
2587 if (w == null || (t = w.nextLocalTask()) == null)
2588 t = pollScan(false);
2589 return t;
2590 }
2591
2592 // External operations
2593
2594 /**
2595 * Finds and locks a WorkQueue for an external submitter, or
2596 * throws RejectedExecutionException if shutdown
2597 * @param rejectOnShutdown true if RejectedExecutionException
2598 * should be thrown when shutdown
2599 */
2600 final WorkQueue externalSubmissionQueue(boolean rejectOnShutdown) {
2601 int r;
2602 if ((r = ThreadLocalRandom.getProbe()) == 0) {
2603 ThreadLocalRandom.localInit(); // initialize caller's probe
2604 r = ThreadLocalRandom.getProbe();
2605 }
2606 for (;;) {
2607 WorkQueue q; WorkQueue[] qs; int n, id, i;
2608 if ((qs = queues) == null || (n = qs.length) <= 0)
2609 break;
2610 if ((q = qs[i = (id = r & EXTERNAL_ID_MASK) & (n - 1)]) == null) {
2611 WorkQueue newq = new WorkQueue(null, id, 0, false);
2612 lockRunState();
2613 if (qs[i] == null && queues == qs)
2614 q = qs[i] = newq; // else lost race to install
2615 unlockRunState();
2616 }
2617 if (q != null && q.tryLockPhase()) {
2618 if (rejectOnShutdown && (runState & SHUTDOWN) != 0L) {
2619 q.unlockPhase(); // check while q lock held
2620 break;
2621 }
2622 return q;
2623 }
2624 r = ThreadLocalRandom.advanceProbe(r); // move
2625 }
2626 throw new RejectedExecutionException();
2627 }
2628
2629 private <T> ForkJoinTask<T> poolSubmit(boolean signalIfEmpty, ForkJoinTask<T> task) {
2630 Thread t; ForkJoinWorkerThread wt; WorkQueue q; boolean internal;
2631 if (((t = JLA.currentCarrierThread()) instanceof ForkJoinWorkerThread) &&
2632 (wt = (ForkJoinWorkerThread)t).pool == this) {
2633 internal = true;
2634 q = wt.workQueue;
2635 }
2636 else { // find and lock queue
2637 internal = false;
2638 q = externalSubmissionQueue(true);
2639 }
2640 q.push(task, signalIfEmpty ? this : null, internal);
2641 return task;
2642 }
2643
2644 /**
2645 * Returns queue for an external thread, if one exists that has
2646 * possibly ever submitted to the given pool (nonzero probe), or
2647 * null if none.
2648 */
2649 static WorkQueue externalQueue(ForkJoinPool p) {
2650 WorkQueue[] qs; int n;
2651 int r = ThreadLocalRandom.getProbe();
2652 return (p != null && (qs = p.queues) != null &&
2653 (n = qs.length) > 0 && r != 0) ?
2654 qs[r & EXTERNAL_ID_MASK & (n - 1)] : null;
2655 }
2656
2657 /**
2658 * Returns external queue for common pool.
2659 */
2660 static WorkQueue commonQueue() {
2661 return externalQueue(common);
2662 }
2663
2664 /**
2665 * If the given executor is a ForkJoinPool, poll and execute
2666 * AsynchronousCompletionTasks from worker's queue until none are
2667 * available or blocker is released.
2668 */
2669 static void helpAsyncBlocker(Executor e, ManagedBlocker blocker) {
2670 WorkQueue w = null; Thread t; ForkJoinWorkerThread wt;
2671 if (((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) &&
2672 (wt = (ForkJoinWorkerThread)t).pool == e)
2673 w = wt.workQueue;
2674 else if (e instanceof ForkJoinPool)
2675 w = externalQueue((ForkJoinPool)e);
2676 if (w != null)
2677 w.helpAsyncBlocker(blocker);
2678 }
2679
2680 /**
2681 * Returns a cheap heuristic guide for task partitioning when
2682 * programmers, frameworks, tools, or languages have little or no
2683 * idea about task granularity. In essence, by offering this
2684 * method, we ask users only about tradeoffs in overhead vs
2685 * expected throughput and its variance, rather than how finely to
2686 * partition tasks.
2687 *
2688 * In a steady state strict (tree-structured) computation, each
2689 * thread makes available for stealing enough tasks for other
2690 * threads to remain active. Inductively, if all threads play by
2691 * the same rules, each thread should make available only a
2692 * constant number of tasks.
2693 *
2694 * The minimum useful constant is just 1. But using a value of 1
2695 * would require immediate replenishment upon each steal to
2696 * maintain enough tasks, which is infeasible. Further,
2697 * partitionings/granularities of offered tasks should minimize
2698 * steal rates, which in general means that threads nearer the top
2699 * of computation tree should generate more than those nearer the
2700 * bottom. In perfect steady state, each thread is at
2701 * approximately the same level of computation tree. However,
2702 * producing extra tasks amortizes the uncertainty of progress and
2703 * diffusion assumptions.
2704 *
2705 * So, users will want to use values larger (but not much larger)
2706 * than 1 to both smooth over transient shortages and hedge
2707 * against uneven progress; as traded off against the cost of
2708 * extra task overhead. We leave the user to pick a threshold
2709 * value to compare with the results of this call to guide
2710 * decisions, but recommend values such as 3.
2711 *
2712 * When all threads are active, it is on average OK to estimate
2713 * surplus strictly locally. In steady-state, if one thread is
2714 * maintaining say 2 surplus tasks, then so are others. So we can
2715 * just use estimated queue length. However, this strategy alone
2716 * leads to serious mis-estimates in some non-steady-state
2717 * conditions (ramp-up, ramp-down, other stalls). We can detect
2718 * many of these by further considering the number of "idle"
2719 * threads, that are known to have zero queued tasks, so
2720 * compensate by a factor of (#idle/#active) threads.
2721 */
2722 static int getSurplusQueuedTaskCount() {
2723 Thread t; ForkJoinWorkerThread wt; ForkJoinPool pool; WorkQueue q;
2724 if (((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) &&
2725 (pool = (wt = (ForkJoinWorkerThread)t).pool) != null &&
2726 (q = wt.workQueue) != null) {
2727 int n = q.top - q.base;
2728 int p = pool.parallelism;
2729 int a = (short)(pool.ctl >>> RC_SHIFT);
2730 return n - (a > (p >>>= 1) ? 0 :
2731 a > (p >>>= 1) ? 1 :
2732 a > (p >>>= 1) ? 2 :
2733 a > (p >>>= 1) ? 4 :
2734 8);
2735 }
2736 return 0;
2737 }
2738
2739 // Termination
2740
2741 /**
2742 * Possibly initiates and/or completes pool termination.
2743 *
2744 * @param now if true, unconditionally terminate, else only
2745 * if no work and no active workers
2746 * @param enable if true, terminate when next possible
2747 * @return runState on exit
2748 */
2749 private long tryTerminate(boolean now, boolean enable) {
2750 long e, isShutdown, ps;
2751 if (((e = runState) & TERMINATED) != 0L)
2752 now = false;
2753 else if ((e & STOP) != 0L)
2754 now = true;
2755 else if (now) {
2756 if (((ps = getAndBitwiseOrRunState(SHUTDOWN|STOP) & STOP)) == 0L) {
2757 if ((ps & RS_LOCK) != 0L) {
2758 spinLockRunState(); // ensure queues array stable after stop
2759 unlockRunState();
2760 }
2761 interruptAll();
2762 }
2763 }
2764 else if ((isShutdown = (e & SHUTDOWN)) != 0L || enable) {
2765 long quiet; DelayScheduler ds;
2766 if (isShutdown == 0L)
2767 getAndBitwiseOrRunState(SHUTDOWN);
2768 if ((quiet = quiescent()) > 0)
2769 now = true;
2770 else if (quiet == 0 && (ds = delayScheduler) != null)
2771 ds.signal();
2772 }
2773
2774 if (now) {
2775 DelayScheduler ds;
2776 releaseWaiters();
2777 if ((ds = delayScheduler) != null)
2778 ds.signal();
2779 for (;;) {
2780 if (((e = runState) & CLEANED) == 0L) {
2781 boolean clean = cleanQueues();
2782 if (((e = runState) & CLEANED) == 0L && clean)
2783 e = getAndBitwiseOrRunState(CLEANED) | CLEANED;
2784 }
2785 if ((e & TERMINATED) != 0L)
2786 break;
2787 if (ctl != 0L) // else loop if didn't finish cleaning
2788 break;
2789 if ((ds = delayScheduler) != null && ds.signal() >= 0)
2790 break;
2791 if ((e & CLEANED) != 0L) {
2792 e |= TERMINATED;
2793 if ((getAndBitwiseOrRunState(TERMINATED) & TERMINATED) == 0L) {
2794 CountDownLatch done; SharedThreadContainer ctr;
2795 if ((done = termination) != null)
2796 done.countDown();
2797 if ((ctr = container) != null)
2798 ctr.close();
2799 }
2800 break;
2801 }
2802 }
2803 }
2804 return e;
2805 }
2806
2807 /**
2808 * Scans queues in a psuedorandom order based on thread id,
2809 * cancelling tasks until empty, or returning early upon
2810 * interference or still-active external queues, in which case
2811 * other calls will finish cancellation.
2812 *
2813 * @return true if all queues empty
2814 */
2815 private boolean cleanQueues() {
2816 int r = (int)Thread.currentThread().threadId();
2817 r ^= r << 13; r ^= r >>> 17; r ^= r << 5; // xorshift
2818 int step = (r >>> 16) | 1; // randomize traversals
2819 WorkQueue[] qs = queues;
2820 int n = (qs == null) ? 0 : qs.length;
2821 for (int l = n; l > 0; --l, r += step) {
2822 WorkQueue q; ForkJoinTask<?>[] a; int cap;
2823 if ((q = qs[r & (n - 1)]) != null &&
2824 (a = q.array) != null && (cap = a.length) > 0) {
2825 for (;;) {
2826 ForkJoinTask<?> t; int b; long k;
2827 t = (ForkJoinTask<?>)U.getReferenceAcquire(
2828 a, k = slotOffset((cap - 1) & (b = q.base)));
2829 if (q.base == b && t != null &&
2830 U.compareAndSetReference(a, k, t, null)) {
2831 q.updateBase(b + 1);
2832 try {
2833 t.cancel(false);
2834 } catch (Throwable ignore) {
2835 }
2836 }
2837 else if ((q.phase & (IDLE|1)) == 0 || // externally locked
2838 q.top - q.base > 0)
2839 return false; // incomplete
2840 else
2841 break;
2842 }
2843 }
2844 }
2845 return true;
2846 }
2847
2848 /**
2849 * Interrupts all workers
2850 */
2851 private void interruptAll() {
2852 Thread current = Thread.currentThread();
2853 WorkQueue[] qs = queues;
2854 int n = (qs == null) ? 0 : qs.length;
2855 for (int i = 1; i < n; i += 2) {
2856 WorkQueue q; Thread o;
2857 if ((q = qs[i]) != null && (o = q.owner) != null && o != current) {
2858 try {
2859 o.interrupt();
2860 } catch (Throwable ignore) {
2861 }
2862 }
2863 }
2864 }
2865
2866 /**
2867 * Returns termination signal, constructing if necessary
2868 */
2869 private CountDownLatch terminationSignal() {
2870 CountDownLatch signal, s, u;
2871 if ((signal = termination) == null)
2872 signal = ((u = cmpExTerminationSignal(
2873 s = new CountDownLatch(1))) == null) ? s : u;
2874 return signal;
2875 }
2876
2877 // Exported methods
2878
2879 // Constructors
2880
2881 /**
2882 * Creates a {@code ForkJoinPool} with parallelism equal to {@link
2883 * java.lang.Runtime#availableProcessors}, using defaults for all
2884 * other parameters (see {@link #ForkJoinPool(int,
2885 * ForkJoinWorkerThreadFactory, UncaughtExceptionHandler, boolean,
2886 * int, int, int, Predicate, long, TimeUnit)}).
2887 */
2888 public ForkJoinPool() {
2889 this(Math.min(MAX_CAP, Runtime.getRuntime().availableProcessors()),
2890 defaultForkJoinWorkerThreadFactory, null, false,
2891 0, MAX_CAP, 1, null, DEFAULT_KEEPALIVE, TimeUnit.MILLISECONDS);
2892 }
2893
2894 /**
2895 * Creates a {@code ForkJoinPool} with the indicated parallelism
2896 * level, using defaults for all other parameters (see {@link
2897 * #ForkJoinPool(int, ForkJoinWorkerThreadFactory,
2898 * UncaughtExceptionHandler, boolean, int, int, int, Predicate,
2899 * long, TimeUnit)}).
2900 *
2901 * @param parallelism the parallelism level
2902 * @throws IllegalArgumentException if parallelism less than or
2903 * equal to zero, or greater than implementation limit
2904 */
2905 public ForkJoinPool(int parallelism) {
2906 this(parallelism, defaultForkJoinWorkerThreadFactory, null, false,
2907 0, MAX_CAP, 1, null, DEFAULT_KEEPALIVE, TimeUnit.MILLISECONDS);
2908 }
2909
2910 /**
2911 * Creates a {@code ForkJoinPool} with the given parameters (using
2912 * defaults for others -- see {@link #ForkJoinPool(int,
2913 * ForkJoinWorkerThreadFactory, UncaughtExceptionHandler, boolean,
2914 * int, int, int, Predicate, long, TimeUnit)}).
2915 *
2916 * @param parallelism the parallelism level. For default value,
2917 * use {@link java.lang.Runtime#availableProcessors}.
2918 * @param factory the factory for creating new threads. For default value,
2919 * use {@link #defaultForkJoinWorkerThreadFactory}.
2920 * @param handler the handler for internal worker threads that
2921 * terminate due to unrecoverable errors encountered while executing
2922 * tasks. For default value, use {@code null}.
2923 * @param asyncMode if true,
2924 * establishes local first-in-first-out scheduling mode for forked
2925 * tasks that are never joined. This mode may be more appropriate
2926 * than default locally stack-based mode in applications in which
2927 * worker threads only process event-style asynchronous tasks.
2928 * For default value, use {@code false}.
2929 * @throws IllegalArgumentException if parallelism less than or
2930 * equal to zero, or greater than implementation limit
2931 * @throws NullPointerException if the factory is null
2932 */
2933 public ForkJoinPool(int parallelism,
2934 ForkJoinWorkerThreadFactory factory,
2935 UncaughtExceptionHandler handler,
2936 boolean asyncMode) {
2937 this(parallelism, factory, handler, asyncMode,
2938 0, MAX_CAP, 1, null, DEFAULT_KEEPALIVE, TimeUnit.MILLISECONDS);
2939 }
2940
2941 /**
2942 * Creates a {@code ForkJoinPool} with the given parameters.
2943 *
2944 * @param parallelism the parallelism level. For default value,
2945 * use {@link java.lang.Runtime#availableProcessors}.
2946 *
2947 * @param factory the factory for creating new threads. For
2948 * default value, use {@link #defaultForkJoinWorkerThreadFactory}.
2949 *
2950 * @param handler the handler for internal worker threads that
2951 * terminate due to unrecoverable errors encountered while
2952 * executing tasks. For default value, use {@code null}.
2953 *
2954 * @param asyncMode if true, establishes local first-in-first-out
2955 * scheduling mode for forked tasks that are never joined. This
2956 * mode may be more appropriate than default locally stack-based
2957 * mode in applications in which worker threads only process
2958 * event-style asynchronous tasks. For default value, use {@code
2959 * false}.
2960 *
2961 * @param corePoolSize ignored: used in previous releases of this
2962 * class but no longer applicable. Using {@code 0} maintains
2963 * compatibility across releases.
2964 *
2965 * @param maximumPoolSize the maximum number of threads allowed.
2966 * When the maximum is reached, attempts to replace blocked
2967 * threads fail. (However, because creation and termination of
2968 * different threads may overlap, and may be managed by the given
2969 * thread factory, this value may be transiently exceeded.) To
2970 * arrange the same value as is used by default for the common
2971 * pool, use {@code 256} plus the {@code parallelism} level. (By
2972 * default, the common pool allows a maximum of 256 spare
2973 * threads.) Using a value (for example {@code
2974 * Integer.MAX_VALUE}) larger than the implementation's total
2975 * thread limit has the same effect as using this limit (which is
2976 * the default).
2977 *
2978 * @param minimumRunnable the minimum allowed number of core
2979 * threads not blocked by a join or {@link ManagedBlocker}. To
2980 * ensure progress, when too few unblocked threads exist and
2981 * unexecuted tasks may exist, new threads are constructed, up to
2982 * the given maximumPoolSize. For the default value, use {@code
2983 * 1}, that ensures liveness. A larger value might improve
2984 * throughput in the presence of blocked activities, but might
2985 * not, due to increased overhead. A value of zero may be
2986 * acceptable when submitted tasks cannot have dependencies
2987 * requiring additional threads.
2988 *
2989 * @param saturate if non-null, a predicate invoked upon attempts
2990 * to create more than the maximum total allowed threads. By
2991 * default, when a thread is about to block on a join or {@link
2992 * ManagedBlocker}, but cannot be replaced because the
2993 * maximumPoolSize would be exceeded, a {@link
2994 * RejectedExecutionException} is thrown. But if this predicate
2995 * returns {@code true}, then no exception is thrown, so the pool
2996 * continues to operate with fewer than the target number of
2997 * runnable threads, which might not ensure progress.
2998 *
2999 * @param keepAliveTime the elapsed time since last use before
3000 * a thread is terminated (and then later replaced if needed).
3001 * For the default value, use {@code 60, TimeUnit.SECONDS}.
3002 *
3003 * @param unit the time unit for the {@code keepAliveTime} argument
3004 *
3005 * @throws IllegalArgumentException if parallelism is less than or
3006 * equal to zero, or is greater than implementation limit,
3007 * or if maximumPoolSize is less than parallelism,
3008 * of if the keepAliveTime is less than or equal to zero.
3009 * @throws NullPointerException if the factory is null
3010 * @since 9
3011 */
3012 public ForkJoinPool(int parallelism,
3013 ForkJoinWorkerThreadFactory factory,
3014 UncaughtExceptionHandler handler,
3015 boolean asyncMode,
3016 int corePoolSize,
3017 int maximumPoolSize,
3018 int minimumRunnable,
3019 Predicate<? super ForkJoinPool> saturate,
3020 long keepAliveTime,
3021 TimeUnit unit) {
3022 int p = parallelism;
3023 if (p <= 0 || p > MAX_CAP || p > maximumPoolSize || keepAliveTime <= 0L)
3024 throw new IllegalArgumentException();
3025 if (factory == null || unit == null)
3026 throw new NullPointerException();
3027 int size = Math.max(MIN_QUEUES_SIZE,
3028 1 << (33 - Integer.numberOfLeadingZeros(p - 1)));
3029 this.parallelism = p;
3030 this.factory = factory;
3031 this.ueh = handler;
3032 this.saturate = saturate;
3033 this.keepAlive = Math.max(unit.toMillis(keepAliveTime), TIMEOUT_SLOP);
3034 int maxSpares = Math.clamp(maximumPoolSize - p, 0, MAX_CAP);
3035 int minAvail = Math.clamp(minimumRunnable, 0, MAX_CAP);
3036 this.config = (((asyncMode ? FIFO : 0) & LMASK) |
3037 (((long)maxSpares) << TC_SHIFT) |
3038 (((long)minAvail) << RC_SHIFT));
3039 this.queues = new WorkQueue[size];
3040 String pid = Integer.toString(getAndAddPoolIds(1) + 1);
3041 String name = "ForkJoinPool-" + pid;
3042 this.poolName = name;
3043 this.workerNamePrefix = name + "-worker-";
3044 this.container = SharedThreadContainer.create(name);
3045 }
3046
3047 /**
3048 * Constructor for common pool using parameters possibly
3049 * overridden by system properties
3050 */
3051 private ForkJoinPool(byte forCommonPoolOnly) {
3052 String name = "ForkJoinPool.commonPool";
3053 ForkJoinWorkerThreadFactory fac = defaultForkJoinWorkerThreadFactory;
3054 UncaughtExceptionHandler handler = null;
3055 int maxSpares = DEFAULT_COMMON_MAX_SPARES;
3056 int pc = 0, preset = 0; // nonzero if size set as property
3057 try { // ignore exceptions in accessing/parsing properties
3058 String pp = System.getProperty
3059 ("java.util.concurrent.ForkJoinPool.common.parallelism");
3060 if (pp != null) {
3061 pc = Math.max(0, Integer.parseInt(pp));
3062 preset = PRESET_SIZE;
3063 }
3064 String ms = System.getProperty
3065 ("java.util.concurrent.ForkJoinPool.common.maximumSpares");
3066 if (ms != null)
3067 maxSpares = Math.clamp(Integer.parseInt(ms), 0, MAX_CAP);
3068 String sf = System.getProperty
3069 ("java.util.concurrent.ForkJoinPool.common.threadFactory");
3070 String sh = System.getProperty
3071 ("java.util.concurrent.ForkJoinPool.common.exceptionHandler");
3072 if (sf != null || sh != null) {
3073 ClassLoader ldr = ClassLoader.getSystemClassLoader();
3074 if (sf != null)
3075 fac = (ForkJoinWorkerThreadFactory)
3076 ldr.loadClass(sf).getConstructor().newInstance();
3077 if (sh != null)
3078 handler = (UncaughtExceptionHandler)
3079 ldr.loadClass(sh).getConstructor().newInstance();
3080 }
3081 } catch (Exception ignore) {
3082 }
3083 if (preset == 0)
3084 pc = Math.max(1, Runtime.getRuntime().availableProcessors() - 1);
3085 int p = Math.min(pc, MAX_CAP);
3086 int size = Math.max(MIN_QUEUES_SIZE,
3087 (p == 0) ? 1 :
3088 1 << (33 - Integer.numberOfLeadingZeros(p-1)));
3089 this.parallelism = p;
3090 this.config = ((preset & LMASK) | (((long)maxSpares) << TC_SHIFT) |
3091 (1L << RC_SHIFT));
3092 this.factory = fac;
3093 this.ueh = handler;
3094 this.keepAlive = DEFAULT_KEEPALIVE;
3095 this.saturate = null;
3096 this.workerNamePrefix = null;
3097 this.poolName = name;
3098 this.queues = new WorkQueue[size];
3099 this.container = SharedThreadContainer.create(name);
3100 }
3101
3102 /**
3103 * Returns the common pool instance. This pool is statically
3104 * constructed; its run state is unaffected by attempts to {@link
3105 * #shutdown} or {@link #shutdownNow}. However this pool and any
3106 * ongoing processing are automatically terminated upon program
3107 * {@link System#exit}. Any program that relies on asynchronous
3108 * task processing to complete before program termination should
3109 * invoke {@code commonPool().}{@link #awaitQuiescence awaitQuiescence},
3110 * before exit.
3111 *
3112 * @return the common pool instance
3113 * @since 1.8
3114 */
3115 public static ForkJoinPool commonPool() {
3116 // assert common != null : "static init error";
3117 return common;
3118 }
3119
3120 /**
3121 * Package-private access to commonPool overriding zero parallelism
3122 */
3123 static ForkJoinPool asyncCommonPool() {
3124 ForkJoinPool cp; int p;
3125 if ((p = (cp = common).parallelism) == 0)
3126 U.compareAndSetInt(cp, PARALLELISM, 0, 2);
3127 return cp;
3128 }
3129
3130 // Execution methods
3131
3132 /**
3133 * Performs the given task, returning its result upon completion.
3134 * If the computation encounters an unchecked Exception or Error,
3135 * it is rethrown as the outcome of this invocation. Rethrown
3136 * exceptions behave in the same way as regular exceptions, but,
3137 * when possible, contain stack traces (as displayed for example
3138 * using {@code ex.printStackTrace()}) of both the current thread
3139 * as well as the thread actually encountering the exception;
3140 * minimally only the latter.
3141 *
3142 * @param task the task
3143 * @param <T> the type of the task's result
3144 * @return the task's result
3145 * @throws NullPointerException if the task is null
3146 * @throws RejectedExecutionException if the task cannot be
3147 * scheduled for execution
3148 */
3149 public <T> T invoke(ForkJoinTask<T> task) {
3150 poolSubmit(true, Objects.requireNonNull(task));
3151 try {
3152 return task.join();
3153 } catch (RuntimeException | Error unchecked) {
3154 throw unchecked;
3155 } catch (Exception checked) {
3156 throw new RuntimeException(checked);
3157 }
3158 }
3159
3160 /**
3161 * Arranges for (asynchronous) execution of the given task.
3162 *
3163 * @param task the task
3164 * @throws NullPointerException if the task is null
3165 * @throws RejectedExecutionException if the task cannot be
3166 * scheduled for execution
3167 */
3168 public void execute(ForkJoinTask<?> task) {
3169 poolSubmit(true, Objects.requireNonNull(task));
3170 }
3171
3172 // AbstractExecutorService methods
3173
3174 /**
3175 * @throws NullPointerException if the task is null
3176 * @throws RejectedExecutionException if the task cannot be
3177 * scheduled for execution
3178 */
3179 @Override
3180 @SuppressWarnings("unchecked")
3181 public void execute(Runnable task) {
3182 poolSubmit(true, (Objects.requireNonNull(task) instanceof ForkJoinTask<?>)
3183 ? (ForkJoinTask<Void>) task // avoid re-wrap
3184 : new ForkJoinTask.RunnableExecuteAction(task));
3185 }
3186
3187 /**
3188 * Submits a ForkJoinTask for execution.
3189 *
3190 * @implSpec
3191 * This method is equivalent to {@link #externalSubmit(ForkJoinTask)}
3192 * when called from a thread that is not in this pool.
3193 *
3194 * @param task the task to submit
3195 * @param <T> the type of the task's result
3196 * @return the task
3197 * @throws NullPointerException if the task is null
3198 * @throws RejectedExecutionException if the task cannot be
3199 * scheduled for execution
3200 */
3201 public <T> ForkJoinTask<T> submit(ForkJoinTask<T> task) {
3202 return poolSubmit(true, Objects.requireNonNull(task));
3203 }
3204
3205 /**
3206 * @throws NullPointerException if the task is null
3207 * @throws RejectedExecutionException if the task cannot be
3208 * scheduled for execution
3209 */
3210 @Override
3211 public <T> ForkJoinTask<T> submit(Callable<T> task) {
3212 Objects.requireNonNull(task);
3213 return poolSubmit(
3214 true,
3215 (Thread.currentThread() instanceof ForkJoinWorkerThread) ?
3216 new ForkJoinTask.AdaptedCallable<T>(task) :
3217 new ForkJoinTask.AdaptedInterruptibleCallable<T>(task));
3218 }
3219
3220 /**
3221 * @throws NullPointerException if the task is null
3222 * @throws RejectedExecutionException if the task cannot be
3223 * scheduled for execution
3224 */
3225 @Override
3226 public <T> ForkJoinTask<T> submit(Runnable task, T result) {
3227 Objects.requireNonNull(task);
3228 return poolSubmit(
3229 true,
3230 (Thread.currentThread() instanceof ForkJoinWorkerThread) ?
3231 new ForkJoinTask.AdaptedRunnable<T>(task, result) :
3232 new ForkJoinTask.AdaptedInterruptibleRunnable<T>(task, result));
3233 }
3234
3235 /**
3236 * @throws NullPointerException if the task is null
3237 * @throws RejectedExecutionException if the task cannot be
3238 * scheduled for execution
3239 */
3240 @Override
3241 @SuppressWarnings("unchecked")
3242 public ForkJoinTask<?> submit(Runnable task) {
3243 Objects.requireNonNull(task);
3244 return poolSubmit(
3245 true,
3246 (task instanceof ForkJoinTask<?>) ?
3247 (ForkJoinTask<Void>) task : // avoid re-wrap
3248 ((Thread.currentThread() instanceof ForkJoinWorkerThread) ?
3249 new ForkJoinTask.AdaptedRunnable<Void>(task, null) :
3250 new ForkJoinTask.AdaptedInterruptibleRunnable<Void>(task, null)));
3251 }
3252
3253 /**
3254 * Submits the given task as if submitted from a non-{@code ForkJoinTask}
3255 * client. The task is added to a scheduling queue for submissions to the
3256 * pool even when called from a thread in the pool.
3257 *
3258 * @implSpec
3259 * This method is equivalent to {@link #submit(ForkJoinTask)} when called
3260 * from a thread that is not in this pool.
3261 *
3262 * @return the task
3263 * @param task the task to submit
3264 * @param <T> the type of the task's result
3265 * @throws NullPointerException if the task is null
3266 * @throws RejectedExecutionException if the task cannot be
3267 * scheduled for execution
3268 * @since 20
3269 */
3270 public <T> ForkJoinTask<T> externalSubmit(ForkJoinTask<T> task) {
3271 Objects.requireNonNull(task);
3272 externalSubmissionQueue(true).push(task, this, false);
3273 return task;
3274 }
3275
3276 /**
3277 * Submits the given task without guaranteeing that it will
3278 * eventually execute in the absence of available active threads.
3279 * In some contexts, this method may reduce contention and
3280 * overhead by relying on context-specific knowledge that existing
3281 * threads (possibly including the calling thread if operating in
3282 * this pool) will eventually be available to execute the task.
3283 *
3284 * @param task the task
3285 * @param <T> the type of the task's result
3286 * @return the task
3287 * @throws NullPointerException if the task is null
3288 * @throws RejectedExecutionException if the task cannot be
3289 * scheduled for execution
3290 * @since 19
3291 */
3292 public <T> ForkJoinTask<T> lazySubmit(ForkJoinTask<T> task) {
3293 return poolSubmit(false, Objects.requireNonNull(task));
3294 }
3295
3296 /**
3297 * Changes the target parallelism of this pool, controlling the
3298 * future creation, use, and termination of worker threads.
3299 * Applications include contexts in which the number of available
3300 * processors changes over time.
3301 *
3302 * @implNote This implementation restricts the maximum number of
3303 * running threads to 32767
3304 *
3305 * @param size the target parallelism level
3306 * @return the previous parallelism level.
3307 * @throws IllegalArgumentException if size is less than 1 or
3308 * greater than the maximum supported by this pool.
3309 * @throws UnsupportedOperationException this is the{@link
3310 * #commonPool()} and parallelism level was set by System
3311 * property {@systemProperty
3312 * java.util.concurrent.ForkJoinPool.common.parallelism}.
3313 * @since 19
3314 */
3315 public int setParallelism(int size) {
3316 int prevSize;
3317 if (size < 1 || size > MAX_CAP)
3318 throw new IllegalArgumentException();
3319 if ((config & PRESET_SIZE) != 0)
3320 throw new UnsupportedOperationException("Cannot override System property");
3321 if ((prevSize = getAndSetParallelism(size)) < size)
3322 signalWork(null, 0); // trigger worker activation
3323 return prevSize;
3324 }
3325
3326 /**
3327 * Uninterrupible version of {@code invokeAll}. Executes the given
3328 * tasks, returning a list of Futures holding their status and
3329 * results when all complete, ignoring interrupts. {@link
3330 * Future#isDone} is {@code true} for each element of the returned
3331 * list. Note that a <em>completed</em> task could have
3332 * terminated either normally or by throwing an exception. The
3333 * results of this method are undefined if the given collection is
3334 * modified while this operation is in progress.
3335 *
3336 * @apiNote This method supports usages that previously relied on an
3337 * incompatible override of
3338 * {@link ExecutorService#invokeAll(java.util.Collection)}.
3339 *
3340 * @param tasks the collection of tasks
3341 * @param <T> the type of the values returned from the tasks
3342 * @return a list of Futures representing the tasks, in the same
3343 * sequential order as produced by the iterator for the
3344 * given task list, each of which has completed
3345 * @throws NullPointerException if tasks or any of its elements are {@code null}
3346 * @throws RejectedExecutionException if any task cannot be
3347 * scheduled for execution
3348 * @since 22
3349 */
3350 public <T> List<Future<T>> invokeAllUninterruptibly(Collection<? extends Callable<T>> tasks) {
3351 ArrayList<Future<T>> futures = new ArrayList<>(tasks.size());
3352 try {
3353 for (Callable<T> t : tasks) {
3354 ForkJoinTask<T> f = ForkJoinTask.adapt(t);
3355 futures.add(f);
3356 poolSubmit(true, f);
3357 }
3358 for (int i = futures.size() - 1; i >= 0; --i)
3359 ((ForkJoinTask<?>)futures.get(i)).quietlyJoin();
3360 return futures;
3361 } catch (Throwable t) {
3362 for (Future<T> e : futures)
3363 e.cancel(true);
3364 throw t;
3365 }
3366 }
3367
3368 /**
3369 * Common support for timed and untimed invokeAll
3370 */
3371 private <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks,
3372 long deadline)
3373 throws InterruptedException {
3374 ArrayList<Future<T>> futures = new ArrayList<>(tasks.size());
3375 try {
3376 for (Callable<T> t : tasks) {
3377 ForkJoinTask<T> f = ForkJoinTask.adaptInterruptible(t);
3378 futures.add(f);
3379 poolSubmit(true, f);
3380 }
3381 for (int i = futures.size() - 1; i >= 0; --i)
3382 ((ForkJoinTask<?>)futures.get(i))
3383 .quietlyJoinPoolInvokeAllTask(deadline);
3384 return futures;
3385 } catch (Throwable t) {
3386 for (Future<T> e : futures)
3387 e.cancel(true);
3388 throw t;
3389 }
3390 }
3391
3392 @Override
3393 public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
3394 throws InterruptedException {
3395 return invokeAll(tasks, 0L);
3396 }
3397 // for jdk version < 22, replace with
3398 // /**
3399 // * @throws NullPointerException {@inheritDoc}
3400 // * @throws RejectedExecutionException {@inheritDoc}
3401 // */
3402 // @Override
3403 // public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) {
3404 // return invokeAllUninterruptibly(tasks);
3405 // }
3406
3407 @Override
3408 public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks,
3409 long timeout, TimeUnit unit)
3410 throws InterruptedException {
3411 return invokeAll(tasks, (System.nanoTime() + unit.toNanos(timeout)) | 1L);
3412 }
3413
3414 @Override
3415 public <T> T invokeAny(Collection<? extends Callable<T>> tasks)
3416 throws InterruptedException, ExecutionException {
3417 try {
3418 return new ForkJoinTask.InvokeAnyRoot<T>()
3419 .invokeAny(tasks, this, false, 0L);
3420 } catch (TimeoutException cannotHappen) {
3421 assert false;
3422 return null;
3423 }
3424 }
3425
3426 @Override
3427 public <T> T invokeAny(Collection<? extends Callable<T>> tasks,
3428 long timeout, TimeUnit unit)
3429 throws InterruptedException, ExecutionException, TimeoutException {
3430 return new ForkJoinTask.InvokeAnyRoot<T>()
3431 .invokeAny(tasks, this, true, unit.toNanos(timeout));
3432 }
3433
3434 // Support for delayed tasks
3435
3436 /**
3437 * Returns STOP and SHUTDOWN status (zero if neither), masking or
3438 * truncating out other bits.
3439 */
3440 final int shutdownStatus(DelayScheduler ds) {
3441 return (int)(runState & (SHUTDOWN | STOP));
3442 }
3443
3444 /**
3445 * Tries to stop and possibly terminate if already enabled, return success.
3446 */
3447 final boolean tryStopIfShutdown(DelayScheduler ds) {
3448 return (tryTerminate(false, false) & STOP) != 0L;
3449 }
3450
3451 /**
3452 * Creates and starts DelayScheduler
3453 */
3454 private DelayScheduler startDelayScheduler() {
3455 DelayScheduler ds;
3456 if ((ds = delayScheduler) == null) {
3457 boolean start = false;
3458 String name = poolName + "-delayScheduler";
3459 if (workerNamePrefix == null)
3460 asyncCommonPool(); // override common parallelism zero
3461 long isShutdown = lockRunState() & SHUTDOWN;
3462 try {
3463 if (isShutdown == 0L && (ds = delayScheduler) == null) {
3464 ds = delayScheduler = new DelayScheduler(this, name);
3465 start = true;
3466 }
3467 } finally {
3468 unlockRunState();
3469 }
3470 if (start) { // start outside of lock
3471 SharedThreadContainer ctr;
3472 try {
3473 if ((ctr = container) != null)
3474 ctr.start(ds);
3475 else
3476 ds.start();
3477 } catch (RuntimeException | Error ex) { // back out
3478 lockRunState();
3479 ds = delayScheduler = null;
3480 unlockRunState();
3481 tryTerminate(false, false);
3482 if (ex instanceof Error)
3483 throw ex;
3484 }
3485 }
3486 }
3487 return ds;
3488 }
3489
3490 /**
3491 * Arranges execution of a ScheduledForkJoinTask whose delay has
3492 * elapsed
3493 */
3494 final void executeEnabledScheduledTask(ScheduledForkJoinTask<?> task) {
3495 externalSubmissionQueue(false).push(task, this, false);
3496 }
3497
3498 /**
3499 * Arranges delayed execution of a ScheduledForkJoinTask via the
3500 * DelayScheduler, creating and starting it if necessary.
3501 * @return the task
3502 */
3503 final <T> ScheduledForkJoinTask<T> scheduleDelayedTask(ScheduledForkJoinTask<T> task) {
3504 DelayScheduler ds;
3505 if (((ds = delayScheduler) == null &&
3506 (ds = startDelayScheduler()) == null) ||
3507 (runState & SHUTDOWN) != 0L)
3508 throw new RejectedExecutionException();
3509 ds.pend(task);
3510 return task;
3511 }
3512
3513 /**
3514 * Submits a one-shot task that becomes enabled for execution after the given
3515 * delay. At that point it will execute unless explicitly
3516 * cancelled, or fail to execute (eventually reporting
3517 * cancellation) when encountering resource exhaustion, or the
3518 * pool is {@link #shutdownNow}, or is {@link #shutdown} when
3519 * otherwise quiescent and {@link #cancelDelayedTasksOnShutdown}
3520 * is in effect.
3521 *
3522 * @param command the task to execute
3523 * @param delay the time from now to delay execution
3524 * @param unit the time unit of the delay parameter
3525 * @return a ForkJoinTask implementing the ScheduledFuture
3526 * interface, whose {@code get()} method will return
3527 * {@code null} upon normal completion.
3528 * @throws RejectedExecutionException if the pool is shutdown or
3529 * submission encounters resource exhaustion.
3530 * @throws NullPointerException if command or unit is null
3531 * @since 25
3532 */
3533 public ScheduledFuture<?> schedule(Runnable command,
3534 long delay, TimeUnit unit) {
3535 return scheduleDelayedTask(
3536 new ScheduledForkJoinTask<Void>(
3537 unit.toNanos(delay), 0L, false, // implicit null check of unit
3538 Objects.requireNonNull(command), null, this));
3539 }
3540
3541 /**
3542 * Submits a value-returning one-shot task that becomes enabled for execution
3543 * after the given delay. At that point it will execute unless
3544 * explicitly cancelled, or fail to execute (eventually reporting
3545 * cancellation) when encountering resource exhaustion, or the
3546 * pool is {@link #shutdownNow}, or is {@link #shutdown} when
3547 * otherwise quiescent and {@link #cancelDelayedTasksOnShutdown}
3548 * is in effect.
3549 *
3550 * @param callable the function to execute
3551 * @param delay the time from now to delay execution
3552 * @param unit the time unit of the delay parameter
3553 * @param <V> the type of the callable's result
3554 * @return a ForkJoinTask implementing the ScheduledFuture
3555 * interface, whose {@code get()} method will return the
3556 * value from the callable upon normal completion.
3557 * @throws RejectedExecutionException if the pool is shutdown or
3558 * submission encounters resource exhaustion.
3559 * @throws NullPointerException if command or unit is null
3560 * @since 25
3561 */
3562 public <V> ScheduledFuture<V> schedule(Callable<V> callable,
3563 long delay, TimeUnit unit) {
3564 return scheduleDelayedTask(
3565 new ScheduledForkJoinTask<V>(
3566 unit.toNanos(delay), 0L, false, null, // implicit null check of unit
3567 Objects.requireNonNull(callable), this));
3568 }
3569
3570 /**
3571 * Submits a periodic action that becomes enabled for execution first after the
3572 * given initial delay, and subsequently with the given period;
3573 * that is, executions will commence after
3574 * {@code initialDelay}, then {@code initialDelay + period}, then
3575 * {@code initialDelay + 2 * period}, and so on.
3576 *
3577 * <p>The sequence of task executions continues indefinitely until
3578 * one of the following exceptional completions occur:
3579 * <ul>
3580 * <li>The task is {@linkplain Future#cancel explicitly cancelled}
3581 * <li>Method {@link #shutdownNow} is called
3582 * <li>Method {@link #shutdown} is called and the pool is
3583 * otherwise quiescent, in which case existing executions continue
3584 * but subsequent executions do not.
3585 * <li>An execution or the task encounters resource exhaustion.
3586 * <li>An execution of the task throws an exception. In this case
3587 * calling {@link Future#get() get} on the returned future will throw
3588 * {@link ExecutionException}, holding the exception as its cause.
3589 * </ul>
3590 * Subsequent executions are suppressed. Subsequent calls to
3591 * {@link Future#isDone isDone()} on the returned future will
3592 * return {@code true}.
3593 *
3594 * <p>If any execution of this task takes longer than its period, then
3595 * subsequent executions may start late, but will not concurrently
3596 * execute.
3597 * @param command the task to execute
3598 * @param initialDelay the time to delay first execution
3599 * @param period the period between successive executions
3600 * @param unit the time unit of the initialDelay and period parameters
3601 * @return a ForkJoinTask implementing the ScheduledFuture
3602 * interface. The future's {@link Future#get() get()}
3603 * method will never return normally, and will throw an
3604 * exception upon task cancellation or abnormal
3605 * termination of a task execution.
3606 * @throws RejectedExecutionException if the pool is shutdown or
3607 * submission encounters resource exhaustion.
3608 * @throws NullPointerException if command or unit is null
3609 * @throws IllegalArgumentException if period less than or equal to zero
3610 * @since 25
3611 */
3612 public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,
3613 long initialDelay,
3614 long period, TimeUnit unit) {
3615 if (period <= 0L)
3616 throw new IllegalArgumentException();
3617 return scheduleDelayedTask(
3618 new ScheduledForkJoinTask<Void>(
3619 unit.toNanos(initialDelay), // implicit null check of unit
3620 unit.toNanos(period), false,
3621 Objects.requireNonNull(command), null, this));
3622 }
3623
3624 /**
3625 * Submits a periodic action that becomes enabled for execution first after the
3626 * given initial delay, and subsequently with the given delay
3627 * between the termination of one execution and the commencement of
3628 * the next.
3629 * <p>The sequence of task executions continues indefinitely until
3630 * one of the following exceptional completions occur:
3631 * <ul>
3632 * <li>The task is {@linkplain Future#cancel explicitly cancelled}
3633 * <li>Method {@link #shutdownNow} is called
3634 * <li>Method {@link #shutdown} is called and the pool is
3635 * otherwise quiescent, in which case existing executions continue
3636 * but subsequent executions do not.
3637 * <li>An execution or the task encounters resource exhaustion.
3638 * <li>An execution of the task throws an exception. In this case
3639 * calling {@link Future#get() get} on the returned future will throw
3640 * {@link ExecutionException}, holding the exception as its cause.
3641 * </ul>
3642 * Subsequent executions are suppressed. Subsequent calls to
3643 * {@link Future#isDone isDone()} on the returned future will
3644 * return {@code true}.
3645 * @param command the task to execute
3646 * @param initialDelay the time to delay first execution
3647 * @param delay the delay between the termination of one
3648 * execution and the commencement of the next
3649 * @param unit the time unit of the initialDelay and delay parameters
3650 * @return a ForkJoinTask implementing the ScheduledFuture
3651 * interface. The future's {@link Future#get() get()}
3652 * method will never return normally, and will throw an
3653 * exception upon task cancellation or abnormal
3654 * termination of a task execution.
3655 * @throws RejectedExecutionException if the pool is shutdown or
3656 * submission encounters resource exhaustion.
3657 * @throws NullPointerException if command or unit is null
3658 * @throws IllegalArgumentException if delay less than or equal to zero
3659 * @since 25
3660 */
3661 public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,
3662 long initialDelay,
3663 long delay, TimeUnit unit) {
3664 if (delay <= 0L)
3665 throw new IllegalArgumentException();
3666 return scheduleDelayedTask(
3667 new ScheduledForkJoinTask<Void>(
3668 unit.toNanos(initialDelay), // implicit null check of unit
3669 -unit.toNanos(delay), false, // negative for fixed delay
3670 Objects.requireNonNull(command), null, this));
3671 }
3672
3673 /**
3674 * Body of a task performed on timeout of another task
3675 */
3676 static final class TimeoutAction<V> implements Runnable {
3677 // set after construction, nulled after use
3678 ForkJoinTask.CallableWithTimeout<V> task;
3679 Consumer<? super ForkJoinTask<V>> action;
3680 TimeoutAction(Consumer<? super ForkJoinTask<V>> action) {
3681 this.action = action;
3682 }
3683 public void run() {
3684 ForkJoinTask.CallableWithTimeout<V> t = task;
3685 Consumer<? super ForkJoinTask<V>> a = action;
3686 task = null;
3687 action = null;
3688 if (t != null && t.status >= 0) {
3689 if (a == null)
3690 t.cancel(true);
3691 else {
3692 a.accept(t);
3693 t.interruptIfRunning(true);
3694 }
3695 }
3696 }
3697 }
3698
3699 /**
3700 * Submits a task executing the given function, cancelling the
3701 * task or performing a given timeoutAction if not completed
3702 * within the given timeout period. If the optional {@code
3703 * timeoutAction} is null, the task is cancelled (via {@code
3704 * cancel(true)}. Otherwise, the action is applied and the task
3705 * may be interrupted if running. Actions may include {@link
3706 * ForkJoinTask#complete} to set a replacement value or {@link
3707 * ForkJoinTask#completeExceptionally} to throw an appropriate
3708 * exception. Note that these can succeed only if the task has
3709 * not already completed when the timeoutAction executes.
3710 *
3711 * @param callable the function to execute
3712 * @param <V> the type of the callable's result
3713 * @param timeout the time to wait before cancelling if not completed
3714 * @param timeoutAction if nonnull, an action to perform on
3715 * timeout, otherwise the default action is to cancel using
3716 * {@code cancel(true)}.
3717 * @param unit the time unit of the timeout parameter
3718 * @return a Future that can be used to extract result or cancel
3719 * @throws RejectedExecutionException if the task cannot be
3720 * scheduled for execution
3721 * @throws NullPointerException if callable or unit is null
3722 * @since 25
3723 */
3724 public <V> ForkJoinTask<V> submitWithTimeout(Callable<V> callable,
3725 long timeout, TimeUnit unit,
3726 Consumer<? super ForkJoinTask<V>> timeoutAction) {
3727 ForkJoinTask.CallableWithTimeout<V> task; TimeoutAction<V> onTimeout;
3728 Objects.requireNonNull(callable);
3729 ScheduledForkJoinTask<Void> timeoutTask =
3730 new ScheduledForkJoinTask<Void>(
3731 unit.toNanos(timeout), 0L, true,
3732 onTimeout = new TimeoutAction<V>(timeoutAction), null, this);
3733 onTimeout.task = task =
3734 new ForkJoinTask.CallableWithTimeout<V>(callable, timeoutTask);
3735 scheduleDelayedTask(timeoutTask);
3736 return poolSubmit(true, task);
3737 }
3738
3739 /**
3740 * Arranges that scheduled tasks that are not executing and have
3741 * not already been enabled for execution will not be executed and
3742 * will be cancelled upon {@link #shutdown} (unless this pool is
3743 * the {@link #commonPool()} which never shuts down). This method
3744 * may be invoked either before {@link #shutdown} to take effect
3745 * upon the next call, or afterwards to cancel such tasks, which
3746 * may then allow termination. Note that subsequent executions of
3747 * periodic tasks are always disabled upon shutdown, so this
3748 * method applies meaningfully only to non-periodic tasks.
3749 * @since 25
3750 */
3751 public void cancelDelayedTasksOnShutdown() {
3752 DelayScheduler ds;
3753 if ((ds = delayScheduler) != null ||
3754 (ds = startDelayScheduler()) != null)
3755 ds.cancelDelayedTasksOnShutdown();
3756 }
3757
3758 /**
3759 * Returns the factory used for constructing new workers.
3760 *
3761 * @return the factory used for constructing new workers
3762 */
3763 public ForkJoinWorkerThreadFactory getFactory() {
3764 return factory;
3765 }
3766
3767 /**
3768 * Returns the handler for internal worker threads that terminate
3769 * due to unrecoverable errors encountered while executing tasks.
3770 *
3771 * @return the handler, or {@code null} if none
3772 */
3773 public UncaughtExceptionHandler getUncaughtExceptionHandler() {
3774 return ueh;
3775 }
3776
3777 /**
3778 * Returns the targeted parallelism level of this pool.
3779 *
3780 * @return the targeted parallelism level of this pool
3781 */
3782 public int getParallelism() {
3783 return Math.max(getParallelismOpaque(), 1);
3784 }
3785
3786 /**
3787 * Returns the targeted parallelism level of the common pool.
3788 *
3789 * @return the targeted parallelism level of the common pool
3790 * @since 1.8
3791 */
3792 public static int getCommonPoolParallelism() {
3793 return common.getParallelism();
3794 }
3795
3796 /**
3797 * Returns the number of worker threads that have started but not
3798 * yet terminated. The result returned by this method may differ
3799 * from {@link #getParallelism} when threads are created to
3800 * maintain parallelism when others are cooperatively blocked.
3801 *
3802 * @return the number of worker threads
3803 */
3804 public int getPoolSize() {
3805 return (short)(ctl >>> TC_SHIFT);
3806 }
3807
3808 /**
3809 * Returns {@code true} if this pool uses local first-in-first-out
3810 * scheduling mode for forked tasks that are never joined.
3811 *
3812 * @return {@code true} if this pool uses async mode
3813 */
3814 public boolean getAsyncMode() {
3815 return (config & FIFO) != 0;
3816 }
3817
3818 /**
3819 * Returns an estimate of the number of worker threads that are
3820 * not blocked waiting to join tasks or for other managed
3821 * synchronization. This method may overestimate the
3822 * number of running threads.
3823 *
3824 * @return the number of worker threads
3825 */
3826 public int getRunningThreadCount() {
3827 WorkQueue[] qs; WorkQueue q;
3828 int rc = 0;
3829 if ((runState & TERMINATED) == 0L && (qs = queues) != null) {
3830 for (int i = 1; i < qs.length; i += 2) {
3831 if ((q = qs[i]) != null && q.isApparentlyUnblocked())
3832 ++rc;
3833 }
3834 }
3835 return rc;
3836 }
3837
3838 /**
3839 * Returns an estimate of the number of threads that are currently
3840 * stealing or executing tasks. This method may overestimate the
3841 * number of active threads.
3842 *
3843 * @return the number of active threads
3844 */
3845 public int getActiveThreadCount() {
3846 return Math.max((short)(ctl >>> RC_SHIFT), 0);
3847 }
3848
3849 /**
3850 * Returns {@code true} if all worker threads are currently idle.
3851 * An idle worker is one that cannot obtain a task to execute
3852 * because none are available to steal from other threads, and
3853 * there are no pending submissions to the pool. This method is
3854 * conservative; it might not return {@code true} immediately upon
3855 * idleness of all threads, but will eventually become true if
3856 * threads remain inactive.
3857 *
3858 * @return {@code true} if all threads are currently idle
3859 */
3860 public boolean isQuiescent() {
3861 return quiescent() >= 0;
3862 }
3863
3864 /**
3865 * Returns an estimate of the total number of completed tasks that
3866 * were executed by a thread other than their submitter. The
3867 * reported value underestimates the actual total number of steals
3868 * when the pool is not quiescent. This value may be useful for
3869 * monitoring and tuning fork/join programs: in general, steal
3870 * counts should be high enough to keep threads busy, but low
3871 * enough to avoid overhead and contention across threads.
3872 *
3873 * @return the number of steals
3874 */
3875 public long getStealCount() {
3876 long count = stealCount;
3877 WorkQueue[] qs; WorkQueue q;
3878 if ((qs = queues) != null) {
3879 for (int i = 1; i < qs.length; i += 2) {
3880 if ((q = qs[i]) != null)
3881 count += (long)q.nsteals & 0xffffffffL;
3882 }
3883 }
3884 return count;
3885 }
3886
3887 /**
3888 * Returns an estimate of the total number of tasks currently held
3889 * in queues by worker threads (but not including tasks submitted
3890 * to the pool that have not begun executing). This value is only
3891 * an approximation, obtained by iterating across all threads in
3892 * the pool. This method may be useful for tuning task
3893 * granularities.The returned count does not include scheduled
3894 * tasks that are not yet ready to execute, which are reported
3895 * separately by method {@link getDelayedTaskCount}.
3896 *
3897 * @return the number of queued tasks
3898 * @see ForkJoinWorkerThread#getQueuedTaskCount()
3899 */
3900 public long getQueuedTaskCount() {
3901 WorkQueue[] qs; WorkQueue q;
3902 long count = 0;
3903 if ((runState & TERMINATED) == 0L && (qs = queues) != null) {
3904 for (int i = 1; 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 tasks submitted to this
3914 * pool that have not yet begun executing. This method may take
3915 * time proportional to the number of submissions.
3916 *
3917 * @return the number of queued submissions
3918 */
3919 public int getQueuedSubmissionCount() {
3920 WorkQueue[] qs; WorkQueue q;
3921 int count = 0;
3922 if ((runState & TERMINATED) == 0L && (qs = queues) != null) {
3923 for (int i = 0; i < qs.length; i += 2) {
3924 if ((q = qs[i]) != null)
3925 count += q.queueSize();
3926 }
3927 }
3928 return count;
3929 }
3930
3931 /**
3932 * Returns an estimate of the number of delayed (including
3933 * periodic) tasks scheduled in this pool that are not yet ready
3934 * to submit for execution. The returned value is inaccurate while
3935 * delayed tasks are being processed.
3936 *
3937 * @return an estimate of the number of delayed tasks
3938 * @since 25
3939 */
3940 public long getDelayedTaskCount() {
3941 DelayScheduler ds;
3942 return ((ds = delayScheduler) == null ? 0 : ds.lastStableSize());
3943 }
3944
3945 /**
3946 * Returns {@code true} if there are any tasks submitted to this
3947 * pool that have not yet begun executing.
3948 *
3949 * @return {@code true} if there are any queued submissions
3950 */
3951 public boolean hasQueuedSubmissions() {
3952 WorkQueue[] qs; WorkQueue q;
3953 if ((runState & STOP) == 0L && (qs = queues) != null) {
3954 for (int i = 0; i < qs.length; i += 2) {
3955 if ((q = qs[i]) != null && q.queueSize() > 0)
3956 return true;
3957 }
3958 }
3959 return false;
3960 }
3961
3962 /**
3963 * Removes and returns the next unexecuted submission if one is
3964 * available. This method may be useful in extensions to this
3965 * class that re-assign work in systems with multiple pools.
3966 *
3967 * @return the next submission, or {@code null} if none
3968 */
3969 protected ForkJoinTask<?> pollSubmission() {
3970 return pollScan(true);
3971 }
3972
3973 /**
3974 * Removes all available unexecuted submitted and forked tasks
3975 * from scheduling queues and adds them to the given collection,
3976 * without altering their execution status. These may include
3977 * artificially generated or wrapped tasks. This method is
3978 * designed to be invoked only when the pool is known to be
3979 * quiescent. Invocations at other times may not remove all
3980 * tasks. A failure encountered while attempting to add elements
3981 * to collection {@code c} may result in elements being in
3982 * neither, either or both collections when the associated
3983 * exception is thrown. The behavior of this operation is
3984 * undefined if the specified collection is modified while the
3985 * operation is in progress.
3986 *
3987 * @param c the collection to transfer elements into
3988 * @return the number of elements transferred
3989 */
3990 protected int drainTasksTo(Collection<? super ForkJoinTask<?>> c) {
3991 int count = 0;
3992 for (ForkJoinTask<?> t; (t = pollScan(false)) != null; ) {
3993 c.add(t);
3994 ++count;
3995 }
3996 return count;
3997 }
3998
3999 /**
4000 * Returns a string identifying this pool, as well as its state,
4001 * including indications of run state, parallelism level, and
4002 * worker and task counts.
4003 *
4004 * @return a string identifying this pool, as well as its state
4005 */
4006 public String toString() {
4007 // Use a single pass through queues to collect counts
4008 DelayScheduler ds;
4009 long e = runState;
4010 long st = stealCount;
4011 long qt = 0L, ss = 0L; int rc = 0;
4012 WorkQueue[] qs; WorkQueue q;
4013 if ((qs = queues) != null) {
4014 for (int i = 0; i < qs.length; ++i) {
4015 if ((q = qs[i]) != null) {
4016 int size = q.queueSize();
4017 if ((i & 1) == 0)
4018 ss += size;
4019 else {
4020 qt += size;
4021 st += (long)q.nsteals & 0xffffffffL;
4022 if (q.isApparentlyUnblocked())
4023 ++rc;
4024 }
4025 }
4026 }
4027 }
4028 String delayed = ((ds = delayScheduler) == null ? "" :
4029 ", delayed = " + ds.lastStableSize());
4030 int pc = parallelism;
4031 long c = ctl;
4032 int tc = (short)(c >>> TC_SHIFT);
4033 int ac = (short)(c >>> RC_SHIFT);
4034 if (ac < 0) // ignore transient negative
4035 ac = 0;
4036 String level = ((e & TERMINATED) != 0L ? "Terminated" :
4037 (e & STOP) != 0L ? "Terminating" :
4038 (e & SHUTDOWN) != 0L ? "Shutting down" :
4039 "Running");
4040 return super.toString() +
4041 "[" + level +
4042 ", parallelism = " + pc +
4043 ", size = " + tc +
4044 ", active = " + ac +
4045 ", running = " + rc +
4046 ", steals = " + st +
4047 ", tasks = " + qt +
4048 ", submissions = " + ss +
4049 delayed +
4050 "]";
4051 }
4052
4053 /**
4054 * Possibly initiates an orderly shutdown in which previously
4055 * submitted tasks are executed, but no new tasks will be
4056 * accepted. Invocation has no effect on execution state if this
4057 * is the {@link #commonPool()}, and no additional effect if
4058 * already shut down. Tasks that are in the process of being
4059 * submitted concurrently during the course of this method may or
4060 * may not be rejected.
4061 */
4062 public void shutdown() {
4063 if (workerNamePrefix != null) // not common pool
4064 tryTerminate(false, true);
4065 }
4066
4067 /**
4068 * Possibly attempts to cancel and/or stop all tasks, and reject
4069 * all subsequently submitted tasks. Invocation has no effect on
4070 * execution state if this is the {@link #commonPool()}, and no
4071 * additional effect if already shut down. Otherwise, tasks that
4072 * are in the process of being submitted or executed concurrently
4073 * during the course of this method may or may not be
4074 * rejected. This method cancels both existing and unexecuted
4075 * tasks, in order to permit termination in the presence of task
4076 * dependencies. So the method always returns an empty list
4077 * (unlike the case for some other Executors).
4078 *
4079 * @return an empty list
4080 */
4081 public List<Runnable> shutdownNow() {
4082 if (workerNamePrefix != null) // not common pool
4083 tryTerminate(true, true);
4084 return Collections.emptyList();
4085 }
4086
4087 /**
4088 * Returns {@code true} if all tasks have completed following shut down.
4089 *
4090 * @return {@code true} if all tasks have completed following shut down
4091 */
4092 public boolean isTerminated() {
4093 return (tryTerminate(false, false) & TERMINATED) != 0;
4094 }
4095
4096 /**
4097 * Returns {@code true} if the process of termination has
4098 * commenced but not yet completed. This method may be useful for
4099 * debugging. A return of {@code true} reported a sufficient
4100 * period after shutdown may indicate that submitted tasks have
4101 * ignored or suppressed interruption, or are waiting for I/O,
4102 * causing this executor not to properly terminate. (See the
4103 * advisory notes for class {@link ForkJoinTask} stating that
4104 * tasks should not normally entail blocking operations. But if
4105 * they do, they must abort them on interrupt.)
4106 *
4107 * @return {@code true} if terminating but not yet terminated
4108 */
4109 public boolean isTerminating() {
4110 return (tryTerminate(false, false) & (STOP | TERMINATED)) == STOP;
4111 }
4112
4113 /**
4114 * Returns {@code true} if this pool has been shut down.
4115 *
4116 * @return {@code true} if this pool has been shut down
4117 */
4118 public boolean isShutdown() {
4119 return (runState & SHUTDOWN) != 0L;
4120 }
4121
4122 /**
4123 * Blocks until all tasks have completed execution after a
4124 * shutdown request, or the timeout occurs, or the current thread
4125 * is interrupted, whichever happens first. Because the {@link
4126 * #commonPool()} never terminates until program shutdown, when
4127 * applied to the common pool, this method is equivalent to {@link
4128 * #awaitQuiescence(long, TimeUnit)} but always returns {@code false}.
4129 *
4130 * @param timeout the maximum time to wait
4131 * @param unit the time unit of the timeout argument
4132 * @return {@code true} if this executor terminated and
4133 * {@code false} if the timeout elapsed before termination
4134 * @throws InterruptedException if interrupted while waiting
4135 */
4136 public boolean awaitTermination(long timeout, TimeUnit unit)
4137 throws InterruptedException {
4138 long nanos = unit.toNanos(timeout);
4139 CountDownLatch done;
4140 if (workerNamePrefix == null) { // is common pool
4141 if (helpQuiescePool(this, nanos, true) < 0)
4142 throw new InterruptedException();
4143 return false;
4144 }
4145 else if ((tryTerminate(false, false) & TERMINATED) != 0 ||
4146 (done = terminationSignal()) == null ||
4147 (runState & TERMINATED) != 0L)
4148 return true;
4149 else
4150 return done.await(nanos, TimeUnit.NANOSECONDS);
4151 }
4152
4153 /**
4154 * If called by a ForkJoinTask operating in this pool, equivalent
4155 * in effect to {@link ForkJoinTask#helpQuiesce}. Otherwise,
4156 * waits and/or attempts to assist performing tasks until this
4157 * pool {@link #isQuiescent} or the indicated timeout elapses.
4158 *
4159 * @param timeout the maximum time to wait
4160 * @param unit the time unit of the timeout argument
4161 * @return {@code true} if quiescent; {@code false} if the
4162 * timeout elapsed.
4163 */
4164 public boolean awaitQuiescence(long timeout, TimeUnit unit) {
4165 return (helpQuiescePool(this, unit.toNanos(timeout), false) > 0);
4166 }
4167
4168 /**
4169 * Unless this is the {@link #commonPool()}, initiates an orderly
4170 * shutdown in which previously submitted tasks are executed, but
4171 * no new tasks will be accepted, and waits until all tasks have
4172 * completed execution and the executor has terminated.
4173 *
4174 * <p> If already terminated, or this is the {@link
4175 * #commonPool()}, this method has no effect on execution, and
4176 * does not wait. Otherwise, if interrupted while waiting, this
4177 * method stops all executing tasks as if by invoking {@link
4178 * #shutdownNow()}. It then continues to wait until all actively
4179 * executing tasks have completed. Tasks that were awaiting
4180 * execution are not executed. The interrupted status will be
4181 * re-asserted before this method returns.
4182 *
4183 * @since 19
4184 */
4185 @Override
4186 public void close() {
4187 if (workerNamePrefix != null) {
4188 CountDownLatch done = null;
4189 boolean interrupted = false;
4190 while ((tryTerminate(interrupted, true) & TERMINATED) == 0) {
4191 if (done == null)
4192 done = terminationSignal();
4193 else {
4194 try {
4195 done.await();
4196 break;
4197 } catch (InterruptedException ex) {
4198 interrupted = true;
4199 }
4200 }
4201 }
4202 if (interrupted)
4203 Thread.currentThread().interrupt();
4204 }
4205 }
4206
4207 /**
4208 * Interface for extending managed parallelism for tasks running
4209 * in {@link ForkJoinPool}s.
4210 *
4211 * <p>A {@code ManagedBlocker} provides two methods. Method
4212 * {@link #isReleasable} must return {@code true} if blocking is
4213 * not necessary. Method {@link #block} blocks the current thread
4214 * if necessary (perhaps internally invoking {@code isReleasable}
4215 * before actually blocking). These actions are performed by any
4216 * thread invoking {@link
4217 * ForkJoinPool#managedBlock(ManagedBlocker)}. The unusual
4218 * methods in this API accommodate synchronizers that may, but
4219 * don't usually, block for long periods. Similarly, they allow
4220 * more efficient internal handling of cases in which additional
4221 * workers may be, but usually are not, needed to ensure
4222 * sufficient parallelism. Toward this end, implementations of
4223 * method {@code isReleasable} must be amenable to repeated
4224 * invocation. Neither method is invoked after a prior invocation
4225 * of {@code isReleasable} or {@code block} returns {@code true}.
4226 *
4227 * <p>For example, here is a ManagedBlocker based on a
4228 * ReentrantLock:
4229 * <pre> {@code
4230 * class ManagedLocker implements ManagedBlocker {
4231 * final ReentrantLock lock;
4232 * boolean hasLock = false;
4233 * ManagedLocker(ReentrantLock lock) { this.lock = lock; }
4234 * public boolean block() {
4235 * if (!hasLock)
4236 * lock.lock();
4237 * return true;
4238 * }
4239 * public boolean isReleasable() {
4240 * return hasLock || (hasLock = lock.tryLock());
4241 * }
4242 * }}</pre>
4243 *
4244 * <p>Here is a class that possibly blocks waiting for an
4245 * item on a given queue:
4246 * <pre> {@code
4247 * class QueueTaker<E> implements ManagedBlocker {
4248 * final BlockingQueue<E> queue;
4249 * volatile E item = null;
4250 * QueueTaker(BlockingQueue<E> q) { this.queue = q; }
4251 * public boolean block() throws InterruptedException {
4252 * if (item == null)
4253 * item = queue.take();
4254 * return true;
4255 * }
4256 * public boolean isReleasable() {
4257 * return item != null || (item = queue.poll()) != null;
4258 * }
4259 * public E getItem() { // call after pool.managedBlock completes
4260 * return item;
4261 * }
4262 * }}</pre>
4263 */
4264 public static interface ManagedBlocker {
4265 /**
4266 * Possibly blocks the current thread, for example waiting for
4267 * a lock or condition.
4268 *
4269 * @return {@code true} if no additional blocking is necessary
4270 * (i.e., if isReleasable would return true)
4271 * @throws InterruptedException if interrupted while waiting
4272 * (the method is not required to do so, but is allowed to)
4273 */
4274 boolean block() throws InterruptedException;
4275
4276 /**
4277 * Returns {@code true} if blocking is unnecessary.
4278 * @return {@code true} if blocking is unnecessary
4279 */
4280 boolean isReleasable();
4281 }
4282
4283 /**
4284 * Runs the given possibly blocking task. When {@linkplain
4285 * ForkJoinTask#inForkJoinPool() running in a ForkJoinPool}, this
4286 * method possibly arranges for a spare thread to be activated if
4287 * necessary to ensure sufficient parallelism while the current
4288 * thread is blocked in {@link ManagedBlocker#block blocker.block()}.
4289 *
4290 * <p>This method repeatedly calls {@code blocker.isReleasable()} and
4291 * {@code blocker.block()} until either method returns {@code true}.
4292 * Every call to {@code blocker.block()} is preceded by a call to
4293 * {@code blocker.isReleasable()} that returned {@code false}.
4294 *
4295 * <p>If not running in a ForkJoinPool, this method is
4296 * behaviorally equivalent to
4297 * <pre> {@code
4298 * while (!blocker.isReleasable())
4299 * if (blocker.block())
4300 * break;}</pre>
4301 *
4302 * If running in a ForkJoinPool, the pool may first be expanded to
4303 * ensure sufficient parallelism available during the call to
4304 * {@code blocker.block()}.
4305 *
4306 * @param blocker the blocker task
4307 * @throws InterruptedException if {@code blocker.block()} did so
4308 */
4309 public static void managedBlock(ManagedBlocker blocker)
4310 throws InterruptedException {
4311 Thread t; ForkJoinPool p;
4312 if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread &&
4313 (p = ((ForkJoinWorkerThread)t).pool) != null)
4314 p.compensatedBlock(blocker);
4315 else
4316 unmanagedBlock(blocker);
4317 }
4318
4319 /** ManagedBlock for ForkJoinWorkerThreads */
4320 private void compensatedBlock(ManagedBlocker blocker)
4321 throws InterruptedException {
4322 Objects.requireNonNull(blocker);
4323 for (;;) {
4324 int comp; boolean done;
4325 long c = ctl;
4326 if (blocker.isReleasable())
4327 break;
4328 if ((runState & STOP) != 0L)
4329 throw new InterruptedException();
4330 if ((comp = tryCompensate(c)) >= 0) {
4331 try {
4332 done = blocker.block();
4333 } finally {
4334 if (comp > 0)
4335 getAndAddCtl(RC_UNIT);
4336 }
4337 if (done)
4338 break;
4339 }
4340 }
4341 }
4342
4343 /**
4344 * Invokes tryCompensate to create or re-activate a spare thread to
4345 * compensate for a thread that performs a blocking operation. When the
4346 * blocking operation is done then endCompensatedBlock must be invoked
4347 * with the value returned by this method to re-adjust the parallelism.
4348 * @return value to use in endCompensatedBlock
4349 */
4350 final long beginCompensatedBlock() {
4351 int c;
4352 do {} while ((c = tryCompensate(ctl)) < 0);
4353 return (c == 0) ? 0L : RC_UNIT;
4354 }
4355
4356 /**
4357 * Re-adjusts parallelism after a blocking operation completes.
4358 * @param post value from beginCompensatedBlock
4359 */
4360 void endCompensatedBlock(long post) {
4361 if (post > 0L) {
4362 getAndAddCtl(post);
4363 }
4364 }
4365
4366 /** ManagedBlock for external threads */
4367 private static void unmanagedBlock(ManagedBlocker blocker)
4368 throws InterruptedException {
4369 Objects.requireNonNull(blocker);
4370 do {} while (!blocker.isReleasable() && !blocker.block());
4371 }
4372
4373 @Override
4374 protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
4375 Objects.requireNonNull(runnable);
4376 return (Thread.currentThread() instanceof ForkJoinWorkerThread) ?
4377 new ForkJoinTask.AdaptedRunnable<T>(runnable, value) :
4378 new ForkJoinTask.AdaptedInterruptibleRunnable<T>(runnable, value);
4379 }
4380
4381 @Override
4382 protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
4383 Objects.requireNonNull(callable);
4384 return (Thread.currentThread() instanceof ForkJoinWorkerThread) ?
4385 new ForkJoinTask.AdaptedCallable<T>(callable) :
4386 new ForkJoinTask.AdaptedInterruptibleCallable<T>(callable);
4387 }
4388
4389 static {
4390 U = Unsafe.getUnsafe();
4391 Class<ForkJoinPool> klass = ForkJoinPool.class;
4392 try {
4393 Field poolIdsField = klass.getDeclaredField("poolIds");
4394 POOLIDS_BASE = U.staticFieldBase(poolIdsField);
4395 POOLIDS = U.staticFieldOffset(poolIdsField);
4396 } catch (NoSuchFieldException e) {
4397 throw new ExceptionInInitializerError(e);
4398 }
4399 CTL = U.objectFieldOffset(klass, "ctl");
4400 RUNSTATE = U.objectFieldOffset(klass, "runState");
4401 PARALLELISM = U.objectFieldOffset(klass, "parallelism");
4402 THREADIDS = U.objectFieldOffset(klass, "threadIds");
4403 TERMINATION = U.objectFieldOffset(klass, "termination");
4404 Class<ForkJoinTask[]> aklass = ForkJoinTask[].class;
4405 ABASE = U.arrayBaseOffset(aklass);
4406 int scale = U.arrayIndexScale(aklass);
4407 ASHIFT = 31 - Integer.numberOfLeadingZeros(scale);
4408 if ((scale & (scale - 1)) != 0)
4409 throw new Error("array index scale not a power of two");
4410
4411 Class<?> dep = LockSupport.class; // ensure loaded
4412 // allow access to non-public methods
4413 JLA = SharedSecrets.getJavaLangAccess();
4414 SharedSecrets.setJavaUtilConcurrentFJPAccess(
4415 new JavaUtilConcurrentFJPAccess() {
4416 @Override
4417 public long beginCompensatedBlock(ForkJoinPool pool) {
4418 return pool.beginCompensatedBlock();
4419 }
4420 public void endCompensatedBlock(ForkJoinPool pool, long post) {
4421 pool.endCompensatedBlock(post);
4422 }
4423 });
4424 defaultForkJoinWorkerThreadFactory =
4425 new DefaultForkJoinWorkerThreadFactory();
4426 common = new ForkJoinPool((byte)0);
4427 }
4428 }