ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinPool.java
Revision: 1.203
Committed: Mon Jul 7 23:19:05 2014 UTC (9 years, 10 months ago) by dl
Branch: MAIN
Changes since 1.202: +12 -2 lines
Log Message:
Revive submission check for termination

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