ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinPool.java
Revision: 1.253
Committed: Mon Aug 3 16:30:37 2015 UTC (8 years, 10 months ago) by dl
Branch: MAIN
Changes since 1.252: +130 -83 lines
Log Message:
better fairness tradeoffs; other touchups

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