ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinPool.java
Revision: 1.330
Committed: Thu Nov 3 12:00:26 2016 UTC (7 years, 6 months ago) by dl
Branch: MAIN
Changes since 1.329: +2 -1 lines
Log Message:
Mention daemon status in docs

File Contents

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