ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jsr166e/ForkJoinPool.java
Revision: 1.11
Committed: Wed Oct 31 12:49:13 2012 UTC (11 years, 6 months ago) by dl
Branch: MAIN
Changes since 1.10: +94 -113 lines
Log Message:
commonPool improvements

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