ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinPool.java
Revision: 1.196
Committed: Mon Dec 9 17:00:23 2013 UTC (10 years, 5 months ago) by jsr166
Branch: MAIN
Changes since 1.195: +1 -2 lines
Log Message:
use the one true code snippet style

File Contents

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