ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinPool.java
Revision: 1.171
Committed: Fri Mar 22 22:03:11 2013 UTC (11 years, 2 months ago) by jsr166
Branch: MAIN
Changes since 1.170: +2 -2 lines
Log Message:
remove obsolescent comment

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