ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinPool.java
Revision: 1.209
Committed: Thu Jul 10 16:00:59 2014 UTC (9 years, 11 months ago) by dl
Branch: MAIN
Changes since 1.208: +47 -32 lines
Log Message:
Max spares settable; termination compatibility

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