ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinPool.java
Revision: 1.298
Committed: Mon Nov 23 17:00:43 2015 UTC (8 years, 6 months ago) by jsr166
Branch: MAIN
Changes since 1.297: +1 -1 lines
Log Message:
fix internal javadoc

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 lifetime status, atomically and
293 * monotonically setting STARTED, SHUTDOWN, STOP, and finally
294 * TERMINATED bits.
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 workQueues. The auxState instance is itself lazily
300 * constructed (see tryInitialize), requiring a double-check-style
301 * bootstrapping use of field runState, and locking a private
302 * 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. Calls to non-abrupt shutdown()
464 * preface this by checking whether termination should commence.
465 * This relies primarily on the active count bits of "ctl"
466 * maintaining consensus -- tryTerminate is called from awaitWork
467 * whenever quiescent. However, external submitters do not take
468 * part in this consensus. So, tryTerminate sweeps through queues
469 * (until stable) to ensure lack of in-flight submissions and
470 * workers about to process them before triggering the "STOP"
471 * phase of termination. (Note: there is an intrinsic conflict if
472 * helpQuiescePool is called when shutdown is enabled. Both wait
473 * for quiescence, but tryTerminate is biased to not trigger until
474 * helpQuiescePool completes.)
475 *
476 * Joining Tasks
477 * =============
478 *
479 * Any of several actions may be taken when one worker is waiting
480 * to join a task stolen (or always held) by another. Because we
481 * are multiplexing many tasks on to a pool of workers, we can't
482 * just let them block (as in Thread.join). We also cannot just
483 * reassign the joiner's run-time stack with another and replace
484 * it later, which would be a form of "continuation", that even if
485 * possible is not necessarily a good idea since we may need both
486 * an unblocked task and its continuation to progress. Instead we
487 * combine two tactics:
488 *
489 * Helping: Arranging for the joiner to execute some task that it
490 * would be running if the steal had not occurred.
491 *
492 * Compensating: Unless there are already enough live threads,
493 * method tryCompensate() may create or re-activate a spare
494 * thread to compensate for blocked joiners until they unblock.
495 *
496 * A third form (implemented in tryRemoveAndExec) amounts to
497 * helping a hypothetical compensator: If we can readily tell that
498 * a possible action of a compensator is to steal and execute the
499 * task being joined, the joining thread can do so directly,
500 * without the need for a compensation thread (although at the
501 * expense of larger run-time stacks, but the tradeoff is
502 * typically worthwhile).
503 *
504 * The ManagedBlocker extension API can't use helping so relies
505 * only on compensation in method awaitBlocker.
506 *
507 * The algorithm in helpStealer entails a form of "linear
508 * helping". Each worker records (in field currentSteal) the most
509 * recent task it stole from some other worker (or a submission).
510 * It also records (in field currentJoin) the task it is currently
511 * actively joining. Method helpStealer uses these markers to try
512 * to find a worker to help (i.e., steal back a task from and
513 * execute it) that could hasten completion of the actively joined
514 * task. Thus, the joiner executes a task that would be on its
515 * own local deque had the to-be-joined task not been stolen. This
516 * is a conservative variant of the approach described in Wagner &
517 * Calder "Leapfrogging: a portable technique for implementing
518 * efficient futures" SIGPLAN Notices, 1993
519 * (http://portal.acm.org/citation.cfm?id=155354). It differs in
520 * that: (1) We only maintain dependency links across workers upon
521 * steals, rather than use per-task bookkeeping. This sometimes
522 * requires a linear scan of workQueues array to locate stealers,
523 * but often doesn't because stealers leave hints (that may become
524 * stale/wrong) of where to locate them. It is only a hint
525 * because a worker might have had multiple steals and the hint
526 * records only one of them (usually the most current). Hinting
527 * isolates cost to when it is needed, rather than adding to
528 * per-task overhead. (2) It is "shallow", ignoring nesting and
529 * potentially cyclic mutual steals. (3) It is intentionally
530 * racy: field currentJoin is updated only while actively joining,
531 * which means that we miss links in the chain during long-lived
532 * tasks, GC stalls etc (which is OK since blocking in such cases
533 * is usually a good idea). (4) We bound the number of attempts
534 * to find work using checksums and fall back to suspending the
535 * worker and if necessary replacing it with another.
536 *
537 * Helping actions for CountedCompleters do not require tracking
538 * currentJoins: Method helpComplete takes and executes any task
539 * with the same root as the task being waited on (preferring
540 * local pops to non-local polls). However, this still entails
541 * some traversal of completer chains, so is less efficient than
542 * using CountedCompleters without explicit joins.
543 *
544 * Compensation does not aim to keep exactly the target
545 * parallelism number of unblocked threads running at any given
546 * time. Some previous versions of this class employed immediate
547 * compensations for any blocked join. However, in practice, the
548 * vast majority of blockages are transient byproducts of GC and
549 * other JVM or OS activities that are made worse by replacement.
550 * Currently, compensation is attempted only after validating that
551 * all purportedly active threads are processing tasks by checking
552 * field WorkQueue.scanState, which eliminates most false
553 * positives. Also, compensation is bypassed (tolerating fewer
554 * threads) in the most common case in which it is rarely
555 * beneficial: when a worker with an empty queue (thus no
556 * continuation tasks) blocks on a join and there still remain
557 * enough threads to ensure liveness.
558 *
559 * Spare threads are removed as soon as they notice that the
560 * target parallelism level has been exceeded, in method
561 * tryDropSpare. (Method scan arranges returns for rechecks upon
562 * each probe via the "bound" parameter.)
563 *
564 * The compensation mechanism may be bounded. Bounds for the
565 * commonPool (see COMMON_MAX_SPARES) better enable JVMs to cope
566 * with programming errors and abuse before running out of
567 * resources to do so. In other cases, users may supply factories
568 * that limit thread construction. The effects of bounding in this
569 * pool (like all others) is imprecise. Total worker counts are
570 * decremented when threads deregister, not when they exit and
571 * resources are reclaimed by the JVM and OS. So the number of
572 * simultaneously live threads may transiently exceed bounds.
573 *
574 * Common Pool
575 * ===========
576 *
577 * The static common pool always exists after static
578 * initialization. Since it (or any other created pool) need
579 * never be used, we minimize initial construction overhead and
580 * footprint to the setup of about a dozen fields, with no nested
581 * allocation. Most bootstrapping occurs within method
582 * externalSubmit during the first submission to the pool.
583 *
584 * When external threads submit to the common pool, they can
585 * perform subtask processing (see externalHelpComplete and
586 * related methods) upon joins. This caller-helps policy makes it
587 * sensible to set common pool parallelism level to one (or more)
588 * less than the total number of available cores, or even zero for
589 * pure caller-runs. We do not need to record whether external
590 * submissions are to the common pool -- if not, external help
591 * methods return quickly. These submitters would otherwise be
592 * blocked waiting for completion, so the extra effort (with
593 * liberally sprinkled task status checks) in inapplicable cases
594 * amounts to an odd form of limited spin-wait before blocking in
595 * ForkJoinTask.join.
596 *
597 * As a more appropriate default in managed environments, unless
598 * overridden by system properties, we use workers of subclass
599 * InnocuousForkJoinWorkerThread when there is a SecurityManager
600 * present. These workers have no permissions set, do not belong
601 * to any user-defined ThreadGroup, and erase all ThreadLocals
602 * after executing any top-level task (see WorkQueue.runTask).
603 * The associated mechanics (mainly in ForkJoinWorkerThread) may
604 * be JVM-dependent and must access particular Thread class fields
605 * to achieve this effect.
606 *
607 * Style notes
608 * ===========
609 *
610 * Memory ordering relies mainly on Unsafe intrinsics that carry
611 * the further responsibility of explicitly performing null- and
612 * bounds- checks otherwise carried out implicitly by JVMs. This
613 * can be awkward and ugly, but also reflects the need to control
614 * outcomes across the unusual cases that arise in very racy code
615 * with very few invariants. So these explicit checks would exist
616 * in some form anyway. All fields are read into locals before
617 * use, and null-checked if they are references. This is usually
618 * done in a "C"-like style of listing declarations at the heads
619 * of methods or blocks, and using inline assignments on first
620 * encounter. Array bounds-checks are usually performed by
621 * masking with array.length-1, which relies on the invariant that
622 * these arrays are created with positive lengths, which is itself
623 * paranoically checked. Nearly all explicit checks lead to
624 * bypass/return, not exception throws, because they may
625 * legitimately arise due to cancellation/revocation during
626 * shutdown.
627 *
628 * There is a lot of representation-level coupling among classes
629 * ForkJoinPool, ForkJoinWorkerThread, and ForkJoinTask. The
630 * fields of WorkQueue maintain data structures managed by
631 * ForkJoinPool, so are directly accessed. There is little point
632 * trying to reduce this, since any associated future changes in
633 * representations will need to be accompanied by algorithmic
634 * changes anyway. Several methods intrinsically sprawl because
635 * they must accumulate sets of consistent reads of fields held in
636 * local variables. There are also other coding oddities
637 * (including several unnecessary-looking hoisted null checks)
638 * that help some methods perform reasonably even when interpreted
639 * (not compiled).
640 *
641 * The order of declarations in this file is (with a few exceptions):
642 * (1) Static utility functions
643 * (2) Nested (static) classes
644 * (3) Static fields
645 * (4) Fields, along with constants used when unpacking some of them
646 * (5) Internal control methods
647 * (6) Callbacks and other support for ForkJoinTask methods
648 * (7) Exported methods
649 * (8) Static block initializing statics in minimally dependent order
650 */
651
652 // Static utilities
653
654 /**
655 * If there is a security manager, makes sure caller has
656 * permission to modify threads.
657 */
658 private static void checkPermission() {
659 SecurityManager security = System.getSecurityManager();
660 if (security != null)
661 security.checkPermission(modifyThreadPermission);
662 }
663
664 // Nested classes
665
666 /**
667 * Factory for creating new {@link ForkJoinWorkerThread}s.
668 * A {@code ForkJoinWorkerThreadFactory} must be defined and used
669 * for {@code ForkJoinWorkerThread} subclasses that extend base
670 * functionality or initialize threads with different contexts.
671 */
672 public static interface ForkJoinWorkerThreadFactory {
673 /**
674 * Returns a new worker thread operating in the given pool.
675 *
676 * @param pool the pool this thread works in
677 * @return the new worker thread, or {@code null} if the request
678 * to create a thread is rejected
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 U.storeFence(); // ensure safe publication
839 int s = top, al, d; ForkJoinTask<?>[] a;
840 if ((a = array) != null && (al = a.length) > 0) {
841 a[(al - 1) & s] = task; // relaxed writes OK
842 top = s + 1;
843 ForkJoinPool p = pool;
844 if ((d = base - s) == 0 && p != null) {
845 U.fullFence();
846 p.signalWork();
847 }
848 else if (al + d == 1)
849 growArray();
850 }
851 }
852
853 /**
854 * Initializes or doubles the capacity of array. Call either
855 * by owner or with lock held -- it is OK for base, but not
856 * top, to move while resizings are in progress.
857 */
858 final ForkJoinTask<?>[] growArray() {
859 ForkJoinTask<?>[] oldA = array;
860 int size = oldA != null ? oldA.length << 1 : INITIAL_QUEUE_CAPACITY;
861 if (size < INITIAL_QUEUE_CAPACITY || size > MAXIMUM_QUEUE_CAPACITY)
862 throw new RejectedExecutionException("Queue capacity exceeded");
863 int oldMask, t, b;
864 ForkJoinTask<?>[] a = array = new ForkJoinTask<?>[size];
865 if (oldA != null && (oldMask = oldA.length - 1) > 0 &&
866 (t = top) - (b = base) > 0) {
867 int mask = size - 1;
868 do { // emulate poll from old array, push to new array
869 int index = b & oldMask;
870 long offset = ((long)index << ASHIFT) + ABASE;
871 ForkJoinTask<?> x = (ForkJoinTask<?>)
872 U.getObjectVolatile(oldA, offset);
873 if (x != null &&
874 U.compareAndSwapObject(oldA, offset, x, null))
875 a[b & mask] = x;
876 } while (++b != t);
877 U.storeFence();
878 }
879 return a;
880 }
881
882 /**
883 * Takes next task, if one exists, in LIFO order. Call only
884 * by owner in unshared queues.
885 */
886 final ForkJoinTask<?> pop() {
887 int b = base, s = top, al, i; ForkJoinTask<?>[] a;
888 if ((a = array) != null && b != s && (al = a.length) > 0) {
889 int index = (al - 1) & --s;
890 long offset = ((long)index << ASHIFT) + ABASE;
891 ForkJoinTask<?> t = (ForkJoinTask<?>)
892 U.getObject(a, offset);
893 if (t != null &&
894 U.compareAndSwapObject(a, offset, t, null)) {
895 top = s;
896 return t;
897 }
898 }
899 return null;
900 }
901
902 /**
903 * Takes a task in FIFO order if b is base of queue and a task
904 * can be claimed without contention. Specialized versions
905 * appear in ForkJoinPool methods scan and helpStealer.
906 */
907 final ForkJoinTask<?> pollAt(int b) {
908 ForkJoinTask<?>[] a; int al;
909 if ((a = array) != null && (al = a.length) > 0) {
910 int index = (al - 1) & b;
911 long offset = ((long)index << ASHIFT) + ABASE;
912 ForkJoinTask<?> t = (ForkJoinTask<?>)
913 U.getObjectVolatile(a, offset);
914 if (t != null && b++ == base &&
915 U.compareAndSwapObject(a, offset, t, null)) {
916 base = b;
917 return t;
918 }
919 }
920 return null;
921 }
922
923 /**
924 * Takes next task, if one exists, in FIFO order.
925 */
926 final ForkJoinTask<?> poll() {
927 for (;;) {
928 int b = base, s = top, d, al; ForkJoinTask<?>[] a;
929 if ((a = array) != null && (d = b - s) < 0 &&
930 (al = a.length) > 0) {
931 int index = (al - 1) & b;
932 long offset = ((long)index << ASHIFT) + ABASE;
933 ForkJoinTask<?> t = (ForkJoinTask<?>)
934 U.getObjectVolatile(a, offset);
935 if (b++ == base) {
936 if (t != null) {
937 if (U.compareAndSwapObject(a, offset, t, null)) {
938 base = b;
939 return t;
940 }
941 }
942 else if (d == -1)
943 break; // now empty
944 }
945 }
946 else
947 break;
948 }
949 return null;
950 }
951
952 /**
953 * Takes next task, if one exists, in order specified by mode.
954 */
955 final ForkJoinTask<?> nextLocalTask() {
956 return (config < 0) ? poll() : pop();
957 }
958
959 /**
960 * Returns next task, if one exists, in order specified by mode.
961 */
962 final ForkJoinTask<?> peek() {
963 int al; ForkJoinTask<?>[] a;
964 return ((a = array) != null && (al = a.length) > 0) ?
965 a[(al - 1) & (config < 0 ? base : top - 1)] : null;
966 }
967
968 /**
969 * Pops the given task only if it is at the current top.
970 */
971 final boolean tryUnpush(ForkJoinTask<?> task) {
972 int b = base, s = top, al; ForkJoinTask<?>[] a;
973 if ((a = array) != null && b != s && (al = a.length) > 0) {
974 int index = (al - 1) & --s;
975 long offset = ((long)index << ASHIFT) + ABASE;
976 if (U.compareAndSwapObject(a, offset, task, null)) {
977 top = s;
978 return true;
979 }
980 }
981 return false;
982 }
983
984 /**
985 * Shared version of push. Fails if already locked.
986 *
987 * @return status: > 0 locked, 0 possibly was empty, < 0 was nonempty
988 */
989 final int sharedPush(ForkJoinTask<?> task) {
990 int stat;
991 if (U.compareAndSwapInt(this, QLOCK, 0, 1)) {
992 int b = base, s = top, al, d; ForkJoinTask<?>[] a;
993 if ((a = array) != null && (al = a.length) > 0 &&
994 al - 1 + (d = b - s) > 0) {
995 a[(al - 1) & s] = task;
996 top = s + 1; // relaxed writes OK here
997 qlock = 0;
998 stat = (d < 0 && b == base) ? d : 0;
999 }
1000 else {
1001 growAndSharedPush(task);
1002 stat = 0;
1003 }
1004 }
1005 else
1006 stat = 1;
1007 return stat;
1008 }
1009
1010 /**
1011 * Helper for sharedPush; called only when locked and resize
1012 * needed.
1013 */
1014 private void growAndSharedPush(ForkJoinTask<?> task) {
1015 try {
1016 growArray();
1017 int s = top, al; ForkJoinTask<?>[] a;
1018 if ((a = array) != null && (al = a.length) > 0) {
1019 a[(al - 1) & s] = task;
1020 top = s + 1;
1021 }
1022 } finally {
1023 qlock = 0;
1024 }
1025 }
1026
1027 /**
1028 * Shared version of tryUnpush.
1029 */
1030 final boolean trySharedUnpush(ForkJoinTask<?> task) {
1031 boolean popped = false;
1032 int s = top - 1, al; ForkJoinTask<?>[] a;
1033 if ((a = array) != null && (al = a.length) > 0) {
1034 int index = (al - 1) & s;
1035 long offset = ((long)index << ASHIFT) + ABASE;
1036 ForkJoinTask<?> t = (ForkJoinTask<?>) U.getObject(a, offset);
1037 if (t == task &&
1038 U.compareAndSwapInt(this, QLOCK, 0, 1)) {
1039 if (top == s + 1 && array == a &&
1040 U.compareAndSwapObject(a, offset, task, null)) {
1041 popped = true;
1042 top = s;
1043 }
1044 U.putOrderedInt(this, QLOCK, 0);
1045 }
1046 }
1047 return popped;
1048 }
1049
1050 /**
1051 * Removes and cancels all known tasks, ignoring any exceptions.
1052 */
1053 final void cancelAll() {
1054 ForkJoinTask<?> t;
1055 if ((t = currentJoin) != null) {
1056 currentJoin = null;
1057 ForkJoinTask.cancelIgnoringExceptions(t);
1058 }
1059 if ((t = currentSteal) != null) {
1060 currentSteal = null;
1061 ForkJoinTask.cancelIgnoringExceptions(t);
1062 }
1063 while ((t = poll()) != null)
1064 ForkJoinTask.cancelIgnoringExceptions(t);
1065 }
1066
1067 // Specialized execution methods
1068
1069 /**
1070 * Pops and executes up to POLL_LIMIT tasks or until empty.
1071 */
1072 final void localPopAndExec() {
1073 for (int nexec = 0;;) {
1074 int b = base, s = top, al; ForkJoinTask<?>[] a;
1075 if ((a = array) != null && b != s && (al = a.length) > 0) {
1076 int index = (al - 1) & --s;
1077 long offset = ((long)index << ASHIFT) + ABASE;
1078 ForkJoinTask<?> t = (ForkJoinTask<?>)
1079 U.getAndSetObject(a, offset, null);
1080 if (t != null) {
1081 top = s;
1082 (currentSteal = t).doExec();
1083 if (++nexec > POLL_LIMIT)
1084 break;
1085 }
1086 else
1087 break;
1088 }
1089 else
1090 break;
1091 }
1092 }
1093
1094 /**
1095 * Polls and executes up to POLL_LIMIT tasks or until empty.
1096 */
1097 final void localPollAndExec() {
1098 for (int nexec = 0;;) {
1099 int b = base, s = top, al; ForkJoinTask<?>[] a;
1100 if ((a = array) != null && b != s && (al = a.length) > 0) {
1101 int index = (al - 1) & b++;
1102 long offset = ((long)index << ASHIFT) + ABASE;
1103 ForkJoinTask<?> t = (ForkJoinTask<?>)
1104 U.getAndSetObject(a, offset, null);
1105 if (t != null) {
1106 base = b;
1107 t.doExec();
1108 if (++nexec > POLL_LIMIT)
1109 break;
1110 }
1111 }
1112 else
1113 break;
1114 }
1115 }
1116
1117 /**
1118 * Executes the given task and (some) remaining local tasks.
1119 */
1120 final void runTask(ForkJoinTask<?> task) {
1121 if (task != null) {
1122 task.doExec();
1123 if (config < 0)
1124 localPollAndExec();
1125 else
1126 localPopAndExec();
1127 int ns = ++nsteals;
1128 ForkJoinWorkerThread thread = owner;
1129 currentSteal = null;
1130 if (ns < 0) // collect on overflow
1131 transferStealCount(pool);
1132 if (thread != null)
1133 thread.afterTopLevelExec();
1134 }
1135 }
1136
1137 /**
1138 * Adds steal count to pool steal count if it exists, and resets.
1139 */
1140 final void transferStealCount(ForkJoinPool p) {
1141 AuxState aux;
1142 if (p != null && (aux = p.auxState) != null) {
1143 long s = nsteals;
1144 nsteals = 0; // if negative, correct for overflow
1145 if (s < 0) s = Integer.MAX_VALUE;
1146 aux.lock();
1147 try {
1148 aux.stealCount += s;
1149 } finally {
1150 aux.unlock();
1151 }
1152 }
1153 }
1154
1155 /**
1156 * If present, removes from queue and executes the given task,
1157 * or any other cancelled task. Used only by awaitJoin.
1158 *
1159 * @return true if queue empty and task not known to be done
1160 */
1161 final boolean tryRemoveAndExec(ForkJoinTask<?> task) {
1162 if (task != null && task.status >= 0) {
1163 int b, s, d, al; ForkJoinTask<?>[] a;
1164 while ((d = (b = base) - (s = top)) < 0 &&
1165 (a = array) != null && (al = a.length) > 0) {
1166 for (;;) { // traverse from s to b
1167 int index = --s & (al - 1);
1168 long offset = (index << ASHIFT) + ABASE;
1169 ForkJoinTask<?> t = (ForkJoinTask<?>)
1170 U.getObjectVolatile(a, offset);
1171 if (t == null)
1172 break; // restart
1173 else if (t == task) {
1174 boolean removed = false;
1175 if (s + 1 == top) { // pop
1176 if (U.compareAndSwapObject(a, offset, t, null)) {
1177 top = s;
1178 removed = true;
1179 }
1180 }
1181 else if (base == b) // replace with proxy
1182 removed = U.compareAndSwapObject(a, offset, t,
1183 new EmptyTask());
1184 if (removed) {
1185 ForkJoinTask<?> ps = currentSteal;
1186 (currentSteal = task).doExec();
1187 currentSteal = ps;
1188 }
1189 break;
1190 }
1191 else if (t.status < 0 && s + 1 == top) {
1192 if (U.compareAndSwapObject(a, offset, t, null)) {
1193 top = s;
1194 }
1195 break; // was cancelled
1196 }
1197 else if (++d == 0) {
1198 if (base != b) // rescan
1199 break;
1200 return false;
1201 }
1202 }
1203 if (task.status < 0)
1204 return false;
1205 }
1206 }
1207 return true;
1208 }
1209
1210 /**
1211 * Pops task if in the same CC computation as the given task,
1212 * in either shared or owned mode. Used only by helpComplete.
1213 */
1214 final CountedCompleter<?> popCC(CountedCompleter<?> task, int mode) {
1215 int b = base, s = top, al; ForkJoinTask<?>[] a;
1216 if ((a = array) != null && b != s && (al = a.length) > 0) {
1217 int index = (al - 1) & (s - 1);
1218 long offset = ((long)index << ASHIFT) + ABASE;
1219 ForkJoinTask<?> o = (ForkJoinTask<?>)
1220 U.getObjectVolatile(a, offset);
1221 if (o instanceof CountedCompleter) {
1222 CountedCompleter<?> t = (CountedCompleter<?>)o;
1223 for (CountedCompleter<?> r = t;;) {
1224 if (r == task) {
1225 if ((mode & IS_OWNED) == 0) {
1226 boolean popped = false;
1227 if (U.compareAndSwapInt(this, QLOCK, 0, 1)) {
1228 if (top == s && array == a &&
1229 U.compareAndSwapObject(a, offset,
1230 t, null)) {
1231 popped = true;
1232 top = s - 1;
1233 }
1234 U.putOrderedInt(this, QLOCK, 0);
1235 if (popped)
1236 return t;
1237 }
1238 }
1239 else if (U.compareAndSwapObject(a, offset,
1240 t, null)) {
1241 top = s - 1;
1242 return t;
1243 }
1244 break;
1245 }
1246 else if ((r = r.completer) == null) // try parent
1247 break;
1248 }
1249 }
1250 }
1251 return null;
1252 }
1253
1254 /**
1255 * Steals and runs a task in the same CC computation as the
1256 * given task if one exists and can be taken without
1257 * contention. Otherwise returns a checksum/control value for
1258 * use by method helpComplete.
1259 *
1260 * @return 1 if successful, 2 if retryable (lost to another
1261 * stealer), -1 if non-empty but no matching task found, else
1262 * the base index, forced negative.
1263 */
1264 final int pollAndExecCC(CountedCompleter<?> task) {
1265 ForkJoinTask<?>[] a;
1266 int b = base, s = top, al, h;
1267 if ((a = array) != null && b != s && (al = a.length) > 0) {
1268 int index = (al - 1) & b;
1269 long offset = ((long)index << ASHIFT) + ABASE;
1270 ForkJoinTask<?> o = (ForkJoinTask<?>)
1271 U.getObjectVolatile(a, offset);
1272 if (o == null)
1273 h = 2; // retryable
1274 else if (!(o instanceof CountedCompleter))
1275 h = -1; // unmatchable
1276 else {
1277 CountedCompleter<?> t = (CountedCompleter<?>)o;
1278 for (CountedCompleter<?> r = t;;) {
1279 if (r == task) {
1280 if (b++ == base &&
1281 U.compareAndSwapObject(a, offset, t, null)) {
1282 base = b;
1283 t.doExec();
1284 h = 1; // success
1285 }
1286 else
1287 h = 2; // lost CAS
1288 break;
1289 }
1290 else if ((r = r.completer) == null) {
1291 h = -1; // unmatched
1292 break;
1293 }
1294 }
1295 }
1296 }
1297 else
1298 h = b | Integer.MIN_VALUE; // to sense movement on re-poll
1299 return h;
1300 }
1301
1302 /**
1303 * Returns true if owned and not known to be blocked.
1304 */
1305 final boolean isApparentlyUnblocked() {
1306 Thread wt; Thread.State s;
1307 return (scanState >= 0 &&
1308 (wt = owner) != null &&
1309 (s = wt.getState()) != Thread.State.BLOCKED &&
1310 s != Thread.State.WAITING &&
1311 s != Thread.State.TIMED_WAITING);
1312 }
1313
1314 // Unsafe mechanics. Note that some are (and must be) the same as in FJP
1315 private static final sun.misc.Unsafe U = sun.misc.Unsafe.getUnsafe();
1316 private static final long QLOCK;
1317 private static final int ABASE;
1318 private static final int ASHIFT;
1319 static {
1320 try {
1321 QLOCK = U.objectFieldOffset
1322 (WorkQueue.class.getDeclaredField("qlock"));
1323 ABASE = U.arrayBaseOffset(ForkJoinTask[].class);
1324 int scale = U.arrayIndexScale(ForkJoinTask[].class);
1325 if ((scale & (scale - 1)) != 0)
1326 throw new Error("array index scale not a power of two");
1327 ASHIFT = 31 - Integer.numberOfLeadingZeros(scale);
1328 } catch (ReflectiveOperationException e) {
1329 throw new Error(e);
1330 }
1331 }
1332 }
1333
1334 // static fields (initialized in static initializer below)
1335
1336 /**
1337 * Creates a new ForkJoinWorkerThread. This factory is used unless
1338 * overridden in ForkJoinPool constructors.
1339 */
1340 public static final ForkJoinWorkerThreadFactory
1341 defaultForkJoinWorkerThreadFactory;
1342
1343 /**
1344 * Permission required for callers of methods that may start or
1345 * kill threads. Also used as a static lock in tryInitialize.
1346 */
1347 static final RuntimePermission modifyThreadPermission;
1348
1349 /**
1350 * Common (static) pool. Non-null for public use unless a static
1351 * construction exception, but internal usages null-check on use
1352 * to paranoically avoid potential initialization circularities
1353 * as well as to simplify generated code.
1354 */
1355 static final ForkJoinPool common;
1356
1357 /**
1358 * Common pool parallelism. To allow simpler use and management
1359 * when common pool threads are disabled, we allow the underlying
1360 * common.parallelism field to be zero, but in that case still report
1361 * parallelism as 1 to reflect resulting caller-runs mechanics.
1362 */
1363 static final int COMMON_PARALLELISM;
1364
1365 /**
1366 * Limit on spare thread construction in tryCompensate.
1367 */
1368 private static final int COMMON_MAX_SPARES;
1369
1370 /**
1371 * Sequence number for creating workerNamePrefix.
1372 */
1373 private static int poolNumberSequence;
1374
1375 /**
1376 * Returns the next sequence number. We don't expect this to
1377 * ever contend, so use simple builtin sync.
1378 */
1379 private static final synchronized int nextPoolId() {
1380 return ++poolNumberSequence;
1381 }
1382
1383 // static configuration constants
1384
1385 /**
1386 * Initial timeout value (in milliseconds) for the thread
1387 * triggering quiescence to park waiting for new work. On timeout,
1388 * the thread will instead try to shrink the number of workers.
1389 * The value should be large enough to avoid overly aggressive
1390 * shrinkage during most transient stalls (long GCs etc).
1391 */
1392 private static final long IDLE_TIMEOUT_MS = 2000L; // 2sec
1393
1394 /**
1395 * Tolerance for idle timeouts, to cope with timer undershoots.
1396 */
1397 private static final long TIMEOUT_SLOP_MS = 20L; // 20ms
1398
1399 /**
1400 * The default value for COMMON_MAX_SPARES. Overridable using the
1401 * "java.util.concurrent.ForkJoinPool.common.maximumSpares" system
1402 * property. The default value is far in excess of normal
1403 * requirements, but also far short of MAX_CAP and typical OS
1404 * thread limits, so allows JVMs to catch misuse/abuse before
1405 * running out of resources needed to do so.
1406 */
1407 private static final int DEFAULT_COMMON_MAX_SPARES = 256;
1408
1409 /**
1410 * Increment for seed generators. See class ThreadLocal for
1411 * explanation.
1412 */
1413 private static final int SEED_INCREMENT = 0x9e3779b9;
1414
1415 /*
1416 * Bits and masks for field ctl, packed with 4 16 bit subfields:
1417 * AC: Number of active running workers minus target parallelism
1418 * TC: Number of total workers minus target parallelism
1419 * SS: version count and status of top waiting thread
1420 * ID: poolIndex of top of Treiber stack of waiters
1421 *
1422 * When convenient, we can extract the lower 32 stack top bits
1423 * (including version bits) as sp=(int)ctl. The offsets of counts
1424 * by the target parallelism and the positionings of fields makes
1425 * it possible to perform the most common checks via sign tests of
1426 * fields: When ac is negative, there are not enough active
1427 * workers, when tc is negative, there are not enough total
1428 * workers. When sp is non-zero, there are waiting workers. To
1429 * deal with possibly negative fields, we use casts in and out of
1430 * "short" and/or signed shifts to maintain signedness.
1431 *
1432 * Because it occupies uppermost bits, we can add one active count
1433 * using getAndAddLong of AC_UNIT, rather than CAS, when returning
1434 * from a blocked join. Other updates entail multiple subfields
1435 * and masking, requiring CAS.
1436 */
1437
1438 // Lower and upper word masks
1439 private static final long SP_MASK = 0xffffffffL;
1440 private static final long UC_MASK = ~SP_MASK;
1441
1442 // Active counts
1443 private static final int AC_SHIFT = 48;
1444 private static final long AC_UNIT = 0x0001L << AC_SHIFT;
1445 private static final long AC_MASK = 0xffffL << AC_SHIFT;
1446
1447 // Total counts
1448 private static final int TC_SHIFT = 32;
1449 private static final long TC_UNIT = 0x0001L << TC_SHIFT;
1450 private static final long TC_MASK = 0xffffL << TC_SHIFT;
1451 private static final long ADD_WORKER = 0x0001L << (TC_SHIFT + 15); // sign
1452
1453 // runState bits: SHUTDOWN must be negative, others arbitrary powers of two
1454 private static final int STARTED = 1;
1455 private static final int STOP = 1 << 1;
1456 private static final int TERMINATED = 1 << 2;
1457 private static final int SHUTDOWN = 1 << 31;
1458
1459 // Instance fields
1460 volatile long ctl; // main pool control
1461 volatile int runState;
1462 final int config; // parallelism, mode
1463 AuxState auxState; // lock, steal counts
1464 volatile WorkQueue[] workQueues; // main registry
1465 final String workerNamePrefix; // to create worker name string
1466 final ForkJoinWorkerThreadFactory factory;
1467 final UncaughtExceptionHandler ueh; // per-worker UEH
1468
1469 /**
1470 * Instantiates fields upon first submission, or upon shutdown if
1471 * no submissions. If checkTermination true, also responds to
1472 * termination by external calls submitting tasks.
1473 */
1474 private void tryInitialize(boolean checkTermination) {
1475 if (runState == 0) { // bootstrap by locking static field
1476 int p = config & SMASK;
1477 int n = (p > 1) ? p - 1 : 1; // ensure at least 2 slots
1478 n |= n >>> 1; // create workQueues array with size a power of two
1479 n |= n >>> 2;
1480 n |= n >>> 4;
1481 n |= n >>> 8;
1482 n |= n >>> 16;
1483 n = ((n + 1) << 1) & SMASK;
1484 AuxState aux = new AuxState();
1485 WorkQueue[] ws = new WorkQueue[n];
1486 synchronized (modifyThreadPermission) { // double-check
1487 if (runState == 0) {
1488 workQueues = ws;
1489 auxState = aux;
1490 runState = STARTED;
1491 }
1492 }
1493 }
1494 if (checkTermination && runState < 0) {
1495 tryTerminate(false, false); // help terminate
1496 throw new RejectedExecutionException();
1497 }
1498 }
1499
1500 // Creating, registering and deregistering workers
1501
1502 /**
1503 * Tries to construct and start one worker. Assumes that total
1504 * count has already been incremented as a reservation. Invokes
1505 * deregisterWorker on any failure.
1506 *
1507 * @param isSpare true if this is a spare thread
1508 * @return true if successful
1509 */
1510 private boolean createWorker(boolean isSpare) {
1511 ForkJoinWorkerThreadFactory fac = factory;
1512 Throwable ex = null;
1513 ForkJoinWorkerThread wt = null;
1514 WorkQueue q;
1515 try {
1516 if (fac != null && (wt = fac.newThread(this)) != null) {
1517 if (isSpare && (q = wt.workQueue) != null)
1518 q.config |= SPARE_WORKER;
1519 wt.start();
1520 return true;
1521 }
1522 } catch (Throwable rex) {
1523 ex = rex;
1524 }
1525 deregisterWorker(wt, ex);
1526 return false;
1527 }
1528
1529 /**
1530 * Tries to add one worker, incrementing ctl counts before doing
1531 * so, relying on createWorker to back out on failure.
1532 *
1533 * @param c incoming ctl value, with total count negative and no
1534 * idle workers. On CAS failure, c is refreshed and retried if
1535 * this holds (otherwise, a new worker is not needed).
1536 */
1537 private void tryAddWorker(long c) {
1538 do {
1539 long nc = ((AC_MASK & (c + AC_UNIT)) |
1540 (TC_MASK & (c + TC_UNIT)));
1541 if (ctl == c && U.compareAndSwapLong(this, CTL, c, nc)) {
1542 createWorker(false);
1543 break;
1544 }
1545 } while (((c = ctl) & ADD_WORKER) != 0L && (int)c == 0);
1546 }
1547
1548 /**
1549 * Callback from ForkJoinWorkerThread constructor to establish and
1550 * record its WorkQueue.
1551 *
1552 * @param wt the worker thread
1553 * @return the worker's queue
1554 */
1555 final WorkQueue registerWorker(ForkJoinWorkerThread wt) {
1556 UncaughtExceptionHandler handler;
1557 AuxState aux;
1558 wt.setDaemon(true); // configure thread
1559 if ((handler = ueh) != null)
1560 wt.setUncaughtExceptionHandler(handler);
1561 WorkQueue w = new WorkQueue(this, wt);
1562 int i = 0; // assign a pool index
1563 int mode = config & MODE_MASK;
1564 if ((aux = auxState) != null) {
1565 aux.lock();
1566 try {
1567 int s = (int)(aux.indexSeed += SEED_INCREMENT), n, m;
1568 WorkQueue[] ws = workQueues;
1569 if (ws != null && (n = ws.length) > 0) {
1570 i = (m = n - 1) & ((s << 1) | 1); // odd-numbered indices
1571 if (ws[i] != null) { // collision
1572 int probes = 0; // step by approx half n
1573 int step = (n <= 4) ? 2 : ((n >>> 1) & EVENMASK) + 2;
1574 while (ws[i = (i + step) & m] != null) {
1575 if (++probes >= n) {
1576 workQueues = ws = Arrays.copyOf(ws, n <<= 1);
1577 m = n - 1;
1578 probes = 0;
1579 }
1580 }
1581 }
1582 w.hint = s; // use as random seed
1583 w.config = i | mode;
1584 w.scanState = i | (s & 0x7fff0000); // random seq bits
1585 ws[i] = w;
1586 }
1587 } finally {
1588 aux.unlock();
1589 }
1590 }
1591 wt.setName(workerNamePrefix.concat(Integer.toString(i >>> 1)));
1592 return w;
1593 }
1594
1595 /**
1596 * Final callback from terminating worker, as well as upon failure
1597 * to construct or start a worker. Removes record of worker from
1598 * array, and adjusts counts. If pool is shutting down, tries to
1599 * complete termination.
1600 *
1601 * @param wt the worker thread, or null if construction failed
1602 * @param ex the exception causing failure, or null if none
1603 */
1604 final void deregisterWorker(ForkJoinWorkerThread wt, Throwable ex) {
1605 WorkQueue w = null;
1606 if (wt != null && (w = wt.workQueue) != null) {
1607 AuxState aux; WorkQueue[] ws; // remove index from array
1608 int idx = w.config & SMASK;
1609 int ns = w.nsteals;
1610 if ((aux = auxState) != null) {
1611 aux.lock();
1612 try {
1613 if ((ws = workQueues) != null && ws.length > idx &&
1614 ws[idx] == w)
1615 ws[idx] = null;
1616 aux.stealCount += ns;
1617 } finally {
1618 aux.unlock();
1619 }
1620 }
1621 }
1622 if (w == null || (w.config & UNREGISTERED) == 0) { // else pre-adjusted
1623 long c; // decrement counts
1624 do {} while (!U.compareAndSwapLong
1625 (this, CTL, c = ctl, ((AC_MASK & (c - AC_UNIT)) |
1626 (TC_MASK & (c - TC_UNIT)) |
1627 (SP_MASK & c))));
1628 }
1629 if (w != null) {
1630 w.currentSteal = null;
1631 w.qlock = -1; // ensure set
1632 w.cancelAll(); // cancel remaining tasks
1633 }
1634 while (tryTerminate(false, false) >= 0) { // possibly replace
1635 WorkQueue[] ws; int wl, sp; long c;
1636 if (w == null || w.array == null ||
1637 (ws = workQueues) == null || (wl = ws.length) <= 0)
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 (w.scanState < 0) {
1776 w.parker = Thread.currentThread();
1777 if (w.scanState < 0) // recheck after write
1778 LockSupport.park(this);
1779 w.parker = null;
1780 if ((runState & STOP) != 0)
1781 stat = w.qlock = -1; // recheck
1782 else if (w.scanState < 0)
1783 Thread.interrupted(); // clear status
1784 }
1785 }
1786 return stat;
1787 }
1788
1789 /**
1790 * Possibly triggers shutdown and tries (once) to block worker
1791 * when pool is (or may be) quiescent. Waits up to a duration
1792 * determined by number of workers. On timeout, if ctl has not
1793 * changed, terminates the worker, which will in turn wake up
1794 * another worker to possibly repeat this process.
1795 *
1796 * @param w the calling worker
1797 * @return negative if w should terminate
1798 */
1799 private int timedAwaitWork(WorkQueue w, long c) {
1800 int stat = 0;
1801 int scale = 1 - (short)(c >>> TC_SHIFT);
1802 long deadline = (((scale <= 0) ? 1 : scale) * IDLE_TIMEOUT_MS +
1803 System.currentTimeMillis());
1804 if ((runState >= 0 || (stat = tryTerminate(false, false)) > 0) &&
1805 w != null && w.scanState < 0) {
1806 int ss; AuxState aux;
1807 w.parker = Thread.currentThread();
1808 if (w.scanState < 0)
1809 LockSupport.parkUntil(this, deadline);
1810 w.parker = null;
1811 if ((runState & STOP) != 0)
1812 stat = w.qlock = -1; // pool terminating
1813 else if ((ss = w.scanState) < 0 && !Thread.interrupted() &&
1814 (int)c == ss && (aux = auxState) != null && ctl == c &&
1815 deadline - System.currentTimeMillis() <= TIMEOUT_SLOP_MS) {
1816 aux.lock();
1817 try { // pre-deregister
1818 WorkQueue[] ws;
1819 int cfg = w.config, idx = cfg & SMASK;
1820 long nc = ((UC_MASK & (c - TC_UNIT)) |
1821 (SP_MASK & w.stackPred));
1822 if ((runState & STOP) == 0 &&
1823 (ws = workQueues) != null &&
1824 idx < ws.length && idx >= 0 && ws[idx] == w &&
1825 U.compareAndSwapLong(this, CTL, c, nc)) {
1826 ws[idx] = null;
1827 w.config = cfg | UNREGISTERED;
1828 stat = w.qlock = -1;
1829 }
1830 } finally {
1831 aux.unlock();
1832 }
1833 }
1834 }
1835 return stat;
1836 }
1837
1838 /**
1839 * If the given worker is a spare with no queued tasks, and there
1840 * are enough existing workers, drops it from ctl counts and sets
1841 * its state to terminated.
1842 *
1843 * @param w the calling worker -- must be a spare
1844 * @return true if dropped (in which case it must not process more tasks)
1845 */
1846 private boolean tryDropSpare(WorkQueue w) {
1847 if (w != null && w.isEmpty()) { // no local tasks
1848 long c; int sp, wl; WorkQueue[] ws; WorkQueue v;
1849 while ((short)((c = ctl) >> TC_SHIFT) > 0 &&
1850 ((sp = (int)c) != 0 || (int)(c >> AC_SHIFT) > 0) &&
1851 (ws = workQueues) != null && (wl = ws.length) > 0) {
1852 boolean dropped, canDrop;
1853 if (sp == 0) { // no queued workers
1854 long nc = ((AC_MASK & (c - AC_UNIT)) |
1855 (TC_MASK & (c - TC_UNIT)) | (SP_MASK & c));
1856 dropped = U.compareAndSwapLong(this, CTL, c, nc);
1857 }
1858 else if (
1859 (v = ws[(wl - 1) & sp]) == null || v.scanState != sp)
1860 dropped = false; // stale; retry
1861 else {
1862 long nc = v.stackPred & SP_MASK;
1863 if (w == v || w.scanState >= 0) {
1864 canDrop = true; // w unqueued or topmost
1865 nc |= ((AC_MASK & c) | // ensure replacement
1866 (TC_MASK & (c - TC_UNIT)));
1867 }
1868 else { // w may be queued
1869 canDrop = false; // help uncover
1870 nc |= ((AC_MASK & (c + AC_UNIT)) |
1871 (TC_MASK & c));
1872 }
1873 if (U.compareAndSwapLong(this, CTL, c, nc)) {
1874 v.scanState = sp & ~UNSIGNALLED;
1875 LockSupport.unpark(v.parker);
1876 dropped = canDrop;
1877 }
1878 else
1879 dropped = false;
1880 }
1881 if (dropped) { // pre-deregister
1882 int cfg = w.config, idx = cfg & SMASK;
1883 if (idx >= 0 && idx < ws.length && ws[idx] == w)
1884 ws[idx] = null;
1885 w.config = cfg | UNREGISTERED;
1886 w.qlock = -1;
1887 return true;
1888 }
1889 }
1890 }
1891 return false;
1892 }
1893
1894 /**
1895 * Top-level runloop for workers, called by ForkJoinWorkerThread.run.
1896 */
1897 final void runWorker(WorkQueue w) {
1898 w.growArray(); // allocate queue
1899 int bound = (w.config & SPARE_WORKER) != 0 ? 0 : POLL_LIMIT;
1900 long seed = w.hint * 0xdaba0b6eb09322e3L; // initial random seed
1901 if ((runState & STOP) == 0) {
1902 for (long r = (seed == 0L) ? 1L : seed;;) { // ensure nonzero
1903 if (bound == 0 && tryDropSpare(w))
1904 break;
1905 // high bits of prev seed for step; current low bits for idx
1906 int step = (int)(r >>> 48) | 1;
1907 r ^= r >>> 12; r ^= r << 25; r ^= r >>> 27; // xorshift
1908 if (scan(w, bound, step, (int)r) < 0 && awaitWork(w) < 0)
1909 break;
1910 }
1911 }
1912 }
1913
1914 // Scanning for tasks
1915
1916 /**
1917 * Repeatedly scans for and tries to steal and execute (via
1918 * workQueue.runTask) a queued task. Each scan traverses queues in
1919 * pseudorandom permutation. Upon finding a non-empty queue, makes
1920 * at most the given bound attempts to re-poll (fewer if
1921 * contended) on the same queue before returning (impossible
1922 * scanState value) 0 to restart scan. Else returns after at least
1923 * 1 and at most 32 full scans.
1924 *
1925 * @param w the worker (via its WorkQueue)
1926 * @param bound repoll bound as bitmask (0 if spare)
1927 * @param step (circular) index increment per iteration (must be odd)
1928 * @param r a random seed for origin index
1929 * @return negative if should await signal
1930 */
1931 private int scan(WorkQueue w, int bound, int step, int r) {
1932 int stat = 0, wl; WorkQueue[] ws;
1933 if ((ws = workQueues) != null && w != null && (wl = ws.length) > 0) {
1934 for (int m = wl - 1,
1935 origin = m & r, idx = origin,
1936 npolls = 0,
1937 ss = w.scanState;;) { // negative if inactive
1938 WorkQueue q; ForkJoinTask<?>[] a; int b, al;
1939 if ((q = ws[idx]) != null && (b = q.base) - q.top < 0 &&
1940 (a = q.array) != null && (al = a.length) > 0) {
1941 int index = (al - 1) & b;
1942 long offset = ((long)index << ASHIFT) + ABASE;
1943 ForkJoinTask<?> t = (ForkJoinTask<?>)
1944 U.getObjectVolatile(a, offset);
1945 if (t == null)
1946 break; // empty or busy
1947 else if (b++ != q.base)
1948 break; // busy
1949 else if (ss < 0) {
1950 tryReactivate(w, ws, r);
1951 break; // retry upon rescan
1952 }
1953 else if (!U.compareAndSwapObject(a, offset, t, null))
1954 break; // contended
1955 else {
1956 q.base = b;
1957 w.currentSteal = t;
1958 if (b != q.top) // propagate signal
1959 signalWork();
1960 w.runTask(t);
1961 if (++npolls > bound)
1962 break;
1963 }
1964 }
1965 else if (npolls != 0) // rescan
1966 break;
1967 else if ((idx = (idx + step) & m) == origin) {
1968 if (ss < 0) { // await signal
1969 stat = ss;
1970 break;
1971 }
1972 else if (r >= 0) {
1973 inactivate(w, ss);
1974 break;
1975 }
1976 else
1977 r <<= 1; // at most 31 rescans
1978 }
1979 }
1980 }
1981 return stat;
1982 }
1983
1984 // Joining tasks
1985
1986 /**
1987 * Tries to steal and run tasks within the target's computation.
1988 * Uses a variant of the top-level algorithm, restricted to tasks
1989 * with the given task as ancestor: It prefers taking and running
1990 * eligible tasks popped from the worker's own queue (via
1991 * popCC). Otherwise it scans others, randomly moving on
1992 * contention or execution, deciding to give up based on a
1993 * checksum (via return codes from pollAndExecCC). The maxTasks
1994 * argument supports external usages; internal calls use zero,
1995 * allowing unbounded steps (external calls trap non-positive
1996 * values).
1997 *
1998 * @param w caller
1999 * @param maxTasks if non-zero, the maximum number of other tasks to run
2000 * @return task status on exit
2001 */
2002 final int helpComplete(WorkQueue w, CountedCompleter<?> task,
2003 int maxTasks) {
2004 WorkQueue[] ws; int s = 0, wl;
2005 if ((ws = workQueues) != null && (wl = ws.length) > 1 &&
2006 task != null && w != null) {
2007 for (int m = wl - 1,
2008 mode = w.config,
2009 r = ~mode, // scanning seed
2010 origin = r & m, k = origin, // first queue to scan
2011 step = 3, // first scan step
2012 h = 1, // 1:ran, >1:contended, <0:hash
2013 oldSum = 0, checkSum = 0;;) {
2014 CountedCompleter<?> p; WorkQueue q; int i;
2015 if ((s = task.status) < 0)
2016 break;
2017 if (h == 1 && (p = w.popCC(task, mode)) != null) {
2018 p.doExec(); // run local task
2019 if (maxTasks != 0 && --maxTasks == 0)
2020 break;
2021 origin = k; // reset
2022 oldSum = checkSum = 0;
2023 }
2024 else { // poll other worker queues
2025 if ((i = k | 1) < 0 || i > m || (q = ws[i]) == null)
2026 h = 0;
2027 else if ((h = q.pollAndExecCC(task)) < 0)
2028 checkSum += h;
2029 if (h > 0) {
2030 if (h == 1 && maxTasks != 0 && --maxTasks == 0)
2031 break;
2032 step = (r >>> 16) | 3;
2033 r ^= r << 13; r ^= r >>> 17; r ^= r << 5; // xorshift
2034 k = origin = r & m; // move and restart
2035 oldSum = checkSum = 0;
2036 }
2037 else if ((k = (k + step) & m) == origin) {
2038 if (oldSum == (oldSum = checkSum))
2039 break;
2040 checkSum = 0;
2041 }
2042 }
2043 }
2044 }
2045 return s;
2046 }
2047
2048 /**
2049 * Tries to locate and execute tasks for a stealer of the given
2050 * task, or in turn one of its stealers. Traces currentSteal ->
2051 * currentJoin links looking for a thread working on a descendant
2052 * of the given task and with a non-empty queue to steal back and
2053 * execute tasks from. The first call to this method upon a
2054 * waiting join will often entail scanning/search, (which is OK
2055 * because the joiner has nothing better to do), but this method
2056 * leaves hints in workers to speed up subsequent calls.
2057 *
2058 * @param w caller
2059 * @param task the task to join
2060 */
2061 private void helpStealer(WorkQueue w, ForkJoinTask<?> task) {
2062 if (task != null && w != null) {
2063 ForkJoinTask<?> ps = w.currentSteal;
2064 WorkQueue[] ws; int wl, oldSum = 0;
2065 outer: while (w.tryRemoveAndExec(task) && task.status >= 0 &&
2066 (ws = workQueues) != null && (wl = ws.length) > 0) {
2067 ForkJoinTask<?> subtask;
2068 int m = wl - 1, checkSum = 0; // for stability check
2069 WorkQueue j = w, v; // v is subtask stealer
2070 descent: for (subtask = task; subtask.status >= 0; ) {
2071 for (int h = j.hint | 1, k = 0, i;;) {
2072 if ((v = ws[i = (h + (k << 1)) & m]) != null) {
2073 if (v.currentSteal == subtask) {
2074 j.hint = i;
2075 break;
2076 }
2077 checkSum += v.base;
2078 }
2079 if (++k > m) // can't find stealer
2080 break outer;
2081 }
2082
2083 for (;;) { // help v or descend
2084 ForkJoinTask<?>[] a; int b, al;
2085 if (subtask.status < 0) // too late to help
2086 break descent;
2087 checkSum += (b = v.base);
2088 ForkJoinTask<?> next = v.currentJoin;
2089 ForkJoinTask<?> t = null;
2090 if ((a = v.array) != null && (al = a.length) > 0) {
2091 int index = (al - 1) & b;
2092 long offset = ((long)index << ASHIFT) + ABASE;
2093 t = (ForkJoinTask<?>)
2094 U.getObjectVolatile(a, offset);
2095 if (t != null && b++ == v.base) {
2096 if (j.currentJoin != subtask ||
2097 v.currentSteal != subtask ||
2098 subtask.status < 0)
2099 break descent; // stale
2100 if (U.compareAndSwapObject(a, offset, t, null)) {
2101 v.base = b;
2102 w.currentSteal = t;
2103 for (int top = w.top;;) {
2104 t.doExec(); // help
2105 w.currentSteal = ps;
2106 if (task.status < 0)
2107 break outer;
2108 if (w.top == top)
2109 break; // run local tasks
2110 if ((t = w.pop()) == null)
2111 break descent;
2112 w.currentSteal = t;
2113 }
2114 }
2115 }
2116 }
2117 if (t == null && b == v.base && b - v.top >= 0) {
2118 if ((subtask = next) == null) { // try to descend
2119 if (next == v.currentJoin &&
2120 oldSum == (oldSum = checkSum))
2121 break outer;
2122 break descent;
2123 }
2124 j = v;
2125 break;
2126 }
2127 }
2128 }
2129 }
2130 }
2131 }
2132
2133 /**
2134 * Tries to decrement active count (sometimes implicitly) and
2135 * possibly release or create a compensating worker in preparation
2136 * for blocking. Returns false (retryable by caller), on
2137 * contention, detected staleness, instability, or termination.
2138 *
2139 * @param w caller
2140 */
2141 private boolean tryCompensate(WorkQueue w) {
2142 boolean canBlock; int wl;
2143 long c = ctl;
2144 WorkQueue[] ws = workQueues;
2145 int pc = config & SMASK;
2146 int ac = pc + (int)(c >> AC_SHIFT);
2147 int tc = pc + (short)(c >> TC_SHIFT);
2148 if (w == null || w.qlock < 0 || pc == 0 || // terminating or disabled
2149 ws == null || (wl = ws.length) <= 0)
2150 canBlock = false;
2151 else {
2152 int m = wl - 1, sp;
2153 boolean busy = true; // validate ac
2154 for (int i = 0; i <= m; ++i) {
2155 int k; WorkQueue v;
2156 if ((k = (i << 1) | 1) <= m && k >= 0 && (v = ws[k]) != null &&
2157 v.scanState >= 0 && v.currentSteal == null) {
2158 busy = false;
2159 break;
2160 }
2161 }
2162 if (!busy || ctl != c)
2163 canBlock = false; // unstable or stale
2164 else if ((sp = (int)c) != 0) // release idle worker
2165 canBlock = tryRelease(c, ws[m & sp], 0L);
2166 else if (tc >= pc && ac > 1 && w.isEmpty()) {
2167 long nc = ((AC_MASK & (c - AC_UNIT)) |
2168 (~AC_MASK & c)); // uncompensated
2169 canBlock = U.compareAndSwapLong(this, CTL, c, nc);
2170 }
2171 else if (tc >= MAX_CAP ||
2172 (this == common && tc >= pc + COMMON_MAX_SPARES))
2173 throw new RejectedExecutionException(
2174 "Thread limit exceeded replacing blocked worker");
2175 else { // similar to tryAddWorker
2176 boolean isSpare = (tc >= pc);
2177 long nc = (AC_MASK & c) | (TC_MASK & (c + TC_UNIT));
2178 canBlock = (U.compareAndSwapLong(this, CTL, c, nc) &&
2179 createWorker(isSpare)); // throws on exception
2180 }
2181 }
2182 return canBlock;
2183 }
2184
2185 /**
2186 * Helps and/or blocks until the given task is done or timeout.
2187 *
2188 * @param w caller
2189 * @param task the task
2190 * @param deadline for timed waits, if nonzero
2191 * @return task status on exit
2192 */
2193 final int awaitJoin(WorkQueue w, ForkJoinTask<?> task, long deadline) {
2194 int s = 0;
2195 if (w != null) {
2196 ForkJoinTask<?> prevJoin = w.currentJoin;
2197 if (task != null && (s = task.status) >= 0) {
2198 w.currentJoin = task;
2199 CountedCompleter<?> cc = (task instanceof CountedCompleter) ?
2200 (CountedCompleter<?>)task : null;
2201 for (;;) {
2202 if (cc != null)
2203 helpComplete(w, cc, 0);
2204 else
2205 helpStealer(w, task);
2206 if ((s = task.status) < 0)
2207 break;
2208 long ms, ns;
2209 if (deadline == 0L)
2210 ms = 0L;
2211 else if ((ns = deadline - System.nanoTime()) <= 0L)
2212 break;
2213 else if ((ms = TimeUnit.NANOSECONDS.toMillis(ns)) <= 0L)
2214 ms = 1L;
2215 if (tryCompensate(w)) {
2216 task.internalWait(ms);
2217 U.getAndAddLong(this, CTL, AC_UNIT);
2218 }
2219 if ((s = task.status) < 0)
2220 break;
2221 }
2222 w.currentJoin = prevJoin;
2223 }
2224 }
2225 return s;
2226 }
2227
2228 // Specialized scanning
2229
2230 /**
2231 * Returns a (probably) non-empty steal queue, if one is found
2232 * during a scan, else null. This method must be retried by
2233 * caller if, by the time it tries to use the queue, it is empty.
2234 */
2235 private WorkQueue findNonEmptyStealQueue() {
2236 WorkQueue[] ws; int wl; // one-shot version of scan loop
2237 int r = ThreadLocalRandom.nextSecondarySeed();
2238 if ((ws = workQueues) != null && (wl = ws.length) > 0) {
2239 int m = wl - 1, origin = r & m;
2240 for (int k = origin, oldSum = 0, checkSum = 0;;) {
2241 WorkQueue q; int b;
2242 if ((q = ws[k]) != null) {
2243 if ((b = q.base) - q.top < 0)
2244 return q;
2245 checkSum += b;
2246 }
2247 if ((k = (k + 1) & m) == origin) {
2248 if (oldSum == (oldSum = checkSum))
2249 break;
2250 checkSum = 0;
2251 }
2252 }
2253 }
2254 return null;
2255 }
2256
2257 /**
2258 * Runs tasks until {@code isQuiescent()}. We piggyback on
2259 * active count ctl maintenance, but rather than blocking
2260 * when tasks cannot be found, we rescan until all others cannot
2261 * find tasks either.
2262 */
2263 final void helpQuiescePool(WorkQueue w) {
2264 ForkJoinTask<?> ps = w.currentSteal; // save context
2265 int wc = w.config;
2266 for (boolean active = true;;) {
2267 long c; WorkQueue q; ForkJoinTask<?> t;
2268 if (wc >= 0 && (t = w.pop()) != null) { // run locals if LIFO
2269 (w.currentSteal = t).doExec();
2270 w.currentSteal = ps;
2271 }
2272 else if ((q = findNonEmptyStealQueue()) != null) {
2273 if (!active) { // re-establish active count
2274 active = true;
2275 U.getAndAddLong(this, CTL, AC_UNIT);
2276 }
2277 if ((t = q.pollAt(q.base)) != null) {
2278 (w.currentSteal = t).doExec();
2279 w.currentSteal = ps;
2280 if (++w.nsteals < 0)
2281 w.transferStealCount(this);
2282 }
2283 }
2284 else if (active) { // decrement active count without queuing
2285 long nc = (AC_MASK & ((c = ctl) - AC_UNIT)) | (~AC_MASK & c);
2286 if (U.compareAndSwapLong(this, CTL, c, nc))
2287 active = false;
2288 }
2289 else if ((int)((c = ctl) >> AC_SHIFT) + (config & SMASK) <= 0 &&
2290 U.compareAndSwapLong(this, CTL, c, c + AC_UNIT))
2291 break;
2292 }
2293 }
2294
2295 /**
2296 * Gets and removes a local or stolen task for the given worker.
2297 *
2298 * @return a task, if available
2299 */
2300 final ForkJoinTask<?> nextTaskFor(WorkQueue w) {
2301 for (ForkJoinTask<?> t;;) {
2302 WorkQueue q;
2303 if ((t = w.nextLocalTask()) != null)
2304 return t;
2305 if ((q = findNonEmptyStealQueue()) == null)
2306 return null;
2307 if ((t = q.pollAt(q.base)) != null)
2308 return t;
2309 }
2310 }
2311
2312 /**
2313 * Returns a cheap heuristic guide for task partitioning when
2314 * programmers, frameworks, tools, or languages have little or no
2315 * idea about task granularity. In essence, by offering this
2316 * method, we ask users only about tradeoffs in overhead vs
2317 * expected throughput and its variance, rather than how finely to
2318 * partition tasks.
2319 *
2320 * In a steady state strict (tree-structured) computation, each
2321 * thread makes available for stealing enough tasks for other
2322 * threads to remain active. Inductively, if all threads play by
2323 * the same rules, each thread should make available only a
2324 * constant number of tasks.
2325 *
2326 * The minimum useful constant is just 1. But using a value of 1
2327 * would require immediate replenishment upon each steal to
2328 * maintain enough tasks, which is infeasible. Further,
2329 * partitionings/granularities of offered tasks should minimize
2330 * steal rates, which in general means that threads nearer the top
2331 * of computation tree should generate more than those nearer the
2332 * bottom. In perfect steady state, each thread is at
2333 * approximately the same level of computation tree. However,
2334 * producing extra tasks amortizes the uncertainty of progress and
2335 * diffusion assumptions.
2336 *
2337 * So, users will want to use values larger (but not much larger)
2338 * than 1 to both smooth over transient shortages and hedge
2339 * against uneven progress; as traded off against the cost of
2340 * extra task overhead. We leave the user to pick a threshold
2341 * value to compare with the results of this call to guide
2342 * decisions, but recommend values such as 3.
2343 *
2344 * When all threads are active, it is on average OK to estimate
2345 * surplus strictly locally. In steady-state, if one thread is
2346 * maintaining say 2 surplus tasks, then so are others. So we can
2347 * just use estimated queue length. However, this strategy alone
2348 * leads to serious mis-estimates in some non-steady-state
2349 * conditions (ramp-up, ramp-down, other stalls). We can detect
2350 * many of these by further considering the number of "idle"
2351 * threads, that are known to have zero queued tasks, so
2352 * compensate by a factor of (#idle/#active) threads.
2353 */
2354 static int getSurplusQueuedTaskCount() {
2355 Thread t; ForkJoinWorkerThread wt; ForkJoinPool pool; WorkQueue q;
2356 if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) {
2357 int p = (pool = (wt = (ForkJoinWorkerThread)t).pool).config & SMASK;
2358 int n = (q = wt.workQueue).top - q.base;
2359 int a = (int)(pool.ctl >> AC_SHIFT) + p;
2360 return n - (a > (p >>>= 1) ? 0 :
2361 a > (p >>>= 1) ? 1 :
2362 a > (p >>>= 1) ? 2 :
2363 a > (p >>>= 1) ? 4 :
2364 8);
2365 }
2366 return 0;
2367 }
2368
2369 // Termination
2370
2371 /**
2372 * Possibly initiates and/or completes termination.
2373 *
2374 * @param now if true, unconditionally terminate, else only
2375 * if no work and no active workers
2376 * @param enable if true, terminate when next possible
2377 * @return -1: terminating/terminated, 0: retry if internal caller, else 1
2378 */
2379 private int tryTerminate(boolean now, boolean enable) {
2380 int rs; // 3 phases: try to set SHUTDOWN, then STOP, then TERMINATED
2381
2382 while ((rs = runState) >= 0) {
2383 if (!enable || this == common) // cannot shutdown
2384 return 1;
2385 else if (rs == 0)
2386 tryInitialize(false); // ensure initialized
2387 else
2388 U.compareAndSwapInt(this, RUNSTATE, rs, rs | SHUTDOWN);
2389 }
2390
2391 if ((rs & STOP) == 0) { // try to initiate termination
2392 if (!now) { // check quiescence
2393 for (long oldSum = 0L;;) { // repeat until stable
2394 WorkQueue[] ws; WorkQueue w; int b;
2395 long checkSum = ctl;
2396 if ((int)(checkSum >> AC_SHIFT) + (config & SMASK) > 0)
2397 return 0; // still active workers
2398 if ((ws = workQueues) != null) {
2399 for (int i = 0; i < ws.length; ++i) {
2400 if ((w = ws[i]) != null) {
2401 checkSum += (b = w.base);
2402 if (w.currentSteal != null || b != w.top)
2403 return 0; // retry if internal caller
2404 }
2405 }
2406 }
2407 if (oldSum == (oldSum = checkSum))
2408 break;
2409 }
2410 }
2411 do {} while (!U.compareAndSwapInt(this, RUNSTATE,
2412 rs = runState, rs | STOP));
2413 }
2414
2415 for (long oldSum = 0L;;) { // repeat until stable
2416 WorkQueue[] ws; WorkQueue w; ForkJoinWorkerThread wt;
2417 long checkSum = ctl;
2418 if ((ws = workQueues) != null) { // help terminate others
2419 for (int i = 0; i < ws.length; ++i) {
2420 if ((w = ws[i]) != null) {
2421 w.cancelAll(); // clear queues
2422 checkSum += w.base;
2423 if (w.qlock >= 0) {
2424 w.qlock = -1; // racy set OK
2425 if ((wt = w.owner) != null) {
2426 try { // unblock join or park
2427 wt.interrupt();
2428 } catch (Throwable ignore) {
2429 }
2430 }
2431 }
2432 }
2433 }
2434 }
2435 if (oldSum == (oldSum = checkSum))
2436 break;
2437 }
2438
2439 if ((short)(ctl >>> TC_SHIFT) + (config & SMASK) <= 0) {
2440 runState = (STARTED | SHUTDOWN | STOP | TERMINATED); // final write
2441 synchronized (this) {
2442 notifyAll(); // for awaitTermination
2443 }
2444 }
2445
2446 return -1;
2447 }
2448
2449 // External operations
2450
2451 /**
2452 * Constructs and tries to install a new external queue,
2453 * failing if the workQueues array already has a queue at
2454 * the given index.
2455 *
2456 * @param index the index of the new queue
2457 */
2458 private void tryCreateExternalQueue(int index) {
2459 AuxState aux;
2460 if ((aux = auxState) != null && index >= 0) {
2461 WorkQueue q = new WorkQueue(this, null);
2462 q.config = index;
2463 q.scanState = ~UNSIGNALLED;
2464 q.qlock = 1; // lock queue
2465 boolean installed = false;
2466 aux.lock();
2467 try { // lock pool to install
2468 WorkQueue[] ws;
2469 if ((ws = workQueues) != null && index < ws.length &&
2470 ws[index] == null) {
2471 ws[index] = q; // else throw away
2472 installed = true;
2473 }
2474 } finally {
2475 aux.unlock();
2476 }
2477 if (installed) {
2478 try {
2479 q.growArray();
2480 } finally {
2481 q.qlock = 0;
2482 }
2483 }
2484 }
2485 }
2486
2487 /**
2488 * Adds the given task to a submission queue at submitter's
2489 * current queue. Also performs secondary initialization upon the
2490 * first submission of the first task to the pool, and detects
2491 * first submission by an external thread and creates a new shared
2492 * queue if the one at index if empty or contended.
2493 *
2494 * @param task the task. Caller must ensure non-null.
2495 */
2496 final void externalPush(ForkJoinTask<?> task) {
2497 int r; // initialize caller's probe
2498 if ((r = ThreadLocalRandom.getProbe()) == 0) {
2499 ThreadLocalRandom.localInit();
2500 r = ThreadLocalRandom.getProbe();
2501 }
2502 for (;;) {
2503 WorkQueue q; int wl, k, stat;
2504 int rs = runState;
2505 WorkQueue[] ws = workQueues;
2506 if (rs <= 0 || ws == null || (wl = ws.length) <= 0)
2507 tryInitialize(true);
2508 else if ((q = ws[k = (wl - 1) & r & SQMASK]) == null)
2509 tryCreateExternalQueue(k);
2510 else if ((stat = q.sharedPush(task)) < 0)
2511 break;
2512 else if (stat == 0) {
2513 signalWork();
2514 break;
2515 }
2516 else // move if busy
2517 r = ThreadLocalRandom.advanceProbe(r);
2518 }
2519 }
2520
2521 /**
2522 * Pushes a possibly-external submission.
2523 */
2524 private <T> ForkJoinTask<T> externalSubmit(ForkJoinTask<T> task) {
2525 Thread t; ForkJoinWorkerThread w; WorkQueue q;
2526 if (task == null)
2527 throw new NullPointerException();
2528 if (((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) &&
2529 (w = (ForkJoinWorkerThread)t).pool == this &&
2530 (q = w.workQueue) != null)
2531 q.push(task);
2532 else
2533 externalPush(task);
2534 return task;
2535 }
2536
2537 /**
2538 * Returns common pool queue for an external thread.
2539 */
2540 static WorkQueue commonSubmitterQueue() {
2541 ForkJoinPool p = common;
2542 int r = ThreadLocalRandom.getProbe();
2543 WorkQueue[] ws; int wl;
2544 return (p != null && (ws = p.workQueues) != null &&
2545 (wl = ws.length) > 0) ?
2546 ws[(wl - 1) & r & SQMASK] : null;
2547 }
2548
2549 /**
2550 * Performs tryUnpush for an external submitter.
2551 */
2552 final boolean tryExternalUnpush(ForkJoinTask<?> task) {
2553 int r = ThreadLocalRandom.getProbe();
2554 WorkQueue[] ws; WorkQueue w; int wl;
2555 return ((ws = workQueues) != null &&
2556 (wl = ws.length) > 0 &&
2557 (w = ws[(wl - 1) & r & SQMASK]) != null &&
2558 w.trySharedUnpush(task));
2559 }
2560
2561 /**
2562 * Performs helpComplete for an external submitter.
2563 */
2564 final int externalHelpComplete(CountedCompleter<?> task, int maxTasks) {
2565 WorkQueue[] ws; int wl;
2566 int r = ThreadLocalRandom.getProbe();
2567 return ((ws = workQueues) != null && (wl = ws.length) > 0) ?
2568 helpComplete(ws[(wl - 1) & r & SQMASK], task, maxTasks) : 0;
2569 }
2570
2571 // Exported methods
2572
2573 // Constructors
2574
2575 /**
2576 * Creates a {@code ForkJoinPool} with parallelism equal to {@link
2577 * java.lang.Runtime#availableProcessors}, using the {@linkplain
2578 * #defaultForkJoinWorkerThreadFactory default thread factory},
2579 * no UncaughtExceptionHandler, and non-async LIFO processing mode.
2580 *
2581 * @throws SecurityException if a security manager exists and
2582 * the caller is not permitted to modify threads
2583 * because it does not hold {@link
2584 * java.lang.RuntimePermission}{@code ("modifyThread")}
2585 */
2586 public ForkJoinPool() {
2587 this(Math.min(MAX_CAP, Runtime.getRuntime().availableProcessors()),
2588 defaultForkJoinWorkerThreadFactory, null, false);
2589 }
2590
2591 /**
2592 * Creates a {@code ForkJoinPool} with the indicated parallelism
2593 * level, the {@linkplain
2594 * #defaultForkJoinWorkerThreadFactory default thread factory},
2595 * no UncaughtExceptionHandler, and non-async LIFO processing mode.
2596 *
2597 * @param parallelism the parallelism level
2598 * @throws IllegalArgumentException if parallelism less than or
2599 * equal to zero, or greater than implementation limit
2600 * @throws SecurityException if a security manager exists and
2601 * the caller is not permitted to modify threads
2602 * because it does not hold {@link
2603 * java.lang.RuntimePermission}{@code ("modifyThread")}
2604 */
2605 public ForkJoinPool(int parallelism) {
2606 this(parallelism, defaultForkJoinWorkerThreadFactory, null, false);
2607 }
2608
2609 /**
2610 * Creates a {@code ForkJoinPool} with the given parameters.
2611 *
2612 * @param parallelism the parallelism level. For default value,
2613 * use {@link java.lang.Runtime#availableProcessors}.
2614 * @param factory the factory for creating new threads. For default value,
2615 * use {@link #defaultForkJoinWorkerThreadFactory}.
2616 * @param handler the handler for internal worker threads that
2617 * terminate due to unrecoverable errors encountered while executing
2618 * tasks. For default value, use {@code null}.
2619 * @param asyncMode if true,
2620 * establishes local first-in-first-out scheduling mode for forked
2621 * tasks that are never joined. This mode may be more appropriate
2622 * than default locally stack-based mode in applications in which
2623 * worker threads only process event-style asynchronous tasks.
2624 * For default value, use {@code false}.
2625 * @throws IllegalArgumentException if parallelism less than or
2626 * equal to zero, or greater than implementation limit
2627 * @throws NullPointerException if the factory is null
2628 * @throws SecurityException if a security manager exists and
2629 * the caller is not permitted to modify threads
2630 * because it does not hold {@link
2631 * java.lang.RuntimePermission}{@code ("modifyThread")}
2632 */
2633 public ForkJoinPool(int parallelism,
2634 ForkJoinWorkerThreadFactory factory,
2635 UncaughtExceptionHandler handler,
2636 boolean asyncMode) {
2637 this(checkParallelism(parallelism),
2638 checkFactory(factory),
2639 handler,
2640 asyncMode ? FIFO_QUEUE : LIFO_QUEUE,
2641 "ForkJoinPool-" + nextPoolId() + "-worker-");
2642 checkPermission();
2643 }
2644
2645 private static int checkParallelism(int parallelism) {
2646 if (parallelism <= 0 || parallelism > MAX_CAP)
2647 throw new IllegalArgumentException();
2648 return parallelism;
2649 }
2650
2651 private static ForkJoinWorkerThreadFactory checkFactory
2652 (ForkJoinWorkerThreadFactory factory) {
2653 if (factory == null)
2654 throw new NullPointerException();
2655 return factory;
2656 }
2657
2658 /**
2659 * Creates a {@code ForkJoinPool} with the given parameters, without
2660 * any security checks or parameter validation. Invoked directly by
2661 * makeCommonPool.
2662 */
2663 private ForkJoinPool(int parallelism,
2664 ForkJoinWorkerThreadFactory factory,
2665 UncaughtExceptionHandler handler,
2666 int mode,
2667 String workerNamePrefix) {
2668 this.workerNamePrefix = workerNamePrefix;
2669 this.factory = factory;
2670 this.ueh = handler;
2671 this.config = (parallelism & SMASK) | mode;
2672 long np = (long)(-parallelism); // offset ctl counts
2673 this.ctl = ((np << AC_SHIFT) & AC_MASK) | ((np << TC_SHIFT) & TC_MASK);
2674 }
2675
2676 /**
2677 * Returns the common pool instance. This pool is statically
2678 * constructed; its run state is unaffected by attempts to {@link
2679 * #shutdown} or {@link #shutdownNow}. However this pool and any
2680 * ongoing processing are automatically terminated upon program
2681 * {@link System#exit}. Any program that relies on asynchronous
2682 * task processing to complete before program termination should
2683 * invoke {@code commonPool().}{@link #awaitQuiescence awaitQuiescence},
2684 * before exit.
2685 *
2686 * @return the common pool instance
2687 * @since 1.8
2688 */
2689 public static ForkJoinPool commonPool() {
2690 // assert common != null : "static init error";
2691 return common;
2692 }
2693
2694 // Execution methods
2695
2696 /**
2697 * Performs the given task, returning its result upon completion.
2698 * If the computation encounters an unchecked Exception or Error,
2699 * it is rethrown as the outcome of this invocation. Rethrown
2700 * exceptions behave in the same way as regular exceptions, but,
2701 * when possible, contain stack traces (as displayed for example
2702 * using {@code ex.printStackTrace()}) of both the current thread
2703 * as well as the thread actually encountering the exception;
2704 * minimally only the latter.
2705 *
2706 * @param task the task
2707 * @param <T> the type of the task's result
2708 * @return the task's result
2709 * @throws NullPointerException if the task is null
2710 * @throws RejectedExecutionException if the task cannot be
2711 * scheduled for execution
2712 */
2713 public <T> T invoke(ForkJoinTask<T> task) {
2714 if (task == null)
2715 throw new NullPointerException();
2716 externalSubmit(task);
2717 return task.join();
2718 }
2719
2720 /**
2721 * Arranges for (asynchronous) execution of the given task.
2722 *
2723 * @param task the task
2724 * @throws NullPointerException if the task is null
2725 * @throws RejectedExecutionException if the task cannot be
2726 * scheduled for execution
2727 */
2728 public void execute(ForkJoinTask<?> task) {
2729 externalSubmit(task);
2730 }
2731
2732 // AbstractExecutorService methods
2733
2734 /**
2735 * @throws NullPointerException if the task is null
2736 * @throws RejectedExecutionException if the task cannot be
2737 * scheduled for execution
2738 */
2739 public void execute(Runnable task) {
2740 if (task == null)
2741 throw new NullPointerException();
2742 ForkJoinTask<?> job;
2743 if (task instanceof ForkJoinTask<?>) // avoid re-wrap
2744 job = (ForkJoinTask<?>) task;
2745 else
2746 job = new ForkJoinTask.RunnableExecuteAction(task);
2747 externalSubmit(job);
2748 }
2749
2750 /**
2751 * Submits a ForkJoinTask for execution.
2752 *
2753 * @param task the task to submit
2754 * @param <T> the type of the task's result
2755 * @return the task
2756 * @throws NullPointerException if the task is null
2757 * @throws RejectedExecutionException if the task cannot be
2758 * scheduled for execution
2759 */
2760 public <T> ForkJoinTask<T> submit(ForkJoinTask<T> task) {
2761 return externalSubmit(task);
2762 }
2763
2764 /**
2765 * @throws NullPointerException if the task is null
2766 * @throws RejectedExecutionException if the task cannot be
2767 * scheduled for execution
2768 */
2769 public <T> ForkJoinTask<T> submit(Callable<T> task) {
2770 return externalSubmit(new ForkJoinTask.AdaptedCallable<T>(task));
2771 }
2772
2773 /**
2774 * @throws NullPointerException if the task is null
2775 * @throws RejectedExecutionException if the task cannot be
2776 * scheduled for execution
2777 */
2778 public <T> ForkJoinTask<T> submit(Runnable task, T result) {
2779 return externalSubmit(new ForkJoinTask.AdaptedRunnable<T>(task, result));
2780 }
2781
2782 /**
2783 * @throws NullPointerException if the task is null
2784 * @throws RejectedExecutionException if the task cannot be
2785 * scheduled for execution
2786 */
2787 public ForkJoinTask<?> submit(Runnable task) {
2788 if (task == null)
2789 throw new NullPointerException();
2790 ForkJoinTask<?> job;
2791 if (task instanceof ForkJoinTask<?>) // avoid re-wrap
2792 job = (ForkJoinTask<?>) task;
2793 else
2794 job = new ForkJoinTask.AdaptedRunnableAction(task);
2795 return externalSubmit(job);
2796 }
2797
2798 /**
2799 * @throws NullPointerException {@inheritDoc}
2800 * @throws RejectedExecutionException {@inheritDoc}
2801 */
2802 public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) {
2803 // In previous versions of this class, this method constructed
2804 // a task to run ForkJoinTask.invokeAll, but now external
2805 // invocation of multiple tasks is at least as efficient.
2806 ArrayList<Future<T>> futures = new ArrayList<>(tasks.size());
2807
2808 try {
2809 for (Callable<T> t : tasks) {
2810 ForkJoinTask<T> f = new ForkJoinTask.AdaptedCallable<T>(t);
2811 futures.add(f);
2812 externalSubmit(f);
2813 }
2814 for (int i = 0, size = futures.size(); i < size; i++)
2815 ((ForkJoinTask<?>)futures.get(i)).quietlyJoin();
2816 return futures;
2817 } catch (Throwable t) {
2818 for (int i = 0, size = futures.size(); i < size; i++)
2819 futures.get(i).cancel(false);
2820 throw t;
2821 }
2822 }
2823
2824 /**
2825 * Returns the factory used for constructing new workers.
2826 *
2827 * @return the factory used for constructing new workers
2828 */
2829 public ForkJoinWorkerThreadFactory getFactory() {
2830 return factory;
2831 }
2832
2833 /**
2834 * Returns the handler for internal worker threads that terminate
2835 * due to unrecoverable errors encountered while executing tasks.
2836 *
2837 * @return the handler, or {@code null} if none
2838 */
2839 public UncaughtExceptionHandler getUncaughtExceptionHandler() {
2840 return ueh;
2841 }
2842
2843 /**
2844 * Returns the targeted parallelism level of this pool.
2845 *
2846 * @return the targeted parallelism level of this pool
2847 */
2848 public int getParallelism() {
2849 int par;
2850 return ((par = config & SMASK) > 0) ? par : 1;
2851 }
2852
2853 /**
2854 * Returns the targeted parallelism level of the common pool.
2855 *
2856 * @return the targeted parallelism level of the common pool
2857 * @since 1.8
2858 */
2859 public static int getCommonPoolParallelism() {
2860 return COMMON_PARALLELISM;
2861 }
2862
2863 /**
2864 * Returns the number of worker threads that have started but not
2865 * yet terminated. The result returned by this method may differ
2866 * from {@link #getParallelism} when threads are created to
2867 * maintain parallelism when others are cooperatively blocked.
2868 *
2869 * @return the number of worker threads
2870 */
2871 public int getPoolSize() {
2872 return (config & SMASK) + (short)(ctl >>> TC_SHIFT);
2873 }
2874
2875 /**
2876 * Returns {@code true} if this pool uses local first-in-first-out
2877 * scheduling mode for forked tasks that are never joined.
2878 *
2879 * @return {@code true} if this pool uses async mode
2880 */
2881 public boolean getAsyncMode() {
2882 return (config & FIFO_QUEUE) != 0;
2883 }
2884
2885 /**
2886 * Returns an estimate of the number of worker threads that are
2887 * not blocked waiting to join tasks or for other managed
2888 * synchronization. This method may overestimate the
2889 * number of running threads.
2890 *
2891 * @return the number of worker threads
2892 */
2893 public int getRunningThreadCount() {
2894 int rc = 0;
2895 WorkQueue[] ws; WorkQueue w;
2896 if ((ws = workQueues) != null) {
2897 for (int i = 1; i < ws.length; i += 2) {
2898 if ((w = ws[i]) != null && w.isApparentlyUnblocked())
2899 ++rc;
2900 }
2901 }
2902 return rc;
2903 }
2904
2905 /**
2906 * Returns an estimate of the number of threads that are currently
2907 * stealing or executing tasks. This method may overestimate the
2908 * number of active threads.
2909 *
2910 * @return the number of active threads
2911 */
2912 public int getActiveThreadCount() {
2913 int r = (config & SMASK) + (int)(ctl >> AC_SHIFT);
2914 return (r <= 0) ? 0 : r; // suppress momentarily negative values
2915 }
2916
2917 /**
2918 * Returns {@code true} if all worker threads are currently idle.
2919 * An idle worker is one that cannot obtain a task to execute
2920 * because none are available to steal from other threads, and
2921 * there are no pending submissions to the pool. This method is
2922 * conservative; it might not return {@code true} immediately upon
2923 * idleness of all threads, but will eventually become true if
2924 * threads remain inactive.
2925 *
2926 * @return {@code true} if all threads are currently idle
2927 */
2928 public boolean isQuiescent() {
2929 return (config & SMASK) + (int)(ctl >> AC_SHIFT) <= 0;
2930 }
2931
2932 /**
2933 * Returns an estimate of the total number of tasks stolen from
2934 * one thread's work queue by another. The reported value
2935 * underestimates the actual total number of steals when the pool
2936 * is not quiescent. This value may be useful for monitoring and
2937 * tuning fork/join programs: in general, steal counts should be
2938 * high enough to keep threads busy, but low enough to avoid
2939 * overhead and contention across threads.
2940 *
2941 * @return the number of steals
2942 */
2943 public long getStealCount() {
2944 AuxState sc = auxState;
2945 long count = (sc == null) ? 0L : sc.stealCount;
2946 WorkQueue[] ws; WorkQueue w;
2947 if ((ws = workQueues) != null) {
2948 for (int i = 1; i < ws.length; i += 2) {
2949 if ((w = ws[i]) != null)
2950 count += w.nsteals;
2951 }
2952 }
2953 return count;
2954 }
2955
2956 /**
2957 * Returns an estimate of the total number of tasks currently held
2958 * in queues by worker threads (but not including tasks submitted
2959 * to the pool that have not begun executing). This value is only
2960 * an approximation, obtained by iterating across all threads in
2961 * the pool. This method may be useful for tuning task
2962 * granularities.
2963 *
2964 * @return the number of queued tasks
2965 */
2966 public long getQueuedTaskCount() {
2967 long count = 0;
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.queueSize();
2973 }
2974 }
2975 return count;
2976 }
2977
2978 /**
2979 * Returns an estimate of the number of tasks submitted to this
2980 * pool that have not yet begun executing. This method may take
2981 * time proportional to the number of submissions.
2982 *
2983 * @return the number of queued submissions
2984 */
2985 public int getQueuedSubmissionCount() {
2986 int count = 0;
2987 WorkQueue[] ws; WorkQueue w;
2988 if ((ws = workQueues) != null) {
2989 for (int i = 0; i < ws.length; i += 2) {
2990 if ((w = ws[i]) != null)
2991 count += w.queueSize();
2992 }
2993 }
2994 return count;
2995 }
2996
2997 /**
2998 * Returns {@code true} if there are any tasks submitted to this
2999 * pool that have not yet begun executing.
3000 *
3001 * @return {@code true} if there are any queued submissions
3002 */
3003 public boolean hasQueuedSubmissions() {
3004 WorkQueue[] ws; WorkQueue w;
3005 if ((ws = workQueues) != null) {
3006 for (int i = 0; i < ws.length; i += 2) {
3007 if ((w = ws[i]) != null && !w.isEmpty())
3008 return true;
3009 }
3010 }
3011 return false;
3012 }
3013
3014 /**
3015 * Removes and returns the next unexecuted submission if one is
3016 * available. This method may be useful in extensions to this
3017 * class that re-assign work in systems with multiple pools.
3018 *
3019 * @return the next submission, or {@code null} if none
3020 */
3021 protected ForkJoinTask<?> pollSubmission() {
3022 WorkQueue[] ws; int wl; WorkQueue w; ForkJoinTask<?> t;
3023 int r = ThreadLocalRandom.nextSecondarySeed();
3024 if ((ws = workQueues) != null && (wl = ws.length) > 0) {
3025 for (int m = wl - 1, i = 0; i < wl; ++i) {
3026 if ((w = ws[(i << 1) & m]) != null && (t = w.poll()) != null)
3027 return t;
3028 }
3029 }
3030 return null;
3031 }
3032
3033 /**
3034 * Removes all available unexecuted submitted and forked tasks
3035 * from scheduling queues and adds them to the given collection,
3036 * without altering their execution status. These may include
3037 * artificially generated or wrapped tasks. This method is
3038 * designed to be invoked only when the pool is known to be
3039 * quiescent. Invocations at other times may not remove all
3040 * tasks. A failure encountered while attempting to add elements
3041 * to collection {@code c} may result in elements being in
3042 * neither, either or both collections when the associated
3043 * exception is thrown. The behavior of this operation is
3044 * undefined if the specified collection is modified while the
3045 * operation is in progress.
3046 *
3047 * @param c the collection to transfer elements into
3048 * @return the number of elements transferred
3049 */
3050 protected int drainTasksTo(Collection<? super ForkJoinTask<?>> c) {
3051 int count = 0;
3052 WorkQueue[] ws; WorkQueue w; ForkJoinTask<?> t;
3053 if ((ws = workQueues) != null) {
3054 for (int i = 0; i < ws.length; ++i) {
3055 if ((w = ws[i]) != null) {
3056 while ((t = w.poll()) != null) {
3057 c.add(t);
3058 ++count;
3059 }
3060 }
3061 }
3062 }
3063 return count;
3064 }
3065
3066 /**
3067 * Returns a string identifying this pool, as well as its state,
3068 * including indications of run state, parallelism level, and
3069 * worker and task counts.
3070 *
3071 * @return a string identifying this pool, as well as its state
3072 */
3073 public String toString() {
3074 // Use a single pass through workQueues to collect counts
3075 long qt = 0L, qs = 0L; int rc = 0;
3076 AuxState sc = auxState;
3077 long st = (sc == null) ? 0L : sc.stealCount;
3078 long c = ctl;
3079 WorkQueue[] ws; WorkQueue w;
3080 if ((ws = workQueues) != null) {
3081 for (int i = 0; i < ws.length; ++i) {
3082 if ((w = ws[i]) != null) {
3083 int size = w.queueSize();
3084 if ((i & 1) == 0)
3085 qs += size;
3086 else {
3087 qt += size;
3088 st += w.nsteals;
3089 if (w.isApparentlyUnblocked())
3090 ++rc;
3091 }
3092 }
3093 }
3094 }
3095 int pc = (config & SMASK);
3096 int tc = pc + (short)(c >>> TC_SHIFT);
3097 int ac = pc + (int)(c >> AC_SHIFT);
3098 if (ac < 0) // ignore transient negative
3099 ac = 0;
3100 int rs = runState;
3101 String level = ((rs & TERMINATED) != 0 ? "Terminated" :
3102 (rs & STOP) != 0 ? "Terminating" :
3103 (rs & SHUTDOWN) != 0 ? "Shutting down" :
3104 "Running");
3105 return super.toString() +
3106 "[" + level +
3107 ", parallelism = " + pc +
3108 ", size = " + tc +
3109 ", active = " + ac +
3110 ", running = " + rc +
3111 ", steals = " + st +
3112 ", tasks = " + qt +
3113 ", submissions = " + qs +
3114 "]";
3115 }
3116
3117 /**
3118 * Possibly initiates an orderly shutdown in which previously
3119 * submitted tasks are executed, but no new tasks will be
3120 * accepted. Invocation has no effect on execution state if this
3121 * is the {@link #commonPool()}, and no additional effect if
3122 * already shut down. Tasks that are in the process of being
3123 * submitted concurrently during the course of this method may or
3124 * may not be rejected.
3125 *
3126 * @throws SecurityException if a security manager exists and
3127 * the caller is not permitted to modify threads
3128 * because it does not hold {@link
3129 * java.lang.RuntimePermission}{@code ("modifyThread")}
3130 */
3131 public void shutdown() {
3132 checkPermission();
3133 tryTerminate(false, true);
3134 }
3135
3136 /**
3137 * Possibly attempts to cancel and/or stop all tasks, and reject
3138 * all subsequently submitted tasks. Invocation has no effect on
3139 * execution state if this is the {@link #commonPool()}, and no
3140 * additional effect if already shut down. Otherwise, tasks that
3141 * are in the process of being submitted or executed concurrently
3142 * during the course of this method may or may not be
3143 * rejected. This method cancels both existing and unexecuted
3144 * tasks, in order to permit termination in the presence of task
3145 * dependencies. So the method always returns an empty list
3146 * (unlike the case for some other Executors).
3147 *
3148 * @return an empty list
3149 * @throws SecurityException if a security manager exists and
3150 * the caller is not permitted to modify threads
3151 * because it does not hold {@link
3152 * java.lang.RuntimePermission}{@code ("modifyThread")}
3153 */
3154 public List<Runnable> shutdownNow() {
3155 checkPermission();
3156 tryTerminate(true, true);
3157 return Collections.emptyList();
3158 }
3159
3160 /**
3161 * Returns {@code true} if all tasks have completed following shut down.
3162 *
3163 * @return {@code true} if all tasks have completed following shut down
3164 */
3165 public boolean isTerminated() {
3166 return (runState & TERMINATED) != 0;
3167 }
3168
3169 /**
3170 * Returns {@code true} if the process of termination has
3171 * commenced but not yet completed. This method may be useful for
3172 * debugging. A return of {@code true} reported a sufficient
3173 * period after shutdown may indicate that submitted tasks have
3174 * ignored or suppressed interruption, or are waiting for I/O,
3175 * causing this executor not to properly terminate. (See the
3176 * advisory notes for class {@link ForkJoinTask} stating that
3177 * tasks should not normally entail blocking operations. But if
3178 * they do, they must abort them on interrupt.)
3179 *
3180 * @return {@code true} if terminating but not yet terminated
3181 */
3182 public boolean isTerminating() {
3183 int rs = runState;
3184 return (rs & STOP) != 0 && (rs & TERMINATED) == 0;
3185 }
3186
3187 /**
3188 * Returns {@code true} if this pool has been shut down.
3189 *
3190 * @return {@code true} if this pool has been shut down
3191 */
3192 public boolean isShutdown() {
3193 return (runState & SHUTDOWN) != 0;
3194 }
3195
3196 /**
3197 * Blocks until all tasks have completed execution after a
3198 * shutdown request, or the timeout occurs, or the current thread
3199 * is interrupted, whichever happens first. Because the {@link
3200 * #commonPool()} never terminates until program shutdown, when
3201 * applied to the common pool, this method is equivalent to {@link
3202 * #awaitQuiescence(long, TimeUnit)} but always returns {@code false}.
3203 *
3204 * @param timeout the maximum time to wait
3205 * @param unit the time unit of the timeout argument
3206 * @return {@code true} if this executor terminated and
3207 * {@code false} if the timeout elapsed before termination
3208 * @throws InterruptedException if interrupted while waiting
3209 */
3210 public boolean awaitTermination(long timeout, TimeUnit unit)
3211 throws InterruptedException {
3212 if (Thread.interrupted())
3213 throw new InterruptedException();
3214 if (this == common) {
3215 awaitQuiescence(timeout, unit);
3216 return false;
3217 }
3218 long nanos = unit.toNanos(timeout);
3219 if (isTerminated())
3220 return true;
3221 if (nanos <= 0L)
3222 return false;
3223 long deadline = System.nanoTime() + nanos;
3224 synchronized (this) {
3225 for (;;) {
3226 if (isTerminated())
3227 return true;
3228 if (nanos <= 0L)
3229 return false;
3230 long millis = TimeUnit.NANOSECONDS.toMillis(nanos);
3231 wait(millis > 0L ? millis : 1L);
3232 nanos = deadline - System.nanoTime();
3233 }
3234 }
3235 }
3236
3237 /**
3238 * If called by a ForkJoinTask operating in this pool, equivalent
3239 * in effect to {@link ForkJoinTask#helpQuiesce}. Otherwise,
3240 * waits and/or attempts to assist performing tasks until this
3241 * pool {@link #isQuiescent} or the indicated timeout elapses.
3242 *
3243 * @param timeout the maximum time to wait
3244 * @param unit the time unit of the timeout argument
3245 * @return {@code true} if quiescent; {@code false} if the
3246 * timeout elapsed.
3247 */
3248 public boolean awaitQuiescence(long timeout, TimeUnit unit) {
3249 long nanos = unit.toNanos(timeout);
3250 ForkJoinWorkerThread wt;
3251 Thread thread = Thread.currentThread();
3252 if ((thread instanceof ForkJoinWorkerThread) &&
3253 (wt = (ForkJoinWorkerThread)thread).pool == this) {
3254 helpQuiescePool(wt.workQueue);
3255 return true;
3256 }
3257 long startTime = System.nanoTime();
3258 WorkQueue[] ws;
3259 int r = 0, wl;
3260 boolean found = true;
3261 while (!isQuiescent() && (ws = workQueues) != null &&
3262 (wl = ws.length) > 0) {
3263 if (!found) {
3264 if ((System.nanoTime() - startTime) > nanos)
3265 return false;
3266 Thread.yield(); // cannot block
3267 }
3268 found = false;
3269 for (int m = wl - 1, j = (m + 1) << 2; j >= 0; --j) {
3270 ForkJoinTask<?> t; WorkQueue q; int b, k;
3271 if ((k = r++ & m) <= m && k >= 0 && (q = ws[k]) != null &&
3272 (b = q.base) - q.top < 0) {
3273 found = true;
3274 if ((t = q.pollAt(b)) != null)
3275 t.doExec();
3276 break;
3277 }
3278 }
3279 }
3280 return true;
3281 }
3282
3283 /**
3284 * Waits and/or attempts to assist performing tasks indefinitely
3285 * until the {@link #commonPool()} {@link #isQuiescent}.
3286 */
3287 static void quiesceCommonPool() {
3288 common.awaitQuiescence(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
3289 }
3290
3291 /**
3292 * Interface for extending managed parallelism for tasks running
3293 * in {@link ForkJoinPool}s.
3294 *
3295 * <p>A {@code ManagedBlocker} provides two methods. Method
3296 * {@link #isReleasable} must return {@code true} if blocking is
3297 * not necessary. Method {@link #block} blocks the current thread
3298 * if necessary (perhaps internally invoking {@code isReleasable}
3299 * before actually blocking). These actions are performed by any
3300 * thread invoking {@link ForkJoinPool#managedBlock(ManagedBlocker)}.
3301 * The unusual methods in this API accommodate synchronizers that
3302 * may, but don't usually, block for long periods. Similarly, they
3303 * allow more efficient internal handling of cases in which
3304 * additional workers may be, but usually are not, needed to
3305 * ensure sufficient parallelism. Toward this end,
3306 * implementations of method {@code isReleasable} must be amenable
3307 * to repeated invocation.
3308 *
3309 * <p>For example, here is a ManagedBlocker based on a
3310 * ReentrantLock:
3311 * <pre> {@code
3312 * class ManagedLocker implements ManagedBlocker {
3313 * final ReentrantLock lock;
3314 * boolean hasLock = false;
3315 * ManagedLocker(ReentrantLock lock) { this.lock = lock; }
3316 * public boolean block() {
3317 * if (!hasLock)
3318 * lock.lock();
3319 * return true;
3320 * }
3321 * public boolean isReleasable() {
3322 * return hasLock || (hasLock = lock.tryLock());
3323 * }
3324 * }}</pre>
3325 *
3326 * <p>Here is a class that possibly blocks waiting for an
3327 * item on a given queue:
3328 * <pre> {@code
3329 * class QueueTaker<E> implements ManagedBlocker {
3330 * final BlockingQueue<E> queue;
3331 * volatile E item = null;
3332 * QueueTaker(BlockingQueue<E> q) { this.queue = q; }
3333 * public boolean block() throws InterruptedException {
3334 * if (item == null)
3335 * item = queue.take();
3336 * return true;
3337 * }
3338 * public boolean isReleasable() {
3339 * return item != null || (item = queue.poll()) != null;
3340 * }
3341 * public E getItem() { // call after pool.managedBlock completes
3342 * return item;
3343 * }
3344 * }}</pre>
3345 */
3346 public static interface ManagedBlocker {
3347 /**
3348 * Possibly blocks the current thread, for example waiting for
3349 * a lock or condition.
3350 *
3351 * @return {@code true} if no additional blocking is necessary
3352 * (i.e., if isReleasable would return true)
3353 * @throws InterruptedException if interrupted while waiting
3354 * (the method is not required to do so, but is allowed to)
3355 */
3356 boolean block() throws InterruptedException;
3357
3358 /**
3359 * Returns {@code true} if blocking is unnecessary.
3360 * @return {@code true} if blocking is unnecessary
3361 */
3362 boolean isReleasable();
3363 }
3364
3365 /**
3366 * Runs the given possibly blocking task. When {@linkplain
3367 * ForkJoinTask#inForkJoinPool() running in a ForkJoinPool}, this
3368 * method possibly arranges for a spare thread to be activated if
3369 * necessary to ensure sufficient parallelism while the current
3370 * thread is blocked in {@link ManagedBlocker#block blocker.block()}.
3371 *
3372 * <p>This method repeatedly calls {@code blocker.isReleasable()} and
3373 * {@code blocker.block()} until either method returns {@code true}.
3374 * Every call to {@code blocker.block()} is preceded by a call to
3375 * {@code blocker.isReleasable()} that returned {@code false}.
3376 *
3377 * <p>If not running in a ForkJoinPool, this method is
3378 * behaviorally equivalent to
3379 * <pre> {@code
3380 * while (!blocker.isReleasable())
3381 * if (blocker.block())
3382 * break;}</pre>
3383 *
3384 * If running in a ForkJoinPool, the pool may first be expanded to
3385 * ensure sufficient parallelism available during the call to
3386 * {@code blocker.block()}.
3387 *
3388 * @param blocker the blocker task
3389 * @throws InterruptedException if {@code blocker.block()} did so
3390 */
3391 public static void managedBlock(ManagedBlocker blocker)
3392 throws InterruptedException {
3393 ForkJoinPool p;
3394 ForkJoinWorkerThread wt;
3395 Thread t = Thread.currentThread();
3396 if ((t instanceof ForkJoinWorkerThread) &&
3397 (p = (wt = (ForkJoinWorkerThread)t).pool) != null) {
3398 WorkQueue w = wt.workQueue;
3399 while (!blocker.isReleasable()) {
3400 if (p.tryCompensate(w)) {
3401 try {
3402 do {} while (!blocker.isReleasable() &&
3403 !blocker.block());
3404 } finally {
3405 U.getAndAddLong(p, CTL, AC_UNIT);
3406 }
3407 break;
3408 }
3409 }
3410 }
3411 else {
3412 do {} while (!blocker.isReleasable() &&
3413 !blocker.block());
3414 }
3415 }
3416
3417 // AbstractExecutorService overrides. These rely on undocumented
3418 // fact that ForkJoinTask.adapt returns ForkJoinTasks that also
3419 // implement RunnableFuture.
3420
3421 protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
3422 return new ForkJoinTask.AdaptedRunnable<T>(runnable, value);
3423 }
3424
3425 protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
3426 return new ForkJoinTask.AdaptedCallable<T>(callable);
3427 }
3428
3429 // Unsafe mechanics
3430 private static final sun.misc.Unsafe U = sun.misc.Unsafe.getUnsafe();
3431 private static final long CTL;
3432 private static final long RUNSTATE;
3433 private static final int ABASE;
3434 private static final int ASHIFT;
3435
3436 static {
3437 try {
3438 CTL = U.objectFieldOffset
3439 (ForkJoinPool.class.getDeclaredField("ctl"));
3440 RUNSTATE = U.objectFieldOffset
3441 (ForkJoinPool.class.getDeclaredField("runState"));
3442 ABASE = U.arrayBaseOffset(ForkJoinTask[].class);
3443 int scale = U.arrayIndexScale(ForkJoinTask[].class);
3444 if ((scale & (scale - 1)) != 0)
3445 throw new Error("array index scale not a power of two");
3446 ASHIFT = 31 - Integer.numberOfLeadingZeros(scale);
3447 } catch (ReflectiveOperationException e) {
3448 throw new Error(e);
3449 }
3450
3451 // Reduce the risk of rare disastrous classloading in first call to
3452 // LockSupport.park: https://bugs.openjdk.java.net/browse/JDK-8074773
3453 Class<?> ensureLoaded = LockSupport.class;
3454
3455 int commonMaxSpares = DEFAULT_COMMON_MAX_SPARES;
3456 try {
3457 String p = System.getProperty
3458 ("java.util.concurrent.ForkJoinPool.common.maximumSpares");
3459 if (p != null)
3460 commonMaxSpares = Integer.parseInt(p);
3461 } catch (Exception ignore) {}
3462 COMMON_MAX_SPARES = commonMaxSpares;
3463
3464 defaultForkJoinWorkerThreadFactory =
3465 new DefaultForkJoinWorkerThreadFactory();
3466 modifyThreadPermission = new RuntimePermission("modifyThread");
3467
3468 common = java.security.AccessController.doPrivileged
3469 (new java.security.PrivilegedAction<ForkJoinPool>() {
3470 public ForkJoinPool run() { return makeCommonPool(); }});
3471
3472 // report 1 even if threads disabled
3473 COMMON_PARALLELISM = Math.max(common.config & SMASK, 1);
3474 }
3475
3476 /**
3477 * Creates and returns the common pool, respecting user settings
3478 * specified via system properties.
3479 */
3480 static ForkJoinPool makeCommonPool() {
3481 int parallelism = -1;
3482 ForkJoinWorkerThreadFactory factory = null;
3483 UncaughtExceptionHandler handler = null;
3484 try { // ignore exceptions in accessing/parsing properties
3485 String pp = System.getProperty
3486 ("java.util.concurrent.ForkJoinPool.common.parallelism");
3487 String fp = System.getProperty
3488 ("java.util.concurrent.ForkJoinPool.common.threadFactory");
3489 String hp = System.getProperty
3490 ("java.util.concurrent.ForkJoinPool.common.exceptionHandler");
3491 if (pp != null)
3492 parallelism = Integer.parseInt(pp);
3493 if (fp != null)
3494 factory = ((ForkJoinWorkerThreadFactory)ClassLoader.
3495 getSystemClassLoader().loadClass(fp).newInstance());
3496 if (hp != null)
3497 handler = ((UncaughtExceptionHandler)ClassLoader.
3498 getSystemClassLoader().loadClass(hp).newInstance());
3499 } catch (Exception ignore) {
3500 }
3501 if (factory == null) {
3502 if (System.getSecurityManager() == null)
3503 factory = defaultForkJoinWorkerThreadFactory;
3504 else // use security-managed default
3505 factory = new InnocuousForkJoinWorkerThreadFactory();
3506 }
3507 if (parallelism < 0 && // default 1 less than #cores
3508 (parallelism = Runtime.getRuntime().availableProcessors() - 1) <= 0)
3509 parallelism = 1;
3510 if (parallelism > MAX_CAP)
3511 parallelism = MAX_CAP;
3512 return new ForkJoinPool(parallelism, factory, handler, LIFO_QUEUE,
3513 "ForkJoinPool.commonPool-worker-");
3514 }
3515
3516 /**
3517 * Factory for innocuous worker threads.
3518 */
3519 private static final class InnocuousForkJoinWorkerThreadFactory
3520 implements ForkJoinWorkerThreadFactory {
3521
3522 /**
3523 * An ACC to restrict permissions for the factory itself.
3524 * The constructed workers have no permissions set.
3525 */
3526 private static final AccessControlContext innocuousAcc;
3527 static {
3528 Permissions innocuousPerms = new Permissions();
3529 innocuousPerms.add(modifyThreadPermission);
3530 innocuousPerms.add(new RuntimePermission(
3531 "enableContextClassLoaderOverride"));
3532 innocuousPerms.add(new RuntimePermission(
3533 "modifyThreadGroup"));
3534 innocuousAcc = new AccessControlContext(new ProtectionDomain[] {
3535 new ProtectionDomain(null, innocuousPerms)
3536 });
3537 }
3538
3539 public final ForkJoinWorkerThread newThread(ForkJoinPool pool) {
3540 return java.security.AccessController.doPrivileged(
3541 new java.security.PrivilegedAction<ForkJoinWorkerThread>() {
3542 public ForkJoinWorkerThread run() {
3543 return new ForkJoinWorkerThread.
3544 InnocuousForkJoinWorkerThread(pool);
3545 }}, innocuousAcc);
3546 }
3547 }
3548
3549 }