ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinPool.java
Revision: 1.210
Committed: Fri Jul 11 16:10:38 2014 UTC (9 years, 10 months ago) by dl
Branch: MAIN
Changes since 1.209: +98 -75 lines
Log Message:
Exception compatibility

File Contents

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