ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinPool.java
Revision: 1.163
Committed: Sat Feb 16 20:50:29 2013 UTC (11 years, 3 months ago) by jsr166
Branch: MAIN
Changes since 1.162: +1 -1 lines
Log Message:
javadoc comment correctness

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