ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinPool.java
Revision: 1.322
Committed: Wed Aug 24 21:00:37 2016 UTC (7 years, 9 months ago) by jsr166
Branch: MAIN
Changes since 1.321: +0 -4 lines
Log Message:
remove same-package imports

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