ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinPool.java
Revision: 1.259
Committed: Sat Aug 8 17:47:32 2015 UTC (8 years, 9 months ago) by jsr166
Branch: MAIN
Changes since 1.258: +4 -4 lines
Log Message:
whitespace

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