ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jdk7/java/util/concurrent/ForkJoinPool.java
Revision: 1.28
Committed: Thu Nov 5 16:47:35 2015 UTC (8 years, 6 months ago) by jsr166
Branch: MAIN
CVS Tags: HEAD
Changes since 1.27: +1 -1 lines
Log Message:
fix javac [rawtypes] warning

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