ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinPool.java
Revision: 1.199
Committed: Sun May 25 02:33:45 2014 UTC (10 years ago) by jsr166
Branch: MAIN
Changes since 1.198: +1 -1 lines
Log Message:
time to start using diamond <>

File Contents

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