ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinPool.java
Revision: 1.282
Committed: Sat Oct 3 15:57:14 2015 UTC (8 years, 8 months ago) by dl
Branch: MAIN
Changes since 1.281: +11 -16 lines
Log Message:
Ensure tasks processed when quiescing

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