ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinPool.java
Revision: 1.214
Committed: Sun Jul 13 18:42:13 2014 UTC (9 years, 10 months ago) by jsr166
Branch: MAIN
Changes since 1.213: +3 -3 lines
Log Message:
whitespace

File Contents

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