ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinPool.java
Revision: 1.351
Committed: Wed Dec 5 11:03:24 2018 UTC (5 years, 5 months ago) by dl
Branch: MAIN
Changes since 1.350: +61 -52 lines
Log Message:
Reduce unnecessary signals

File Contents

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