ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinPool.java
Revision: 1.403
Committed: Thu Sep 30 17:29:05 2021 UTC (2 years, 8 months ago) by dl
Branch: MAIN
Changes since 1.402: +1 -1 lines
Log Message:
Fix incompatible common pool sizing when ncpus = 1 vs previous versions

File Contents

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