ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinPool.java
Revision: 1.97
Committed: Mon Aug 13 18:25:53 2012 UTC (11 years, 9 months ago) by jsr166
Branch: MAIN
Changes since 1.96: +1 -1 lines
Log Message:
typos

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