ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinPool.java
Revision: 1.157
Committed: Mon Feb 11 08:09:37 2013 UTC (11 years, 3 months ago) by jsr166
Branch: MAIN
Changes since 1.156: +3 -3 lines
Log Message:
javadoc link readability

File Contents

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