ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinPool.java
Revision: 1.231
Committed: Sun Jan 4 01:06:15 2015 UTC (9 years, 5 months ago) by jsr166
Branch: MAIN
Changes since 1.230: +2 -2 lines
Log Message:
use ReflectiveOperationException for Unsafe mechanics

File Contents

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