ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinPool.java
Revision: 1.340
Committed: Tue Jan 16 20:54:38 2018 UTC (6 years, 4 months ago) by jsr166
Branch: MAIN
Changes since 1.339: +0 -1 lines
Log Message:
whitespace

File Contents

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