ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinPool.java
Revision: 1.224
Committed: Sat Sep 13 16:11:45 2014 UTC (9 years, 8 months ago) by dl
Branch: MAIN
Changes since 1.223: +73 -54 lines
Log Message:
Add explicit length checks

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