ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinPool.java
Revision: 1.164
Committed: Fri Feb 22 01:11:48 2013 UTC (11 years, 3 months ago) by dl
Branch: MAIN
Changes since 1.163: +1 -0 lines
Log Message:
Spec clarification

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