ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinPool.java
Revision: 1.373
Committed: Tue Feb 11 23:59:56 2020 UTC (4 years, 3 months ago) by dl
Branch: MAIN
Changes since 1.372: +57 -47 lines
Log Message:
combine some code paths

File Contents

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