ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinPool.java
Revision: 1.345
Committed: Mon Feb 12 20:01:40 2018 UTC (6 years, 3 months ago) by dl
Branch: MAIN
Changes since 1.344: +565 -625 lines
Log Message:
Recommit 1.339, with updates and fix

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