ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinPool.java
Revision: 1.226
Committed: Wed Dec 3 23:57:07 2014 UTC (9 years, 6 months ago) by jsr166
Branch: MAIN
Changes since 1.225: +4 -6 lines
Log Message:
remove boolean done flag in invokeAll by converting to Throwable rethrow

File Contents

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