ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinPool.java
Revision: 1.333
Committed: Fri Feb 3 20:21:47 2017 UTC (7 years, 3 months ago) by jsr166
Branch: MAIN
Changes since 1.332: +7 -6 lines
Log Message:
improve docs for common pool default thread factory behavior

File Contents

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