ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jsr166e/ForkJoinPool.java
Revision: 1.8
Committed: Mon Oct 29 17:23:26 2012 UTC (11 years, 6 months ago) by dl
Branch: MAIN
Changes since 1.7: +216 -163 lines
Log Message:
Reduce common pool footprint

File Contents

# User Rev Content
1 dl 1.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 dl 1.7
9 dl 1.1 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 dl 1.7 import java.util.concurrent.ThreadLocalRandom;
22 dl 1.1 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 dl 1.7 * <p>A static {@link #commonPool} is available and appropriate for
47 dl 1.8 * 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 dl 1.7 * 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 dl 1.1 * 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 dl 1.8 * "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 dl 1.1 *
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 dl 1.7 * 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 dl 1.1 *
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. (We do not have a shared
696     * version of this method because it is never needed.)
697     */
698     final ForkJoinTask<?> pop() {
699     ForkJoinTask<?>[] a; ForkJoinTask<?> t; int m;
700     if ((a = array) != null && (m = a.length - 1) >= 0) {
701     for (int s; (s = top - 1) - base >= 0;) {
702     long j = ((m & s) << ASHIFT) + ABASE;
703     if ((t = (ForkJoinTask<?>)U.getObject(a, j)) == null)
704     break;
705     if (U.compareAndSwapObject(a, j, t, null)) {
706     top = s;
707     return t;
708     }
709     }
710     }
711     return null;
712     }
713    
714     /**
715     * Takes a task in FIFO order if b is base of queue and a task
716     * can be claimed without contention. Specialized versions
717     * appear in ForkJoinPool methods scan and tryHelpStealer.
718     */
719     final ForkJoinTask<?> pollAt(int b) {
720     ForkJoinTask<?> t; ForkJoinTask<?>[] a;
721     if ((a = array) != null) {
722     int j = (((a.length - 1) & b) << ASHIFT) + ABASE;
723     if ((t = (ForkJoinTask<?>)U.getObjectVolatile(a, j)) != null &&
724     base == b &&
725     U.compareAndSwapObject(a, j, t, null)) {
726     base = b + 1;
727     return t;
728     }
729     }
730     return null;
731     }
732    
733     /**
734     * Takes next task, if one exists, in FIFO order.
735     */
736     final ForkJoinTask<?> poll() {
737     ForkJoinTask<?>[] a; int b; ForkJoinTask<?> t;
738     while ((b = base) - top < 0 && (a = array) != null) {
739     int j = (((a.length - 1) & b) << ASHIFT) + ABASE;
740     t = (ForkJoinTask<?>)U.getObjectVolatile(a, j);
741     if (t != null) {
742     if (base == b &&
743     U.compareAndSwapObject(a, j, t, null)) {
744     base = b + 1;
745     return t;
746     }
747     }
748     else if (base == b) {
749     if (b + 1 == top)
750     break;
751     Thread.yield(); // wait for lagging update
752     }
753     }
754     return null;
755     }
756    
757     /**
758     * Takes next task, if one exists, in order specified by mode.
759     */
760     final ForkJoinTask<?> nextLocalTask() {
761     return mode == 0 ? pop() : poll();
762     }
763    
764     /**
765     * Returns next task, if one exists, in order specified by mode.
766     */
767     final ForkJoinTask<?> peek() {
768     ForkJoinTask<?>[] a = array; int m;
769     if (a == null || (m = a.length - 1) < 0)
770     return null;
771     int i = mode == 0 ? top - 1 : base;
772     int j = ((i & m) << ASHIFT) + ABASE;
773     return (ForkJoinTask<?>)U.getObjectVolatile(a, j);
774     }
775    
776     /**
777     * Pops the given task only if it is at the current top.
778     */
779     final boolean tryUnpush(ForkJoinTask<?> t) {
780     ForkJoinTask<?>[] a; int s;
781     if ((a = array) != null && (s = top) != base &&
782     U.compareAndSwapObject
783     (a, (((a.length - 1) & --s) << ASHIFT) + ABASE, t, null)) {
784     top = s;
785     return true;
786     }
787     return false;
788     }
789    
790     /**
791 dl 1.7 * Version of tryUnpush for shared queues; called by non-FJ
792 dl 1.8 * submitters after prechecking that task probably exists.
793 dl 1.7 */
794 dl 1.8 final boolean trySharedUnpush(ForkJoinTask<?> t) {
795 dl 1.7 boolean success = false;
796 dl 1.8 if (runState == 0 && U.compareAndSwapInt(this, RUNSTATE, 0, 1)) {
797 dl 1.7 try {
798 dl 1.8 ForkJoinTask<?>[] a; int s;
799     if ((a = array) != null && (s = top) != base &&
800     U.compareAndSwapObject
801     (a, (((a.length - 1) & --s) << ASHIFT) + ABASE, t, null)) {
802     top = s;
803     success = true;
804 dl 1.7 }
805     } finally {
806     runState = 0; // unlock
807     }
808     }
809     return success;
810     }
811    
812     /**
813 dl 1.1 * Polls the given task only if it is at the current base.
814     */
815     final boolean pollFor(ForkJoinTask<?> task) {
816     ForkJoinTask<?>[] a; int b;
817     if ((b = base) - top < 0 && (a = array) != null) {
818     int j = (((a.length - 1) & b) << ASHIFT) + ABASE;
819     if (U.getObjectVolatile(a, j) == task && base == b &&
820     U.compareAndSwapObject(a, j, task, null)) {
821     base = b + 1;
822     return true;
823     }
824     }
825     return false;
826     }
827    
828     /**
829     * Initializes or doubles the capacity of array. Call either
830     * by owner or with lock held -- it is OK for base, but not
831     * top, to move while resizings are in progress.
832     *
833     * @param rejectOnFailure if true, throw exception if capacity
834     * exceeded (relayed ultimately to user); else return null.
835     */
836     final ForkJoinTask<?>[] growArray(boolean rejectOnFailure) {
837     ForkJoinTask<?>[] oldA = array;
838     int size = oldA != null ? oldA.length << 1 : INITIAL_QUEUE_CAPACITY;
839     if (size <= MAXIMUM_QUEUE_CAPACITY) {
840     int oldMask, t, b;
841     ForkJoinTask<?>[] a = array = new ForkJoinTask<?>[size];
842     if (oldA != null && (oldMask = oldA.length - 1) >= 0 &&
843     (t = top) - (b = base) > 0) {
844     int mask = size - 1;
845     do {
846     ForkJoinTask<?> x;
847     int oldj = ((b & oldMask) << ASHIFT) + ABASE;
848     int j = ((b & mask) << ASHIFT) + ABASE;
849     x = (ForkJoinTask<?>)U.getObjectVolatile(oldA, oldj);
850     if (x != null &&
851     U.compareAndSwapObject(oldA, oldj, x, null))
852     U.putObjectVolatile(a, j, x);
853     } while (++b != t);
854     }
855     return a;
856     }
857     else if (!rejectOnFailure)
858     return null;
859     else
860     throw new RejectedExecutionException("Queue capacity exceeded");
861     }
862    
863     /**
864     * Removes and cancels all known tasks, ignoring any exceptions.
865     */
866     final void cancelAll() {
867     ForkJoinTask.cancelIgnoringExceptions(currentJoin);
868     ForkJoinTask.cancelIgnoringExceptions(currentSteal);
869     for (ForkJoinTask<?> t; (t = poll()) != null; )
870     ForkJoinTask.cancelIgnoringExceptions(t);
871     }
872    
873     /**
874     * Computes next value for random probes. Scans don't require
875     * a very high quality generator, but also not a crummy one.
876     * Marsaglia xor-shift is cheap and works well enough. Note:
877     * This is manually inlined in its usages in ForkJoinPool to
878     * avoid writes inside busy scan loops.
879     */
880     final int nextSeed() {
881     int r = seed;
882     r ^= r << 13;
883     r ^= r >>> 17;
884     return seed = r ^= r << 5;
885     }
886    
887     // Execution methods
888    
889     /**
890     * Pops and runs tasks until empty.
891     */
892     private void popAndExecAll() {
893     // A bit faster than repeated pop calls
894     ForkJoinTask<?>[] a; int m, s; long j; ForkJoinTask<?> t;
895     while ((a = array) != null && (m = a.length - 1) >= 0 &&
896     (s = top - 1) - base >= 0 &&
897     (t = ((ForkJoinTask<?>)
898     U.getObject(a, j = ((m & s) << ASHIFT) + ABASE)))
899     != null) {
900     if (U.compareAndSwapObject(a, j, t, null)) {
901     top = s;
902     t.doExec();
903     }
904     }
905     }
906    
907     /**
908     * Polls and runs tasks until empty.
909     */
910     private void pollAndExecAll() {
911     for (ForkJoinTask<?> t; (t = poll()) != null;)
912     t.doExec();
913     }
914    
915     /**
916     * If present, removes from queue and executes the given task, or
917     * any other cancelled task. Returns (true) immediately on any CAS
918     * or consistency check failure so caller can retry.
919     *
920     * @return 0 if no progress can be made, else positive
921     * (this unusual convention simplifies use with tryHelpStealer.)
922     */
923     final int tryRemoveAndExec(ForkJoinTask<?> task) {
924     int stat = 1;
925     boolean removed = false, empty = true;
926     ForkJoinTask<?>[] a; int m, s, b, n;
927     if ((a = array) != null && (m = a.length - 1) >= 0 &&
928     (n = (s = top) - (b = base)) > 0) {
929     for (ForkJoinTask<?> t;;) { // traverse from s to b
930     int j = ((--s & m) << ASHIFT) + ABASE;
931     t = (ForkJoinTask<?>)U.getObjectVolatile(a, j);
932     if (t == null) // inconsistent length
933     break;
934     else if (t == task) {
935     if (s + 1 == top) { // pop
936     if (!U.compareAndSwapObject(a, j, task, null))
937     break;
938     top = s;
939     removed = true;
940     }
941     else if (base == b) // replace with proxy
942     removed = U.compareAndSwapObject(a, j, task,
943     new EmptyTask());
944     break;
945     }
946     else if (t.status >= 0)
947     empty = false;
948     else if (s + 1 == top) { // pop and throw away
949     if (U.compareAndSwapObject(a, j, t, null))
950     top = s;
951     break;
952     }
953     if (--n == 0) {
954     if (!empty && base == b)
955     stat = 0;
956     break;
957     }
958     }
959     }
960     if (removed)
961     task.doExec();
962     return stat;
963     }
964    
965     /**
966     * Executes a top-level task and any local tasks remaining
967     * after execution.
968     */
969     final void runTask(ForkJoinTask<?> t) {
970     if (t != null) {
971     currentSteal = t;
972     t.doExec();
973     if (top != base) { // process remaining local tasks
974     if (mode == 0)
975     popAndExecAll();
976     else
977     pollAndExecAll();
978     }
979     ++nsteals;
980     currentSteal = null;
981     }
982     }
983    
984     /**
985     * Executes a non-top-level (stolen) task.
986     */
987     final void runSubtask(ForkJoinTask<?> t) {
988     if (t != null) {
989     ForkJoinTask<?> ps = currentSteal;
990     currentSteal = t;
991     t.doExec();
992     currentSteal = ps;
993     }
994     }
995    
996     /**
997     * Returns true if owned and not known to be blocked.
998     */
999     final boolean isApparentlyUnblocked() {
1000     Thread wt; Thread.State s;
1001     return (eventCount >= 0 &&
1002     (wt = owner) != null &&
1003     (s = wt.getState()) != Thread.State.BLOCKED &&
1004     s != Thread.State.WAITING &&
1005     s != Thread.State.TIMED_WAITING);
1006     }
1007    
1008     /**
1009     * If this owned and is not already interrupted, try to
1010     * interrupt and/or unpark, ignoring exceptions.
1011     */
1012     final void interruptOwner() {
1013     Thread wt, p;
1014     if ((wt = owner) != null && !wt.isInterrupted()) {
1015     try {
1016     wt.interrupt();
1017     } catch (SecurityException ignore) {
1018     }
1019     }
1020     if ((p = parker) != null)
1021     U.unpark(p);
1022     }
1023    
1024     // Unsafe mechanics
1025     private static final sun.misc.Unsafe U;
1026     private static final long RUNSTATE;
1027     private static final int ABASE;
1028     private static final int ASHIFT;
1029     static {
1030     int s;
1031     try {
1032     U = getUnsafe();
1033     Class<?> k = WorkQueue.class;
1034     Class<?> ak = ForkJoinTask[].class;
1035     RUNSTATE = U.objectFieldOffset
1036     (k.getDeclaredField("runState"));
1037     ABASE = U.arrayBaseOffset(ak);
1038     s = U.arrayIndexScale(ak);
1039     } catch (Exception e) {
1040     throw new Error(e);
1041     }
1042     if ((s & (s-1)) != 0)
1043     throw new Error("data type scale not a power of two");
1044     ASHIFT = 31 - Integer.numberOfLeadingZeros(s);
1045     }
1046     }
1047 jsr166 1.3
1048 dl 1.1 /**
1049     * Per-thread records for threads that submit to pools. Currently
1050     * holds only pseudo-random seed / index that is used to choose
1051     * submission queues in method doSubmit. In the future, this may
1052     * also incorporate a means to implement different task rejection
1053     * and resubmission policies.
1054     *
1055     * Seeds for submitters and workers/workQueues work in basically
1056     * the same way but are initialized and updated using slightly
1057     * different mechanics. Both are initialized using the same
1058     * approach as in class ThreadLocal, where successive values are
1059     * unlikely to collide with previous values. This is done during
1060     * registration for workers, but requires a separate AtomicInteger
1061     * for submitters. Seeds are then randomly modified upon
1062     * collisions using xorshifts, which requires a non-zero seed.
1063     */
1064     static final class Submitter {
1065     int seed;
1066     Submitter() {
1067     int s = nextSubmitterSeed.getAndAdd(SEED_INCREMENT);
1068     seed = (s == 0) ? 1 : s; // ensure non-zero
1069     }
1070     }
1071    
1072     /** ThreadLocal class for Submitters */
1073     static final class ThreadSubmitter extends ThreadLocal<Submitter> {
1074     public Submitter initialValue() { return new Submitter(); }
1075     }
1076    
1077     // static fields (initialized in static initializer below)
1078    
1079     /**
1080     * Creates a new ForkJoinWorkerThread. This factory is used unless
1081     * overridden in ForkJoinPool constructors.
1082     */
1083     public static final ForkJoinWorkerThreadFactory
1084     defaultForkJoinWorkerThreadFactory;
1085    
1086 dl 1.8
1087     /** Property prefix for constructing common pool */
1088     private static final String propPrefix =
1089     "java.util.concurrent.ForkJoinPool.common.";
1090    
1091     /**
1092     * Common (static) pool. Non-null for public use unless a static
1093     * construction exception, but internal usages must null-check on
1094     * use.
1095     */
1096     static final ForkJoinPool commonPool;
1097    
1098     /**
1099     * Common pool parallelism. Must equal commonPool.parallelism.
1100     */
1101     static final int commonPoolParallelism;
1102    
1103 dl 1.1 /**
1104     * Generator for assigning sequence numbers as pool names.
1105     */
1106     private static final AtomicInteger poolNumberGenerator;
1107    
1108     /**
1109     * Generator for initial hashes/seeds for submitters. Accessed by
1110     * Submitter class constructor.
1111     */
1112     static final AtomicInteger nextSubmitterSeed;
1113    
1114     /**
1115     * Permission required for callers of methods that may start or
1116     * kill threads.
1117     */
1118     private static final RuntimePermission modifyThreadPermission;
1119    
1120     /**
1121 jsr166 1.2 * Per-thread submission bookkeeping. Shared across all pools
1122 dl 1.1 * to reduce ThreadLocal pollution and because random motion
1123     * to avoid contention in one pool is likely to hold for others.
1124     */
1125     private static final ThreadSubmitter submitters;
1126    
1127     // static constants
1128    
1129     /**
1130 dl 1.8 * Initial timeout value (in nanoseconds) for the thread triggering
1131 dl 1.7 * quiescence to park waiting for new work. On timeout, the thread
1132     * will instead try to shrink the number of workers.
1133 dl 1.1 */
1134 dl 1.7 private static final long IDLE_TIMEOUT = 1000L * 1000L * 1000L; // 1sec
1135 dl 1.1
1136     /**
1137 dl 1.7 * Timeout value when there are more threads than parallelism level
1138 dl 1.1 */
1139 dl 1.7 private static final long FAST_IDLE_TIMEOUT = 100L * 1000L * 1000L;
1140 dl 1.1
1141     /**
1142     * The maximum stolen->joining link depth allowed in method
1143     * tryHelpStealer. Must be a power of two. This value also
1144     * controls the maximum number of times to try to help join a task
1145     * without any apparent progress or change in pool state before
1146     * giving up and blocking (see awaitJoin). Depths for legitimate
1147     * chains are unbounded, but we use a fixed constant to avoid
1148     * (otherwise unchecked) cycles and to bound staleness of
1149     * traversal parameters at the expense of sometimes blocking when
1150     * we could be helping.
1151     */
1152     private static final int MAX_HELP = 64;
1153    
1154     /**
1155     * Secondary time-based bound (in nanosecs) for helping attempts
1156     * before trying compensated blocking in awaitJoin. Used in
1157     * conjunction with MAX_HELP to reduce variance due to different
1158     * polling rates associated with different helping options. The
1159     * value should roughly approximate the time required to create
1160     * and/or activate a worker thread.
1161     */
1162     private static final long COMPENSATION_DELAY = 1L << 18; // ~0.25 millisec
1163    
1164     /**
1165     * Increment for seed generators. See class ThreadLocal for
1166     * explanation.
1167     */
1168     private static final int SEED_INCREMENT = 0x61c88647;
1169    
1170     /**
1171     * Bits and masks for control variables
1172     *
1173     * Field ctl is a long packed with:
1174     * AC: Number of active running workers minus target parallelism (16 bits)
1175     * TC: Number of total workers minus target parallelism (16 bits)
1176     * ST: true if pool is terminating (1 bit)
1177     * EC: the wait count of top waiting thread (15 bits)
1178     * ID: poolIndex of top of Treiber stack of waiters (16 bits)
1179     *
1180     * When convenient, we can extract the upper 32 bits of counts and
1181     * the lower 32 bits of queue state, u = (int)(ctl >>> 32) and e =
1182     * (int)ctl. The ec field is never accessed alone, but always
1183     * together with id and st. The offsets of counts by the target
1184     * parallelism and the positionings of fields makes it possible to
1185     * perform the most common checks via sign tests of fields: When
1186     * ac is negative, there are not enough active workers, when tc is
1187     * negative, there are not enough total workers, and when e is
1188     * negative, the pool is terminating. To deal with these possibly
1189     * negative fields, we use casts in and out of "short" and/or
1190     * signed shifts to maintain signedness.
1191     *
1192     * When a thread is queued (inactivated), its eventCount field is
1193     * set negative, which is the only way to tell if a worker is
1194     * prevented from executing tasks, even though it must continue to
1195     * scan for them to avoid queuing races. Note however that
1196     * eventCount updates lag releases so usage requires care.
1197     *
1198     * Field runState is an int packed with:
1199     * SHUTDOWN: true if shutdown is enabled (1 bit)
1200     * SEQ: a sequence number updated upon (de)registering workers (30 bits)
1201     * INIT: set true after workQueues array construction (1 bit)
1202     *
1203     * The sequence number enables simple consistency checks:
1204     * Staleness of read-only operations on the workQueues array can
1205     * be checked by comparing runState before vs after the reads.
1206     */
1207    
1208     // bit positions/shifts for fields
1209     private static final int AC_SHIFT = 48;
1210     private static final int TC_SHIFT = 32;
1211     private static final int ST_SHIFT = 31;
1212     private static final int EC_SHIFT = 16;
1213    
1214     // bounds
1215     private static final int SMASK = 0xffff; // short bits
1216     private static final int MAX_CAP = 0x7fff; // max #workers - 1
1217     private static final int SQMASK = 0xfffe; // even short bits
1218     private static final int SHORT_SIGN = 1 << 15;
1219     private static final int INT_SIGN = 1 << 31;
1220    
1221     // masks
1222     private static final long STOP_BIT = 0x0001L << ST_SHIFT;
1223     private static final long AC_MASK = ((long)SMASK) << AC_SHIFT;
1224     private static final long TC_MASK = ((long)SMASK) << TC_SHIFT;
1225    
1226     // units for incrementing and decrementing
1227     private static final long TC_UNIT = 1L << TC_SHIFT;
1228     private static final long AC_UNIT = 1L << AC_SHIFT;
1229    
1230     // masks and units for dealing with u = (int)(ctl >>> 32)
1231     private static final int UAC_SHIFT = AC_SHIFT - 32;
1232     private static final int UTC_SHIFT = TC_SHIFT - 32;
1233     private static final int UAC_MASK = SMASK << UAC_SHIFT;
1234     private static final int UTC_MASK = SMASK << UTC_SHIFT;
1235     private static final int UAC_UNIT = 1 << UAC_SHIFT;
1236     private static final int UTC_UNIT = 1 << UTC_SHIFT;
1237    
1238     // masks and units for dealing with e = (int)ctl
1239     private static final int E_MASK = 0x7fffffff; // no STOP_BIT
1240     private static final int E_SEQ = 1 << EC_SHIFT;
1241    
1242     // runState bits
1243     private static final int SHUTDOWN = 1 << 31;
1244    
1245     // access mode for WorkQueue
1246     static final int LIFO_QUEUE = 0;
1247     static final int FIFO_QUEUE = 1;
1248     static final int SHARED_QUEUE = -1;
1249    
1250     // Instance fields
1251    
1252     /*
1253     * Field layout order in this class tends to matter more than one
1254     * would like. Runtime layout order is only loosely related to
1255     * declaration order and may differ across JVMs, but the following
1256     * empirically works OK on current JVMs.
1257     */
1258    
1259 dl 1.8 volatile long stealCount; // collects worker counts
1260 dl 1.1 volatile long ctl; // main pool control
1261     final int parallelism; // parallelism level
1262     final int localMode; // per-worker scheduling mode
1263 dl 1.8 volatile int nextWorkerNumber; // to create worker name string
1264 dl 1.1 final int submitMask; // submit queue index bound
1265     int nextSeed; // for initializing worker seeds
1266 dl 1.8 volatile int mainLock; // spinlock for array updates
1267 dl 1.1 volatile int runState; // shutdown status and seq
1268     WorkQueue[] workQueues; // main registry
1269     final ForkJoinWorkerThreadFactory factory; // factory for new workers
1270     final Thread.UncaughtExceptionHandler ueh; // per-worker UEH
1271 dl 1.8 final String workerNamePrefix; // to create worker name string
1272    
1273     /*
1274     * Mechanics for main lock protecting worker array updates. Uses
1275     * the same strategy as ConcurrentHashMap bins -- a spinLock for
1276     * normal cases, but falling back to builtin lock when (rarely)
1277     * needed. See internal ConcurrentHashMap documentation for
1278     * explanation.
1279     */
1280    
1281     static final int LOCK_WAITING = 2; // bit to indicate need for signal
1282     static final int MAX_LOCK_SPINS = 1 << 8;
1283    
1284     private void tryAwaitMainLock() {
1285     int spins = MAX_LOCK_SPINS, r = 0, h;
1286     while (((h = mainLock) & 1) != 0) {
1287     if (r == 0)
1288     r = ThreadLocalRandom.current().nextInt(); // randomize spins
1289     else if (spins >= 0) {
1290     r ^= r << 1; r ^= r >>> 3; r ^= r << 10; // xorshift
1291     if (r >= 0)
1292     --spins;
1293     }
1294     else if (U.compareAndSwapInt(this, MAINLOCK, h, h | LOCK_WAITING)) {
1295     synchronized (this) {
1296     if ((mainLock & LOCK_WAITING) != 0) {
1297     try {
1298     wait();
1299     } catch (InterruptedException ie) {
1300     Thread.currentThread().interrupt();
1301     }
1302     }
1303     else
1304     notifyAll(); // possibly won race vs signaller
1305     }
1306     break;
1307     }
1308     }
1309     }
1310 dl 1.1
1311     // Creating, registering, and deregistering workers
1312    
1313     /**
1314     * Tries to create and start a worker
1315     */
1316     private void addWorker() {
1317     Throwable ex = null;
1318     ForkJoinWorkerThread wt = null;
1319     try {
1320     if ((wt = factory.newThread(this)) != null) {
1321     wt.start();
1322     return;
1323     }
1324     } catch (Throwable e) {
1325     ex = e;
1326     }
1327     deregisterWorker(wt, ex); // adjust counts etc on failure
1328     }
1329    
1330     /**
1331     * Callback from ForkJoinWorkerThread constructor to assign a
1332     * public name. This must be separate from registerWorker because
1333     * it is called during the "super" constructor call in
1334     * ForkJoinWorkerThread.
1335     */
1336     final String nextWorkerName() {
1337 dl 1.8 int n;
1338     do {} while(!U.compareAndSwapInt(this, NEXTWORKERNUMBER,
1339     n = nextWorkerNumber, ++n));
1340     return workerNamePrefix.concat(Integer.toString(n));
1341 dl 1.1 }
1342    
1343     /**
1344     * Callback from ForkJoinWorkerThread constructor to establish its
1345     * poolIndex and record its WorkQueue. To avoid scanning bias due
1346     * to packing entries in front of the workQueues array, we treat
1347     * the array as a simple power-of-two hash table using per-thread
1348     * seed as hash, expanding as needed.
1349     *
1350     * @param w the worker's queue
1351     */
1352     final void registerWorker(WorkQueue w) {
1353 dl 1.8 while (!U.compareAndSwapInt(this, MAINLOCK, 0, 1))
1354     tryAwaitMainLock();
1355 dl 1.1 try {
1356 dl 1.8 WorkQueue[] ws;
1357     if ((ws = workQueues) == null)
1358     ws = workQueues = new WorkQueue[submitMask + 1];
1359     if (w != null) {
1360 dl 1.7 int rs, n = ws.length, m = n - 1;
1361 dl 1.1 int s = nextSeed += SEED_INCREMENT; // rarely-colliding sequence
1362     w.seed = (s == 0) ? 1 : s; // ensure non-zero seed
1363     int r = (s << 1) | 1; // use odd-numbered indices
1364     if (ws[r &= m] != null) { // collision
1365     int probes = 0; // step by approx half size
1366     int step = (n <= 4) ? 2 : ((n >>> 1) & SQMASK) + 2;
1367     while (ws[r = (r + step) & m] != null) {
1368     if (++probes >= n) {
1369     workQueues = ws = Arrays.copyOf(ws, n <<= 1);
1370     m = n - 1;
1371     probes = 0;
1372     }
1373     }
1374     }
1375     w.eventCount = w.poolIndex = r; // establish before recording
1376     ws[r] = w; // also update seq
1377     runState = ((rs = runState) & SHUTDOWN) | ((rs + 2) & ~SHUTDOWN);
1378     }
1379     } finally {
1380 dl 1.8 if (!U.compareAndSwapInt(this, MAINLOCK, 1, 0)) {
1381     mainLock = 0;
1382     synchronized (this) { notifyAll(); };
1383     }
1384 dl 1.1 }
1385 dl 1.8
1386 dl 1.1 }
1387    
1388     /**
1389     * Final callback from terminating worker, as well as upon failure
1390     * to construct or start a worker in addWorker. Removes record of
1391     * worker from array, and adjusts counts. If pool is shutting
1392     * down, tries to complete termination.
1393     *
1394     * @param wt the worker thread or null if addWorker failed
1395     * @param ex the exception causing failure, or null if none
1396     */
1397     final void deregisterWorker(ForkJoinWorkerThread wt, Throwable ex) {
1398     WorkQueue w = null;
1399     if (wt != null && (w = wt.workQueue) != null) {
1400     w.runState = -1; // ensure runState is set
1401 dl 1.8 long steals = w.totalSteals + w.nsteals, sc;
1402     do {} while(!U.compareAndSwapLong(this, STEALCOUNT,
1403     sc = stealCount, sc + steals));
1404 dl 1.1 int idx = w.poolIndex;
1405 dl 1.8 while (!U.compareAndSwapInt(this, MAINLOCK, 0, 1))
1406     tryAwaitMainLock();
1407     try {
1408 dl 1.1 WorkQueue[] ws = workQueues;
1409     if (ws != null && idx >= 0 && idx < ws.length && ws[idx] == w)
1410     ws[idx] = null;
1411     } finally {
1412 dl 1.8 if (!U.compareAndSwapInt(this, MAINLOCK, 1, 0)) {
1413     mainLock = 0;
1414     synchronized (this) { notifyAll(); };
1415     }
1416 dl 1.1 }
1417     }
1418    
1419     long c; // adjust ctl counts
1420     do {} while (!U.compareAndSwapLong
1421     (this, CTL, c = ctl, (((c - AC_UNIT) & AC_MASK) |
1422     ((c - TC_UNIT) & TC_MASK) |
1423     (c & ~(AC_MASK|TC_MASK)))));
1424    
1425     if (!tryTerminate(false, false) && w != null) {
1426     w.cancelAll(); // cancel remaining tasks
1427     if (w.array != null) // suppress signal if never ran
1428     signalWork(); // wake up or create replacement
1429     if (ex == null) // help clean refs on way out
1430     ForkJoinTask.helpExpungeStaleExceptions();
1431     }
1432    
1433     if (ex != null) // rethrow
1434     U.throwException(ex);
1435     }
1436    
1437     // Submissions
1438    
1439     /**
1440     * Unless shutting down, adds the given task to a submission queue
1441     * at submitter's current queue index (modulo submission
1442     * range). If no queue exists at the index, one is created. If
1443     * the queue is busy, another index is randomly chosen. The
1444     * submitMask bounds the effective number of queues to the
1445     * (nearest power of two for) parallelism level.
1446     *
1447     * @param task the task. Caller must ensure non-null.
1448     */
1449     private void doSubmit(ForkJoinTask<?> task) {
1450     Submitter s = submitters.get();
1451     for (int r = s.seed, m = submitMask;;) {
1452     WorkQueue[] ws; WorkQueue q;
1453     int k = r & m & SQMASK; // use only even indices
1454 dl 1.8 if (runState < 0)
1455 dl 1.1 throw new RejectedExecutionException(); // shutting down
1456 dl 1.8 else if ((ws = workQueues) == null || ws.length <= k) {
1457     while (!U.compareAndSwapInt(this, MAINLOCK, 0, 1))
1458     tryAwaitMainLock();
1459     try {
1460     if (workQueues == null)
1461     workQueues = new WorkQueue[submitMask + 1];
1462     } finally {
1463     if (!U.compareAndSwapInt(this, MAINLOCK, 1, 0)) {
1464     mainLock = 0;
1465     synchronized (this) { notifyAll(); };
1466     }
1467     }
1468     }
1469 dl 1.1 else if ((q = ws[k]) == null) { // create new queue
1470     WorkQueue nq = new WorkQueue(this, null, SHARED_QUEUE);
1471 dl 1.8 while (!U.compareAndSwapInt(this, MAINLOCK, 0, 1))
1472     tryAwaitMainLock();
1473     try {
1474 dl 1.1 int rs = runState; // to update seq
1475     if (ws == workQueues && ws[k] == null) {
1476     ws[k] = nq;
1477     runState = ((rs & SHUTDOWN) | ((rs + 2) & ~SHUTDOWN));
1478     }
1479     } finally {
1480 dl 1.8 if (!U.compareAndSwapInt(this, MAINLOCK, 1, 0)) {
1481     mainLock = 0;
1482     synchronized (this) { notifyAll(); };
1483     }
1484 dl 1.1 }
1485     }
1486     else if (q.trySharedPush(task)) {
1487     signalWork();
1488     return;
1489     }
1490     else if (m > 1) { // move to a different index
1491     r ^= r << 13; // same xorshift as WorkQueues
1492     r ^= r >>> 17;
1493     s.seed = r ^= r << 5;
1494     }
1495     else
1496     Thread.yield(); // yield if no alternatives
1497     }
1498     }
1499    
1500 dl 1.7 /**
1501     * Submits the given (non-null) task to the common pool, if possible.
1502     */
1503     static void submitToCommonPool(ForkJoinTask<?> task) {
1504     ForkJoinPool p;
1505     if ((p = commonPool) == null)
1506 dl 1.8 throw new RejectedExecutionException("Common Pool Unavailable");
1507 dl 1.7 p.doSubmit(task);
1508     }
1509    
1510     /**
1511     * Returns true if the given task was submitted to common pool
1512     * and has not yet commenced execution, and is available for
1513     * removal according to execution policies; if so removing the
1514     * submission from the pool.
1515     *
1516     * @param task the task
1517     * @return true if successful
1518     */
1519     static boolean tryUnsubmitFromCommonPool(ForkJoinTask<?> task) {
1520 dl 1.8 // Peek, looking for task and eligibility before
1521     // using trySharedUnpush to actually take it under lock
1522 dl 1.7 ForkJoinPool p; WorkQueue[] ws; WorkQueue q;
1523 dl 1.8 ForkJoinTask<?>[] a; int t, s, n;
1524 dl 1.7 int k = submitters.get().seed & SQMASK;
1525     return ((p = commonPool) != null &&
1526     (ws = p.workQueues) != null &&
1527     ws.length > (k &= p.submitMask) &&
1528     (q = ws[k]) != null &&
1529 dl 1.8 (a = q.array) != null &&
1530     (n = (t = q.top) - q.base) > 0 &&
1531     (n > 1 || (int)(p.ctl >> AC_SHIFT) < 0) &&
1532     (s = t - 1) >= 0 && s < a.length && a[s] == task &&
1533     q.trySharedUnpush(task));
1534 dl 1.7 }
1535    
1536 dl 1.1 // Maintaining ctl counts
1537    
1538     /**
1539     * Increments active count; mainly called upon return from blocking.
1540     */
1541     final void incrementActiveCount() {
1542     long c;
1543     do {} while (!U.compareAndSwapLong(this, CTL, c = ctl, c + AC_UNIT));
1544     }
1545    
1546     /**
1547 dl 1.7 * Tries to create one or activate one or more workers if too few are active.
1548 dl 1.1 */
1549     final void signalWork() {
1550     long c; int u;
1551     while ((u = (int)((c = ctl) >>> 32)) < 0) { // too few active
1552     WorkQueue[] ws = workQueues; int e, i; WorkQueue w; Thread p;
1553     if ((e = (int)c) > 0) { // at least one waiting
1554     if (ws != null && (i = e & SMASK) < ws.length &&
1555     (w = ws[i]) != null && w.eventCount == (e | INT_SIGN)) {
1556     long nc = (((long)(w.nextWait & E_MASK)) |
1557     ((long)(u + UAC_UNIT) << 32));
1558     if (U.compareAndSwapLong(this, CTL, c, nc)) {
1559     w.eventCount = (e + E_SEQ) & E_MASK;
1560     if ((p = w.parker) != null)
1561     U.unpark(p); // activate and release
1562     break;
1563     }
1564     }
1565     else
1566     break;
1567     }
1568     else if (e == 0 && (u & SHORT_SIGN) != 0) { // too few total
1569     long nc = (long)(((u + UTC_UNIT) & UTC_MASK) |
1570     ((u + UAC_UNIT) & UAC_MASK)) << 32;
1571     if (U.compareAndSwapLong(this, CTL, c, nc)) {
1572     addWorker();
1573     break;
1574     }
1575     }
1576     else
1577     break;
1578     }
1579     }
1580    
1581     // Scanning for tasks
1582    
1583     /**
1584     * Top-level runloop for workers, called by ForkJoinWorkerThread.run.
1585     */
1586     final void runWorker(WorkQueue w) {
1587     w.growArray(false); // initialize queue array in this thread
1588     do { w.runTask(scan(w)); } while (w.runState >= 0);
1589     }
1590    
1591     /**
1592     * Scans for and, if found, returns one task, else possibly
1593     * inactivates the worker. This method operates on single reads of
1594     * volatile state and is designed to be re-invoked continuously,
1595     * in part because it returns upon detecting inconsistencies,
1596     * contention, or state changes that indicate possible success on
1597     * re-invocation.
1598     *
1599     * The scan searches for tasks across a random permutation of
1600     * queues (starting at a random index and stepping by a random
1601     * relative prime, checking each at least once). The scan
1602     * terminates upon either finding a non-empty queue, or completing
1603     * the sweep. If the worker is not inactivated, it takes and
1604     * returns a task from this queue. On failure to find a task, we
1605     * take one of the following actions, after which the caller will
1606     * retry calling this method unless terminated.
1607     *
1608     * * If pool is terminating, terminate the worker.
1609     *
1610     * * If not a complete sweep, try to release a waiting worker. If
1611     * the scan terminated because the worker is inactivated, then the
1612     * released worker will often be the calling worker, and it can
1613     * succeed obtaining a task on the next call. Or maybe it is
1614     * another worker, but with same net effect. Releasing in other
1615     * cases as well ensures that we have enough workers running.
1616     *
1617     * * If not already enqueued, try to inactivate and enqueue the
1618     * worker on wait queue. Or, if inactivating has caused the pool
1619     * to be quiescent, relay to idleAwaitWork to check for
1620     * termination and possibly shrink pool.
1621     *
1622     * * If already inactive, and the caller has run a task since the
1623     * last empty scan, return (to allow rescan) unless others are
1624     * also inactivated. Field WorkQueue.rescans counts down on each
1625     * scan to ensure eventual inactivation and blocking.
1626     *
1627     * * If already enqueued and none of the above apply, park
1628     * awaiting signal,
1629     *
1630     * @param w the worker (via its WorkQueue)
1631 jsr166 1.5 * @return a task or null if none found
1632 dl 1.1 */
1633     private final ForkJoinTask<?> scan(WorkQueue w) {
1634     WorkQueue[] ws; // first update random seed
1635     int r = w.seed; r ^= r << 13; r ^= r >>> 17; w.seed = r ^= r << 5;
1636     int rs = runState, m; // volatile read order matters
1637     if ((ws = workQueues) != null && (m = ws.length - 1) > 0) {
1638     int ec = w.eventCount; // ec is negative if inactive
1639     int step = (r >>> 16) | 1; // relative prime
1640     for (int j = (m + 1) << 2; ; r += step) {
1641     WorkQueue q; ForkJoinTask<?> t; ForkJoinTask<?>[] a; int b;
1642     if ((q = ws[r & m]) != null && (b = q.base) - q.top < 0 &&
1643     (a = q.array) != null) { // probably nonempty
1644     int i = (((a.length - 1) & b) << ASHIFT) + ABASE;
1645     t = (ForkJoinTask<?>)U.getObjectVolatile(a, i);
1646     if (q.base == b && ec >= 0 && t != null &&
1647     U.compareAndSwapObject(a, i, t, null)) {
1648 dl 1.7 if (q.top - (q.base = b + 1) > 0)
1649 dl 1.1 signalWork(); // help pushes signal
1650     return t;
1651     }
1652     else if (ec < 0 || j <= m) {
1653     rs = 0; // mark scan as imcomplete
1654     break; // caller can retry after release
1655     }
1656     }
1657     if (--j < 0)
1658     break;
1659     }
1660    
1661     long c = ctl; int e = (int)c, a = (int)(c >> AC_SHIFT), nr, ns;
1662     if (e < 0) // decode ctl on empty scan
1663     w.runState = -1; // pool is terminating
1664     else if (rs == 0 || rs != runState) { // incomplete scan
1665     WorkQueue v; Thread p; // try to release a waiter
1666     if (e > 0 && a < 0 && w.eventCount == ec &&
1667     (v = ws[e & m]) != null && v.eventCount == (e | INT_SIGN)) {
1668     long nc = ((long)(v.nextWait & E_MASK) |
1669     ((c + AC_UNIT) & (AC_MASK|TC_MASK)));
1670     if (ctl == c && U.compareAndSwapLong(this, CTL, c, nc)) {
1671     v.eventCount = (e + E_SEQ) & E_MASK;
1672     if ((p = v.parker) != null)
1673     U.unpark(p);
1674     }
1675     }
1676     }
1677     else if (ec >= 0) { // try to enqueue/inactivate
1678     long nc = (long)ec | ((c - AC_UNIT) & (AC_MASK|TC_MASK));
1679     w.nextWait = e;
1680     w.eventCount = ec | INT_SIGN; // mark as inactive
1681     if (ctl != c || !U.compareAndSwapLong(this, CTL, c, nc))
1682     w.eventCount = ec; // unmark on CAS failure
1683     else {
1684     if ((ns = w.nsteals) != 0) {
1685     w.nsteals = 0; // set rescans if ran task
1686     w.rescans = (a > 0) ? 0 : a + parallelism;
1687     w.totalSteals += ns;
1688     }
1689     if (a == 1 - parallelism) // quiescent
1690     idleAwaitWork(w, nc, c);
1691     }
1692     }
1693     else if (w.eventCount < 0) { // already queued
1694 dl 1.7 int ac = a + parallelism;
1695     if ((nr = w.rescans) > 0) // continue rescanning
1696     w.rescans = (ac < nr) ? ac : nr - 1;
1697     else if (((w.seed >>> 16) & ac) == 0) { // randomize park
1698 dl 1.1 Thread.interrupted(); // clear status
1699     Thread wt = Thread.currentThread();
1700     U.putObject(wt, PARKBLOCKER, this);
1701     w.parker = wt; // emulate LockSupport.park
1702     if (w.eventCount < 0) // recheck
1703     U.park(false, 0L);
1704     w.parker = null;
1705     U.putObject(wt, PARKBLOCKER, null);
1706     }
1707     }
1708     }
1709     return null;
1710     }
1711    
1712     /**
1713     * If inactivating worker w has caused the pool to become
1714     * quiescent, checks for pool termination, and, so long as this is
1715 dl 1.7 * not the only worker, waits for event for up to a given
1716     * duration. On timeout, if ctl has not changed, terminates the
1717 dl 1.1 * worker, which will in turn wake up another worker to possibly
1718     * repeat this process.
1719     *
1720     * @param w the calling worker
1721     * @param currentCtl the ctl value triggering possible quiescence
1722     * @param prevCtl the ctl value to restore if thread is terminated
1723     */
1724     private void idleAwaitWork(WorkQueue w, long currentCtl, long prevCtl) {
1725     if (w.eventCount < 0 && !tryTerminate(false, false) &&
1726     (int)prevCtl != 0 && !hasQueuedSubmissions() && ctl == currentCtl) {
1727 dl 1.7 int dc = -(short)(currentCtl >>> TC_SHIFT);
1728     long parkTime = dc < 0 ? FAST_IDLE_TIMEOUT: (dc + 1) * IDLE_TIMEOUT;
1729     long deadline = System.nanoTime() + parkTime - 100000L; // 1ms slop
1730 dl 1.1 Thread wt = Thread.currentThread();
1731     while (ctl == currentCtl) {
1732     Thread.interrupted(); // timed variant of version in scan()
1733     U.putObject(wt, PARKBLOCKER, this);
1734     w.parker = wt;
1735     if (ctl == currentCtl)
1736 dl 1.7 U.park(false, parkTime);
1737 dl 1.1 w.parker = null;
1738     U.putObject(wt, PARKBLOCKER, null);
1739     if (ctl != currentCtl)
1740     break;
1741 dl 1.7 if (deadline - System.nanoTime() <= 0L &&
1742 dl 1.1 U.compareAndSwapLong(this, CTL, currentCtl, prevCtl)) {
1743     w.eventCount = (w.eventCount + E_SEQ) | E_MASK;
1744     w.runState = -1; // shrink
1745     break;
1746     }
1747     }
1748     }
1749     }
1750    
1751     /**
1752     * Tries to locate and execute tasks for a stealer of the given
1753     * task, or in turn one of its stealers, Traces currentSteal ->
1754     * currentJoin links looking for a thread working on a descendant
1755     * of the given task and with a non-empty queue to steal back and
1756     * execute tasks from. The first call to this method upon a
1757     * waiting join will often entail scanning/search, (which is OK
1758     * because the joiner has nothing better to do), but this method
1759     * leaves hints in workers to speed up subsequent calls. The
1760     * implementation is very branchy to cope with potential
1761     * inconsistencies or loops encountering chains that are stale,
1762     * unknown, or so long that they are likely cyclic.
1763     *
1764     * @param joiner the joining worker
1765     * @param task the task to join
1766     * @return 0 if no progress can be made, negative if task
1767     * known complete, else positive
1768     */
1769     private int tryHelpStealer(WorkQueue joiner, ForkJoinTask<?> task) {
1770     int stat = 0, steps = 0; // bound to avoid cycles
1771     if (joiner != null && task != null) { // hoist null checks
1772     restart: for (;;) {
1773     ForkJoinTask<?> subtask = task; // current target
1774     for (WorkQueue j = joiner, v;;) { // v is stealer of subtask
1775     WorkQueue[] ws; int m, s, h;
1776     if ((s = task.status) < 0) {
1777     stat = s;
1778     break restart;
1779     }
1780     if ((ws = workQueues) == null || (m = ws.length - 1) <= 0)
1781     break restart; // shutting down
1782     if ((v = ws[h = (j.stealHint | 1) & m]) == null ||
1783     v.currentSteal != subtask) {
1784     for (int origin = h;;) { // find stealer
1785     if (((h = (h + 2) & m) & 15) == 1 &&
1786     (subtask.status < 0 || j.currentJoin != subtask))
1787     continue restart; // occasional staleness check
1788     if ((v = ws[h]) != null &&
1789     v.currentSteal == subtask) {
1790     j.stealHint = h; // save hint
1791     break;
1792     }
1793     if (h == origin)
1794     break restart; // cannot find stealer
1795     }
1796     }
1797     for (;;) { // help stealer or descend to its stealer
1798     ForkJoinTask[] a; int b;
1799     if (subtask.status < 0) // surround probes with
1800     continue restart; // consistency checks
1801     if ((b = v.base) - v.top < 0 && (a = v.array) != null) {
1802     int i = (((a.length - 1) & b) << ASHIFT) + ABASE;
1803     ForkJoinTask<?> t =
1804     (ForkJoinTask<?>)U.getObjectVolatile(a, i);
1805     if (subtask.status < 0 || j.currentJoin != subtask ||
1806     v.currentSteal != subtask)
1807     continue restart; // stale
1808     stat = 1; // apparent progress
1809     if (t != null && v.base == b &&
1810     U.compareAndSwapObject(a, i, t, null)) {
1811     v.base = b + 1; // help stealer
1812     joiner.runSubtask(t);
1813     }
1814     else if (v.base == b && ++steps == MAX_HELP)
1815     break restart; // v apparently stalled
1816     }
1817     else { // empty -- try to descend
1818     ForkJoinTask<?> next = v.currentJoin;
1819     if (subtask.status < 0 || j.currentJoin != subtask ||
1820     v.currentSteal != subtask)
1821     continue restart; // stale
1822     else if (next == null || ++steps == MAX_HELP)
1823     break restart; // dead-end or maybe cyclic
1824     else {
1825     subtask = next;
1826     j = v;
1827     break;
1828     }
1829     }
1830     }
1831     }
1832     }
1833     }
1834     return stat;
1835     }
1836    
1837     /**
1838     * If task is at base of some steal queue, steals and executes it.
1839     *
1840     * @param joiner the joining worker
1841     * @param task the task
1842     */
1843     private void tryPollForAndExec(WorkQueue joiner, ForkJoinTask<?> task) {
1844     WorkQueue[] ws;
1845     if ((ws = workQueues) != null) {
1846     for (int j = 1; j < ws.length && task.status >= 0; j += 2) {
1847     WorkQueue q = ws[j];
1848     if (q != null && q.pollFor(task)) {
1849     joiner.runSubtask(task);
1850     break;
1851     }
1852     }
1853     }
1854     }
1855    
1856     /**
1857     * Tries to decrement active count (sometimes implicitly) and
1858     * possibly release or create a compensating worker in preparation
1859     * for blocking. Fails on contention or termination. Otherwise,
1860     * adds a new thread if no idle workers are available and either
1861     * pool would become completely starved or: (at least half
1862     * starved, and fewer than 50% spares exist, and there is at least
1863     * one task apparently available). Even though the availability
1864     * check requires a full scan, it is worthwhile in reducing false
1865     * alarms.
1866     *
1867     * @param task if non-null, a task being waited for
1868     * @param blocker if non-null, a blocker being waited for
1869     * @return true if the caller can block, else should recheck and retry
1870     */
1871     final boolean tryCompensate(ForkJoinTask<?> task, ManagedBlocker blocker) {
1872     int pc = parallelism, e;
1873     long c = ctl;
1874     WorkQueue[] ws = workQueues;
1875     if ((e = (int)c) >= 0 && ws != null) {
1876     int u, a, ac, hc;
1877     int tc = (short)((u = (int)(c >>> 32)) >>> UTC_SHIFT) + pc;
1878     boolean replace = false;
1879     if ((a = u >> UAC_SHIFT) <= 0) {
1880     if ((ac = a + pc) <= 1)
1881     replace = true;
1882     else if ((e > 0 || (task != null &&
1883     ac <= (hc = pc >>> 1) && tc < pc + hc))) {
1884     WorkQueue w;
1885     for (int j = 0; j < ws.length; ++j) {
1886     if ((w = ws[j]) != null && !w.isEmpty()) {
1887     replace = true;
1888     break; // in compensation range and tasks available
1889     }
1890     }
1891     }
1892     }
1893     if ((task == null || task.status >= 0) && // recheck need to block
1894     (blocker == null || !blocker.isReleasable()) && ctl == c) {
1895     if (!replace) { // no compensation
1896     long nc = ((c - AC_UNIT) & AC_MASK) | (c & ~AC_MASK);
1897     if (U.compareAndSwapLong(this, CTL, c, nc))
1898     return true;
1899     }
1900     else if (e != 0) { // release an idle worker
1901     WorkQueue w; Thread p; int i;
1902     if ((i = e & SMASK) < ws.length && (w = ws[i]) != null) {
1903     long nc = ((long)(w.nextWait & E_MASK) |
1904     (c & (AC_MASK|TC_MASK)));
1905     if (w.eventCount == (e | INT_SIGN) &&
1906     U.compareAndSwapLong(this, CTL, c, nc)) {
1907     w.eventCount = (e + E_SEQ) & E_MASK;
1908     if ((p = w.parker) != null)
1909     U.unpark(p);
1910     return true;
1911     }
1912     }
1913     }
1914     else if (tc < MAX_CAP) { // create replacement
1915     long nc = ((c + TC_UNIT) & TC_MASK) | (c & ~TC_MASK);
1916     if (U.compareAndSwapLong(this, CTL, c, nc)) {
1917     addWorker();
1918     return true;
1919     }
1920     }
1921     }
1922     }
1923     return false;
1924     }
1925    
1926     /**
1927     * Helps and/or blocks until the given task is done.
1928     *
1929     * @param joiner the joining worker
1930     * @param task the task
1931     * @return task status on exit
1932     */
1933     final int awaitJoin(WorkQueue joiner, ForkJoinTask<?> task) {
1934     int s;
1935     if ((s = task.status) >= 0) {
1936     ForkJoinTask<?> prevJoin = joiner.currentJoin;
1937     joiner.currentJoin = task;
1938     long startTime = 0L;
1939     for (int k = 0;;) {
1940     if ((s = (joiner.isEmpty() ? // try to help
1941     tryHelpStealer(joiner, task) :
1942     joiner.tryRemoveAndExec(task))) == 0 &&
1943     (s = task.status) >= 0) {
1944     if (k == 0) {
1945     startTime = System.nanoTime();
1946     tryPollForAndExec(joiner, task); // check uncommon case
1947     }
1948     else if ((k & (MAX_HELP - 1)) == 0 &&
1949     System.nanoTime() - startTime >=
1950     COMPENSATION_DELAY &&
1951     tryCompensate(task, null)) {
1952     if (task.trySetSignal()) {
1953     synchronized (task) {
1954     if (task.status >= 0) {
1955     try { // see ForkJoinTask
1956     task.wait(); // for explanation
1957     } catch (InterruptedException ie) {
1958     }
1959     }
1960     else
1961     task.notifyAll();
1962     }
1963     }
1964     long c; // re-activate
1965     do {} while (!U.compareAndSwapLong
1966     (this, CTL, c = ctl, c + AC_UNIT));
1967     }
1968     }
1969     if (s < 0 || (s = task.status) < 0) {
1970     joiner.currentJoin = prevJoin;
1971     break;
1972     }
1973     else if ((k++ & (MAX_HELP - 1)) == MAX_HELP >>> 1)
1974     Thread.yield(); // for politeness
1975     }
1976     }
1977     return s;
1978     }
1979    
1980     /**
1981     * Stripped-down variant of awaitJoin used by timed joins. Tries
1982     * to help join only while there is continuous progress. (Caller
1983     * will then enter a timed wait.)
1984     *
1985     * @param joiner the joining worker
1986     * @param task the task
1987     * @return task status on exit
1988     */
1989     final int helpJoinOnce(WorkQueue joiner, ForkJoinTask<?> task) {
1990     int s;
1991     while ((s = task.status) >= 0 &&
1992     (joiner.isEmpty() ?
1993     tryHelpStealer(joiner, task) :
1994     joiner.tryRemoveAndExec(task)) != 0)
1995     ;
1996     return s;
1997     }
1998    
1999     /**
2000     * Returns a (probably) non-empty steal queue, if one is found
2001     * during a random, then cyclic scan, else null. This method must
2002     * be retried by caller if, by the time it tries to use the queue,
2003     * it is empty.
2004     */
2005     private WorkQueue findNonEmptyStealQueue(WorkQueue w) {
2006     // Similar to loop in scan(), but ignoring submissions
2007 dl 1.8 int r = w.seed; r ^= r << 13; r ^= r >>> 17; w.seed = r ^= r << 5;
2008 dl 1.1 int step = (r >>> 16) | 1;
2009     for (WorkQueue[] ws;;) {
2010     int rs = runState, m;
2011     if ((ws = workQueues) == null || (m = ws.length - 1) < 1)
2012     return null;
2013     for (int j = (m + 1) << 2; ; r += step) {
2014     WorkQueue q = ws[((r << 1) | 1) & m];
2015     if (q != null && !q.isEmpty())
2016     return q;
2017     else if (--j < 0) {
2018     if (runState == rs)
2019     return null;
2020     break;
2021     }
2022     }
2023     }
2024     }
2025    
2026     /**
2027     * Runs tasks until {@code isQuiescent()}. We piggyback on
2028     * active count ctl maintenance, but rather than blocking
2029     * when tasks cannot be found, we rescan until all others cannot
2030     * find tasks either.
2031     */
2032     final void helpQuiescePool(WorkQueue w) {
2033     for (boolean active = true;;) {
2034     ForkJoinTask<?> localTask; // exhaust local queue
2035     while ((localTask = w.nextLocalTask()) != null)
2036     localTask.doExec();
2037     WorkQueue q = findNonEmptyStealQueue(w);
2038     if (q != null) {
2039     ForkJoinTask<?> t; int b;
2040     if (!active) { // re-establish active count
2041     long c;
2042     active = true;
2043     do {} while (!U.compareAndSwapLong
2044     (this, CTL, c = ctl, c + AC_UNIT));
2045     }
2046     if ((b = q.base) - q.top < 0 && (t = q.pollAt(b)) != null)
2047     w.runSubtask(t);
2048     }
2049     else {
2050     long c;
2051     if (active) { // decrement active count without queuing
2052     active = false;
2053     do {} while (!U.compareAndSwapLong
2054     (this, CTL, c = ctl, c -= AC_UNIT));
2055     }
2056     else
2057     c = ctl; // re-increment on exit
2058     if ((int)(c >> AC_SHIFT) + parallelism == 0) {
2059     do {} while (!U.compareAndSwapLong
2060     (this, CTL, c = ctl, c + AC_UNIT));
2061     break;
2062     }
2063     }
2064     }
2065     }
2066    
2067     /**
2068 dl 1.7 * Restricted version of helpQuiescePool for non-FJ callers
2069     */
2070     static void externalHelpQuiescePool() {
2071     ForkJoinPool p; WorkQueue[] ws; WorkQueue w, q;
2072     ForkJoinTask<?> t; int b;
2073     int k = submitters.get().seed & SQMASK;
2074     if ((p = commonPool) != null &&
2075     (ws = p.workQueues) != null &&
2076     ws.length > (k &= p.submitMask) &&
2077     (w = ws[k]) != null &&
2078     (q = p.findNonEmptyStealQueue(w)) != null &&
2079     (b = q.base) - q.top < 0 &&
2080     (t = q.pollAt(b)) != null)
2081     t.doExec();
2082     }
2083    
2084     /**
2085 dl 1.1 * Gets and removes a local or stolen task for the given worker.
2086     *
2087     * @return a task, if available
2088     */
2089     final ForkJoinTask<?> nextTaskFor(WorkQueue w) {
2090     for (ForkJoinTask<?> t;;) {
2091     WorkQueue q; int b;
2092     if ((t = w.nextLocalTask()) != null)
2093     return t;
2094     if ((q = findNonEmptyStealQueue(w)) == null)
2095     return null;
2096     if ((b = q.base) - q.top < 0 && (t = q.pollAt(b)) != null)
2097     return t;
2098     }
2099     }
2100    
2101     /**
2102     * Returns the approximate (non-atomic) number of idle threads per
2103     * active thread to offset steal queue size for method
2104     * ForkJoinTask.getSurplusQueuedTaskCount().
2105     */
2106     final int idlePerActive() {
2107     // Approximate at powers of two for small values, saturate past 4
2108     int p = parallelism;
2109     int a = p + (int)(ctl >> AC_SHIFT);
2110     return (a > (p >>>= 1) ? 0 :
2111     a > (p >>>= 1) ? 1 :
2112     a > (p >>>= 1) ? 2 :
2113     a > (p >>>= 1) ? 4 :
2114     8);
2115     }
2116    
2117 dl 1.7 /**
2118     * Returns approximate submission queue length for the given caller
2119     */
2120     static int getEstimatedSubmitterQueueLength() {
2121     ForkJoinPool p; WorkQueue[] ws; WorkQueue q;
2122     int k = submitters.get().seed & SQMASK;
2123     return ((p = commonPool) != null &&
2124     p.runState >= 0 &&
2125     (ws = p.workQueues) != null &&
2126     ws.length > (k &= p.submitMask) &&
2127     (q = ws[k]) != null) ?
2128     q.queueSize() : 0;
2129     }
2130    
2131 dl 1.1 // Termination
2132    
2133     /**
2134     * Possibly initiates and/or completes termination. The caller
2135     * triggering termination runs three passes through workQueues:
2136     * (0) Setting termination status, followed by wakeups of queued
2137     * workers; (1) cancelling all tasks; (2) interrupting lagging
2138     * threads (likely in external tasks, but possibly also blocked in
2139     * joins). Each pass repeats previous steps because of potential
2140     * lagging thread creation.
2141     *
2142     * @param now if true, unconditionally terminate, else only
2143     * if no work and no active workers
2144     * @param enable if true, enable shutdown when next possible
2145     * @return true if now terminating or terminated
2146     */
2147     private boolean tryTerminate(boolean now, boolean enable) {
2148     for (long c;;) {
2149     if (((c = ctl) & STOP_BIT) != 0) { // already terminating
2150     if ((short)(c >>> TC_SHIFT) == -parallelism) {
2151 dl 1.8 synchronized(this) {
2152     notifyAll(); // signal when 0 workers
2153     }
2154 dl 1.1 }
2155     return true;
2156     }
2157     if (runState >= 0) { // not yet enabled
2158     if (!enable)
2159     return false;
2160 dl 1.8 while (!U.compareAndSwapInt(this, MAINLOCK, 0, 1))
2161     tryAwaitMainLock();
2162     try {
2163     runState |= SHUTDOWN;
2164     } finally {
2165     if (!U.compareAndSwapInt(this, MAINLOCK, 1, 0)) {
2166     mainLock = 0;
2167     synchronized (this) { notifyAll(); };
2168     }
2169     }
2170 dl 1.1 }
2171     if (!now) { // check if idle & no tasks
2172     if ((int)(c >> AC_SHIFT) != -parallelism ||
2173     hasQueuedSubmissions())
2174     return false;
2175     // Check for unqueued inactive workers. One pass suffices.
2176     WorkQueue[] ws = workQueues; WorkQueue w;
2177     if (ws != null) {
2178     for (int i = 1; i < ws.length; i += 2) {
2179     if ((w = ws[i]) != null && w.eventCount >= 0)
2180     return false;
2181     }
2182     }
2183     }
2184     if (U.compareAndSwapLong(this, CTL, c, c | STOP_BIT)) {
2185     for (int pass = 0; pass < 3; ++pass) {
2186     WorkQueue[] ws = workQueues;
2187     if (ws != null) {
2188     WorkQueue w;
2189     int n = ws.length;
2190     for (int i = 0; i < n; ++i) {
2191     if ((w = ws[i]) != null) {
2192     w.runState = -1;
2193     if (pass > 0) {
2194     w.cancelAll();
2195     if (pass > 1)
2196     w.interruptOwner();
2197     }
2198     }
2199     }
2200     // Wake up workers parked on event queue
2201     int i, e; long cc; Thread p;
2202     while ((e = (int)(cc = ctl) & E_MASK) != 0 &&
2203     (i = e & SMASK) < n &&
2204     (w = ws[i]) != null) {
2205     long nc = ((long)(w.nextWait & E_MASK) |
2206     ((cc + AC_UNIT) & AC_MASK) |
2207     (cc & (TC_MASK|STOP_BIT)));
2208     if (w.eventCount == (e | INT_SIGN) &&
2209     U.compareAndSwapLong(this, CTL, cc, nc)) {
2210     w.eventCount = (e + E_SEQ) & E_MASK;
2211     w.runState = -1;
2212     if ((p = w.parker) != null)
2213     U.unpark(p);
2214     }
2215     }
2216     }
2217     }
2218     }
2219     }
2220     }
2221    
2222     // Exported methods
2223    
2224     // Constructors
2225    
2226     /**
2227     * Creates a {@code ForkJoinPool} with parallelism equal to {@link
2228     * java.lang.Runtime#availableProcessors}, using the {@linkplain
2229     * #defaultForkJoinWorkerThreadFactory default thread factory},
2230     * no UncaughtExceptionHandler, and non-async LIFO processing mode.
2231     *
2232     * @throws SecurityException if a security manager exists and
2233     * the caller is not permitted to modify threads
2234     * because it does not hold {@link
2235     * java.lang.RuntimePermission}{@code ("modifyThread")}
2236     */
2237     public ForkJoinPool() {
2238     this(Runtime.getRuntime().availableProcessors(),
2239     defaultForkJoinWorkerThreadFactory, null, false);
2240     }
2241    
2242     /**
2243     * Creates a {@code ForkJoinPool} with the indicated parallelism
2244     * level, the {@linkplain
2245     * #defaultForkJoinWorkerThreadFactory default thread factory},
2246     * no UncaughtExceptionHandler, and non-async LIFO processing mode.
2247     *
2248     * @param parallelism the parallelism level
2249     * @throws IllegalArgumentException if parallelism less than or
2250     * equal to zero, or greater than implementation limit
2251     * @throws SecurityException if a security manager exists and
2252     * the caller is not permitted to modify threads
2253     * because it does not hold {@link
2254     * java.lang.RuntimePermission}{@code ("modifyThread")}
2255     */
2256     public ForkJoinPool(int parallelism) {
2257     this(parallelism, defaultForkJoinWorkerThreadFactory, null, false);
2258     }
2259    
2260     /**
2261     * Creates a {@code ForkJoinPool} with the given parameters.
2262     *
2263     * @param parallelism the parallelism level. For default value,
2264     * use {@link java.lang.Runtime#availableProcessors}.
2265     * @param factory the factory for creating new threads. For default value,
2266     * use {@link #defaultForkJoinWorkerThreadFactory}.
2267     * @param handler the handler for internal worker threads that
2268     * terminate due to unrecoverable errors encountered while executing
2269     * tasks. For default value, use {@code null}.
2270     * @param asyncMode if true,
2271     * establishes local first-in-first-out scheduling mode for forked
2272     * tasks that are never joined. This mode may be more appropriate
2273     * than default locally stack-based mode in applications in which
2274     * worker threads only process event-style asynchronous tasks.
2275     * For default value, use {@code false}.
2276     * @throws IllegalArgumentException if parallelism less than or
2277     * equal to zero, or greater than implementation limit
2278     * @throws NullPointerException if the factory is null
2279     * @throws SecurityException if a security manager exists and
2280     * the caller is not permitted to modify threads
2281     * because it does not hold {@link
2282     * java.lang.RuntimePermission}{@code ("modifyThread")}
2283     */
2284     public ForkJoinPool(int parallelism,
2285     ForkJoinWorkerThreadFactory factory,
2286     Thread.UncaughtExceptionHandler handler,
2287     boolean asyncMode) {
2288     checkPermission();
2289     if (factory == null)
2290     throw new NullPointerException();
2291     if (parallelism <= 0 || parallelism > MAX_CAP)
2292     throw new IllegalArgumentException();
2293     this.parallelism = parallelism;
2294     this.factory = factory;
2295     this.ueh = handler;
2296     this.localMode = asyncMode ? FIFO_QUEUE : LIFO_QUEUE;
2297     long np = (long)(-parallelism); // offset ctl counts
2298     this.ctl = ((np << AC_SHIFT) & AC_MASK) | ((np << TC_SHIFT) & TC_MASK);
2299     // Use nearest power 2 for workQueues size. See Hackers Delight sec 3.2.
2300     int n = parallelism - 1;
2301     n |= n >>> 1; n |= n >>> 2; n |= n >>> 4; n |= n >>> 8; n |= n >>> 16;
2302 dl 1.8 this.submitMask = ((n + 1) << 1) - 1;
2303 dl 1.1 int pn = poolNumberGenerator.incrementAndGet();
2304     StringBuilder sb = new StringBuilder("ForkJoinPool-");
2305     sb.append(Integer.toString(pn));
2306     sb.append("-worker-");
2307     this.workerNamePrefix = sb.toString();
2308     this.runState = 1; // set init flag
2309     }
2310    
2311 dl 1.7 /**
2312 dl 1.8 * Constructor for common pool, suitable only for static initialization.
2313     * Basically the same as above, but uses smallest possible initial footprint.
2314     */
2315     ForkJoinPool(int parallelism, int submitMask,
2316     ForkJoinWorkerThreadFactory factory,
2317     Thread.UncaughtExceptionHandler handler) {
2318     this.factory = factory;
2319     this.ueh = handler;
2320     this.submitMask = submitMask;
2321     this.parallelism = parallelism;
2322     long np = (long)(-parallelism);
2323     this.ctl = ((np << AC_SHIFT) & AC_MASK) | ((np << TC_SHIFT) & TC_MASK);
2324     this.localMode = LIFO_QUEUE;
2325     this.workerNamePrefix = "ForkJoinPool.commonPool-worker-";
2326     this.runState = 1;
2327     }
2328    
2329     /**
2330     * Returns the common pool instance.
2331 dl 1.7 *
2332     * @return the common pool instance
2333     */
2334     public static ForkJoinPool commonPool() {
2335     ForkJoinPool p;
2336 dl 1.8 if ((p = commonPool) == null)
2337     throw new Error("Common Pool Unavailable");
2338 dl 1.7 return p;
2339     }
2340    
2341 dl 1.1 // Execution methods
2342    
2343     /**
2344     * Performs the given task, returning its result upon completion.
2345     * If the computation encounters an unchecked Exception or Error,
2346     * it is rethrown as the outcome of this invocation. Rethrown
2347     * exceptions behave in the same way as regular exceptions, but,
2348     * when possible, contain stack traces (as displayed for example
2349     * using {@code ex.printStackTrace()}) of both the current thread
2350     * as well as the thread actually encountering the exception;
2351     * minimally only the latter.
2352     *
2353     * @param task the task
2354     * @return the task's result
2355     * @throws NullPointerException if the task is null
2356     * @throws RejectedExecutionException if the task cannot be
2357     * scheduled for execution
2358     */
2359     public <T> T invoke(ForkJoinTask<T> task) {
2360     if (task == null)
2361     throw new NullPointerException();
2362     doSubmit(task);
2363     return task.join();
2364     }
2365    
2366     /**
2367     * Arranges for (asynchronous) execution of the given task.
2368     *
2369     * @param task the task
2370     * @throws NullPointerException if the task is null
2371     * @throws RejectedExecutionException if the task cannot be
2372     * scheduled for execution
2373     */
2374     public void execute(ForkJoinTask<?> task) {
2375     if (task == null)
2376     throw new NullPointerException();
2377     doSubmit(task);
2378     }
2379    
2380     // AbstractExecutorService methods
2381    
2382     /**
2383     * @throws NullPointerException if the task is null
2384     * @throws RejectedExecutionException if the task cannot be
2385     * scheduled for execution
2386     */
2387     public void execute(Runnable task) {
2388     if (task == null)
2389     throw new NullPointerException();
2390     ForkJoinTask<?> job;
2391     if (task instanceof ForkJoinTask<?>) // avoid re-wrap
2392     job = (ForkJoinTask<?>) task;
2393     else
2394     job = new ForkJoinTask.AdaptedRunnableAction(task);
2395     doSubmit(job);
2396     }
2397    
2398     /**
2399     * Submits a ForkJoinTask for execution.
2400     *
2401     * @param task the task to submit
2402     * @return the task
2403     * @throws NullPointerException if the task is null
2404     * @throws RejectedExecutionException if the task cannot be
2405     * scheduled for execution
2406     */
2407     public <T> ForkJoinTask<T> submit(ForkJoinTask<T> task) {
2408     if (task == null)
2409     throw new NullPointerException();
2410     doSubmit(task);
2411     return task;
2412     }
2413    
2414     /**
2415     * @throws NullPointerException if the task is null
2416     * @throws RejectedExecutionException if the task cannot be
2417     * scheduled for execution
2418     */
2419     public <T> ForkJoinTask<T> submit(Callable<T> task) {
2420     ForkJoinTask<T> job = new ForkJoinTask.AdaptedCallable<T>(task);
2421     doSubmit(job);
2422     return job;
2423     }
2424    
2425     /**
2426     * @throws NullPointerException if the task is null
2427     * @throws RejectedExecutionException if the task cannot be
2428     * scheduled for execution
2429     */
2430     public <T> ForkJoinTask<T> submit(Runnable task, T result) {
2431     ForkJoinTask<T> job = new ForkJoinTask.AdaptedRunnable<T>(task, result);
2432     doSubmit(job);
2433     return job;
2434     }
2435    
2436     /**
2437     * @throws NullPointerException if the task is null
2438     * @throws RejectedExecutionException if the task cannot be
2439     * scheduled for execution
2440     */
2441     public ForkJoinTask<?> submit(Runnable task) {
2442     if (task == null)
2443     throw new NullPointerException();
2444     ForkJoinTask<?> job;
2445     if (task instanceof ForkJoinTask<?>) // avoid re-wrap
2446     job = (ForkJoinTask<?>) task;
2447     else
2448     job = new ForkJoinTask.AdaptedRunnableAction(task);
2449     doSubmit(job);
2450     return job;
2451     }
2452    
2453     /**
2454     * @throws NullPointerException {@inheritDoc}
2455     * @throws RejectedExecutionException {@inheritDoc}
2456     */
2457     public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) {
2458     // In previous versions of this class, this method constructed
2459     // a task to run ForkJoinTask.invokeAll, but now external
2460     // invocation of multiple tasks is at least as efficient.
2461     List<ForkJoinTask<T>> fs = new ArrayList<ForkJoinTask<T>>(tasks.size());
2462     // Workaround needed because method wasn't declared with
2463     // wildcards in return type but should have been.
2464     @SuppressWarnings({"unchecked", "rawtypes"})
2465     List<Future<T>> futures = (List<Future<T>>) (List) fs;
2466    
2467     boolean done = false;
2468     try {
2469     for (Callable<T> t : tasks) {
2470     ForkJoinTask<T> f = new ForkJoinTask.AdaptedCallable<T>(t);
2471     doSubmit(f);
2472     fs.add(f);
2473     }
2474     for (ForkJoinTask<T> f : fs)
2475     f.quietlyJoin();
2476     done = true;
2477     return futures;
2478     } finally {
2479     if (!done)
2480     for (ForkJoinTask<T> f : fs)
2481     f.cancel(false);
2482     }
2483     }
2484    
2485     /**
2486     * Returns the factory used for constructing new workers.
2487     *
2488     * @return the factory used for constructing new workers
2489     */
2490     public ForkJoinWorkerThreadFactory getFactory() {
2491     return factory;
2492     }
2493    
2494     /**
2495     * Returns the handler for internal worker threads that terminate
2496     * due to unrecoverable errors encountered while executing tasks.
2497     *
2498     * @return the handler, or {@code null} if none
2499     */
2500     public Thread.UncaughtExceptionHandler getUncaughtExceptionHandler() {
2501     return ueh;
2502     }
2503    
2504     /**
2505     * Returns the targeted parallelism level of this pool.
2506     *
2507     * @return the targeted parallelism level of this pool
2508     */
2509     public int getParallelism() {
2510     return parallelism;
2511     }
2512    
2513     /**
2514 dl 1.7 * Returns the targeted parallelism level of the common pool.
2515     *
2516     * @return the targeted parallelism level of the common pool
2517     */
2518     public static int getCommonPoolParallelism() {
2519     return commonPoolParallelism;
2520     }
2521    
2522     /**
2523 dl 1.1 * Returns the number of worker threads that have started but not
2524     * yet terminated. The result returned by this method may differ
2525     * from {@link #getParallelism} when threads are created to
2526     * maintain parallelism when others are cooperatively blocked.
2527     *
2528     * @return the number of worker threads
2529     */
2530     public int getPoolSize() {
2531     return parallelism + (short)(ctl >>> TC_SHIFT);
2532     }
2533    
2534     /**
2535     * Returns {@code true} if this pool uses local first-in-first-out
2536     * scheduling mode for forked tasks that are never joined.
2537     *
2538     * @return {@code true} if this pool uses async mode
2539     */
2540     public boolean getAsyncMode() {
2541     return localMode != 0;
2542     }
2543    
2544     /**
2545     * Returns an estimate of the number of worker threads that are
2546     * not blocked waiting to join tasks or for other managed
2547     * synchronization. This method may overestimate the
2548     * number of running threads.
2549     *
2550     * @return the number of worker threads
2551     */
2552     public int getRunningThreadCount() {
2553     int rc = 0;
2554     WorkQueue[] ws; WorkQueue w;
2555     if ((ws = workQueues) != null) {
2556     for (int i = 1; i < ws.length; i += 2) {
2557     if ((w = ws[i]) != null && w.isApparentlyUnblocked())
2558     ++rc;
2559     }
2560     }
2561     return rc;
2562     }
2563    
2564     /**
2565     * Returns an estimate of the number of threads that are currently
2566     * stealing or executing tasks. This method may overestimate the
2567     * number of active threads.
2568     *
2569     * @return the number of active threads
2570     */
2571     public int getActiveThreadCount() {
2572     int r = parallelism + (int)(ctl >> AC_SHIFT);
2573     return (r <= 0) ? 0 : r; // suppress momentarily negative values
2574     }
2575    
2576     /**
2577     * Returns {@code true} if all worker threads are currently idle.
2578     * An idle worker is one that cannot obtain a task to execute
2579     * because none are available to steal from other threads, and
2580     * there are no pending submissions to the pool. This method is
2581     * conservative; it might not return {@code true} immediately upon
2582     * idleness of all threads, but will eventually become true if
2583     * threads remain inactive.
2584     *
2585     * @return {@code true} if all threads are currently idle
2586     */
2587     public boolean isQuiescent() {
2588     return (int)(ctl >> AC_SHIFT) + parallelism == 0;
2589     }
2590    
2591     /**
2592     * Returns an estimate of the total number of tasks stolen from
2593     * one thread's work queue by another. The reported value
2594     * underestimates the actual total number of steals when the pool
2595     * is not quiescent. This value may be useful for monitoring and
2596     * tuning fork/join programs: in general, steal counts should be
2597     * high enough to keep threads busy, but low enough to avoid
2598     * overhead and contention across threads.
2599     *
2600     * @return the number of steals
2601     */
2602     public long getStealCount() {
2603 dl 1.8 long count = stealCount;
2604 dl 1.1 WorkQueue[] ws; WorkQueue w;
2605     if ((ws = workQueues) != null) {
2606     for (int i = 1; i < ws.length; i += 2) {
2607     if ((w = ws[i]) != null)
2608     count += w.totalSteals;
2609     }
2610     }
2611     return count;
2612     }
2613    
2614     /**
2615     * Returns an estimate of the total number of tasks currently held
2616     * in queues by worker threads (but not including tasks submitted
2617     * to the pool that have not begun executing). This value is only
2618     * an approximation, obtained by iterating across all threads in
2619     * the pool. This method may be useful for tuning task
2620     * granularities.
2621     *
2622     * @return the number of queued tasks
2623     */
2624     public long getQueuedTaskCount() {
2625     long count = 0;
2626     WorkQueue[] ws; WorkQueue w;
2627     if ((ws = workQueues) != null) {
2628     for (int i = 1; i < ws.length; i += 2) {
2629     if ((w = ws[i]) != null)
2630     count += w.queueSize();
2631     }
2632     }
2633     return count;
2634     }
2635    
2636     /**
2637     * Returns an estimate of the number of tasks submitted to this
2638     * pool that have not yet begun executing. This method may take
2639     * time proportional to the number of submissions.
2640     *
2641     * @return the number of queued submissions
2642     */
2643     public int getQueuedSubmissionCount() {
2644     int count = 0;
2645     WorkQueue[] ws; WorkQueue w;
2646     if ((ws = workQueues) != null) {
2647     for (int i = 0; i < ws.length; i += 2) {
2648     if ((w = ws[i]) != null)
2649     count += w.queueSize();
2650     }
2651     }
2652     return count;
2653     }
2654    
2655     /**
2656     * Returns {@code true} if there are any tasks submitted to this
2657     * pool that have not yet begun executing.
2658     *
2659     * @return {@code true} if there are any queued submissions
2660     */
2661     public boolean hasQueuedSubmissions() {
2662     WorkQueue[] ws; WorkQueue w;
2663     if ((ws = workQueues) != null) {
2664     for (int i = 0; i < ws.length; i += 2) {
2665     if ((w = ws[i]) != null && !w.isEmpty())
2666     return true;
2667     }
2668     }
2669     return false;
2670     }
2671    
2672     /**
2673     * Removes and returns the next unexecuted submission if one is
2674     * available. This method may be useful in extensions to this
2675     * class that re-assign work in systems with multiple pools.
2676     *
2677     * @return the next submission, or {@code null} if none
2678     */
2679     protected ForkJoinTask<?> pollSubmission() {
2680     WorkQueue[] ws; WorkQueue w; ForkJoinTask<?> t;
2681     if ((ws = workQueues) != null) {
2682     for (int i = 0; i < ws.length; i += 2) {
2683     if ((w = ws[i]) != null && (t = w.poll()) != null)
2684     return t;
2685     }
2686     }
2687     return null;
2688     }
2689    
2690     /**
2691     * Removes all available unexecuted submitted and forked tasks
2692     * from scheduling queues and adds them to the given collection,
2693     * without altering their execution status. These may include
2694     * artificially generated or wrapped tasks. This method is
2695     * designed to be invoked only when the pool is known to be
2696     * quiescent. Invocations at other times may not remove all
2697     * tasks. A failure encountered while attempting to add elements
2698     * to collection {@code c} may result in elements being in
2699     * neither, either or both collections when the associated
2700     * exception is thrown. The behavior of this operation is
2701     * undefined if the specified collection is modified while the
2702     * operation is in progress.
2703     *
2704     * @param c the collection to transfer elements into
2705     * @return the number of elements transferred
2706     */
2707     protected int drainTasksTo(Collection<? super ForkJoinTask<?>> c) {
2708     int count = 0;
2709     WorkQueue[] ws; WorkQueue w; ForkJoinTask<?> t;
2710     if ((ws = workQueues) != null) {
2711     for (int i = 0; i < ws.length; ++i) {
2712     if ((w = ws[i]) != null) {
2713     while ((t = w.poll()) != null) {
2714     c.add(t);
2715     ++count;
2716     }
2717     }
2718     }
2719     }
2720     return count;
2721     }
2722    
2723     /**
2724     * Returns a string identifying this pool, as well as its state,
2725     * including indications of run state, parallelism level, and
2726     * worker and task counts.
2727     *
2728     * @return a string identifying this pool, as well as its state
2729     */
2730     public String toString() {
2731     // Use a single pass through workQueues to collect counts
2732     long qt = 0L, qs = 0L; int rc = 0;
2733 dl 1.8 long st = stealCount;
2734 dl 1.1 long c = ctl;
2735     WorkQueue[] ws; WorkQueue w;
2736     if ((ws = workQueues) != null) {
2737     for (int i = 0; i < ws.length; ++i) {
2738     if ((w = ws[i]) != null) {
2739     int size = w.queueSize();
2740     if ((i & 1) == 0)
2741     qs += size;
2742     else {
2743     qt += size;
2744     st += w.totalSteals;
2745     if (w.isApparentlyUnblocked())
2746     ++rc;
2747     }
2748     }
2749     }
2750     }
2751     int pc = parallelism;
2752     int tc = pc + (short)(c >>> TC_SHIFT);
2753     int ac = pc + (int)(c >> AC_SHIFT);
2754     if (ac < 0) // ignore transient negative
2755     ac = 0;
2756     String level;
2757     if ((c & STOP_BIT) != 0)
2758     level = (tc == 0) ? "Terminated" : "Terminating";
2759     else
2760     level = runState < 0 ? "Shutting down" : "Running";
2761     return super.toString() +
2762     "[" + level +
2763     ", parallelism = " + pc +
2764     ", size = " + tc +
2765     ", active = " + ac +
2766     ", running = " + rc +
2767     ", steals = " + st +
2768     ", tasks = " + qt +
2769     ", submissions = " + qs +
2770     "]";
2771     }
2772    
2773     /**
2774 dl 1.7 * Possibly initiates an orderly shutdown in which previously
2775     * submitted tasks are executed, but no new tasks will be
2776     * accepted. Invocation has no effect on execution state if this
2777     * is the {@link #commonPool}, and no additional effect if
2778     * already shut down. Tasks that are in the process of being
2779     * submitted concurrently during the course of this method may or
2780     * may not be rejected.
2781 dl 1.1 *
2782     * @throws SecurityException if a security manager exists and
2783     * the caller is not permitted to modify threads
2784     * because it does not hold {@link
2785     * java.lang.RuntimePermission}{@code ("modifyThread")}
2786     */
2787     public void shutdown() {
2788     checkPermission();
2789 dl 1.7 if (this != commonPool)
2790     tryTerminate(false, true);
2791 dl 1.1 }
2792    
2793     /**
2794 dl 1.7 * Possibly attempts to cancel and/or stop all tasks, and reject
2795     * all subsequently submitted tasks. Invocation has no effect on
2796     * execution state if this is the {@link #commonPool}, and no
2797     * additional effect if already shut down. Otherwise, tasks that
2798     * are in the process of being submitted or executed concurrently
2799     * during the course of this method may or may not be
2800     * rejected. This method cancels both existing and unexecuted
2801     * tasks, in order to permit termination in the presence of task
2802     * dependencies. So the method always returns an empty list
2803     * (unlike the case for some other Executors).
2804 dl 1.1 *
2805     * @return an empty list
2806     * @throws SecurityException if a security manager exists and
2807     * the caller is not permitted to modify threads
2808     * because it does not hold {@link
2809     * java.lang.RuntimePermission}{@code ("modifyThread")}
2810     */
2811     public List<Runnable> shutdownNow() {
2812     checkPermission();
2813 dl 1.7 if (this != commonPool)
2814     tryTerminate(true, true);
2815 dl 1.1 return Collections.emptyList();
2816     }
2817    
2818     /**
2819     * Returns {@code true} if all tasks have completed following shut down.
2820     *
2821     * @return {@code true} if all tasks have completed following shut down
2822     */
2823     public boolean isTerminated() {
2824     long c = ctl;
2825     return ((c & STOP_BIT) != 0L &&
2826     (short)(c >>> TC_SHIFT) == -parallelism);
2827     }
2828    
2829     /**
2830     * Returns {@code true} if the process of termination has
2831     * commenced but not yet completed. This method may be useful for
2832     * debugging. A return of {@code true} reported a sufficient
2833     * period after shutdown may indicate that submitted tasks have
2834     * ignored or suppressed interruption, or are waiting for IO,
2835     * causing this executor not to properly terminate. (See the
2836     * advisory notes for class {@link ForkJoinTask} stating that
2837     * tasks should not normally entail blocking operations. But if
2838     * they do, they must abort them on interrupt.)
2839     *
2840     * @return {@code true} if terminating but not yet terminated
2841     */
2842     public boolean isTerminating() {
2843     long c = ctl;
2844     return ((c & STOP_BIT) != 0L &&
2845     (short)(c >>> TC_SHIFT) != -parallelism);
2846     }
2847    
2848     /**
2849     * Returns {@code true} if this pool has been shut down.
2850     *
2851     * @return {@code true} if this pool has been shut down
2852     */
2853     public boolean isShutdown() {
2854     return runState < 0;
2855     }
2856    
2857     /**
2858     * Blocks until all tasks have completed execution after a shutdown
2859     * request, or the timeout occurs, or the current thread is
2860     * interrupted, whichever happens first.
2861     *
2862     * @param timeout the maximum time to wait
2863     * @param unit the time unit of the timeout argument
2864     * @return {@code true} if this executor terminated and
2865     * {@code false} if the timeout elapsed before termination
2866     * @throws InterruptedException if interrupted while waiting
2867     */
2868     public boolean awaitTermination(long timeout, TimeUnit unit)
2869     throws InterruptedException {
2870     long nanos = unit.toNanos(timeout);
2871 dl 1.8 if (isTerminated())
2872     return true;
2873     long startTime = System.nanoTime();
2874     boolean terminated = false;
2875     synchronized(this) {
2876     for (long waitTime = nanos, millis = 0L;;) {
2877     if (terminated = isTerminated() ||
2878     waitTime <= 0L ||
2879     (millis = unit.toMillis(waitTime)) <= 0L)
2880     break;
2881     wait(millis);
2882     waitTime = nanos - (System.nanoTime() - startTime);
2883 dl 1.1 }
2884     }
2885 dl 1.8 return terminated;
2886 dl 1.1 }
2887    
2888     /**
2889     * Interface for extending managed parallelism for tasks running
2890     * in {@link ForkJoinPool}s.
2891     *
2892     * <p>A {@code ManagedBlocker} provides two methods. Method
2893     * {@code isReleasable} must return {@code true} if blocking is
2894     * not necessary. Method {@code block} blocks the current thread
2895     * if necessary (perhaps internally invoking {@code isReleasable}
2896     * before actually blocking). These actions are performed by any
2897     * thread invoking {@link ForkJoinPool#managedBlock}. The
2898     * unusual methods in this API accommodate synchronizers that may,
2899     * but don't usually, block for long periods. Similarly, they
2900     * allow more efficient internal handling of cases in which
2901     * additional workers may be, but usually are not, needed to
2902     * ensure sufficient parallelism. Toward this end,
2903     * implementations of method {@code isReleasable} must be amenable
2904     * to repeated invocation.
2905     *
2906     * <p>For example, here is a ManagedBlocker based on a
2907     * ReentrantLock:
2908     * <pre> {@code
2909     * class ManagedLocker implements ManagedBlocker {
2910     * final ReentrantLock lock;
2911     * boolean hasLock = false;
2912     * ManagedLocker(ReentrantLock lock) { this.lock = lock; }
2913     * public boolean block() {
2914     * if (!hasLock)
2915     * lock.lock();
2916     * return true;
2917     * }
2918     * public boolean isReleasable() {
2919     * return hasLock || (hasLock = lock.tryLock());
2920     * }
2921     * }}</pre>
2922     *
2923     * <p>Here is a class that possibly blocks waiting for an
2924     * item on a given queue:
2925     * <pre> {@code
2926     * class QueueTaker<E> implements ManagedBlocker {
2927     * final BlockingQueue<E> queue;
2928     * volatile E item = null;
2929     * QueueTaker(BlockingQueue<E> q) { this.queue = q; }
2930     * public boolean block() throws InterruptedException {
2931     * if (item == null)
2932     * item = queue.take();
2933     * return true;
2934     * }
2935     * public boolean isReleasable() {
2936     * return item != null || (item = queue.poll()) != null;
2937     * }
2938     * public E getItem() { // call after pool.managedBlock completes
2939     * return item;
2940     * }
2941     * }}</pre>
2942     */
2943     public static interface ManagedBlocker {
2944     /**
2945     * Possibly blocks the current thread, for example waiting for
2946     * a lock or condition.
2947     *
2948     * @return {@code true} if no additional blocking is necessary
2949     * (i.e., if isReleasable would return true)
2950     * @throws InterruptedException if interrupted while waiting
2951     * (the method is not required to do so, but is allowed to)
2952     */
2953     boolean block() throws InterruptedException;
2954    
2955     /**
2956     * Returns {@code true} if blocking is unnecessary.
2957     */
2958     boolean isReleasable();
2959     }
2960    
2961     /**
2962     * Blocks in accord with the given blocker. If the current thread
2963     * is a {@link ForkJoinWorkerThread}, this method possibly
2964     * arranges for a spare thread to be activated if necessary to
2965     * ensure sufficient parallelism while the current thread is blocked.
2966     *
2967     * <p>If the caller is not a {@link ForkJoinTask}, this method is
2968     * behaviorally equivalent to
2969     * <pre> {@code
2970     * while (!blocker.isReleasable())
2971     * if (blocker.block())
2972     * return;
2973     * }</pre>
2974     *
2975     * If the caller is a {@code ForkJoinTask}, then the pool may
2976     * first be expanded to ensure parallelism, and later adjusted.
2977     *
2978     * @param blocker the blocker
2979     * @throws InterruptedException if blocker.block did so
2980     */
2981     public static void managedBlock(ManagedBlocker blocker)
2982     throws InterruptedException {
2983     Thread t = Thread.currentThread();
2984     ForkJoinPool p = ((t instanceof ForkJoinWorkerThread) ?
2985     ((ForkJoinWorkerThread)t).pool : null);
2986     while (!blocker.isReleasable()) {
2987     if (p == null || p.tryCompensate(null, blocker)) {
2988     try {
2989     do {} while (!blocker.isReleasable() && !blocker.block());
2990     } finally {
2991     if (p != null)
2992     p.incrementActiveCount();
2993     }
2994     break;
2995     }
2996     }
2997     }
2998    
2999     // AbstractExecutorService overrides. These rely on undocumented
3000     // fact that ForkJoinTask.adapt returns ForkJoinTasks that also
3001     // implement RunnableFuture.
3002    
3003     protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
3004     return new ForkJoinTask.AdaptedRunnable<T>(runnable, value);
3005     }
3006    
3007     protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
3008     return new ForkJoinTask.AdaptedCallable<T>(callable);
3009     }
3010    
3011     // Unsafe mechanics
3012     private static final sun.misc.Unsafe U;
3013     private static final long CTL;
3014     private static final long PARKBLOCKER;
3015     private static final int ABASE;
3016     private static final int ASHIFT;
3017 dl 1.8 private static final long NEXTWORKERNUMBER;
3018     private static final long STEALCOUNT;
3019     private static final long MAINLOCK;
3020 dl 1.1
3021     static {
3022     poolNumberGenerator = new AtomicInteger();
3023     nextSubmitterSeed = new AtomicInteger(0x55555555);
3024     modifyThreadPermission = new RuntimePermission("modifyThread");
3025     defaultForkJoinWorkerThreadFactory =
3026     new DefaultForkJoinWorkerThreadFactory();
3027     submitters = new ThreadSubmitter();
3028     int s;
3029     try {
3030     U = getUnsafe();
3031     Class<?> k = ForkJoinPool.class;
3032     Class<?> ak = ForkJoinTask[].class;
3033     CTL = U.objectFieldOffset
3034     (k.getDeclaredField("ctl"));
3035 dl 1.8 NEXTWORKERNUMBER = U.objectFieldOffset
3036     (k.getDeclaredField("nextWorkerNumber"));
3037     STEALCOUNT = U.objectFieldOffset
3038     (k.getDeclaredField("stealCount"));
3039     MAINLOCK = U.objectFieldOffset
3040     (k.getDeclaredField("mainLock"));
3041 dl 1.1 Class<?> tk = Thread.class;
3042     PARKBLOCKER = U.objectFieldOffset
3043     (tk.getDeclaredField("parkBlocker"));
3044     ABASE = U.arrayBaseOffset(ak);
3045     s = U.arrayIndexScale(ak);
3046 dl 1.8 ASHIFT = 31 - Integer.numberOfLeadingZeros(s);
3047 dl 1.1 } catch (Exception e) {
3048     throw new Error(e);
3049     }
3050     if ((s & (s-1)) != 0)
3051     throw new Error("data type scale not a power of two");
3052 dl 1.8 try { // Establish common pool
3053 dl 1.7 String pp = System.getProperty(propPrefix + "parallelism");
3054     String fp = System.getProperty(propPrefix + "threadFactory");
3055     String up = System.getProperty(propPrefix + "exceptionHandler");
3056 dl 1.8 ForkJoinWorkerThreadFactory fac = (fp == null) ?
3057     defaultForkJoinWorkerThreadFactory :
3058     ((ForkJoinWorkerThreadFactory)ClassLoader.
3059     getSystemClassLoader().loadClass(fp).newInstance());
3060     Thread.UncaughtExceptionHandler ueh = (up == null)? null :
3061     ((Thread.UncaughtExceptionHandler)ClassLoader.
3062     getSystemClassLoader().loadClass(up).newInstance());
3063 dl 1.7 int par;
3064     if ((pp == null || (par = Integer.parseInt(pp)) <= 0))
3065     par = Runtime.getRuntime().availableProcessors();
3066 dl 1.8 if (par > MAX_CAP)
3067     par = MAX_CAP;
3068 dl 1.7 commonPoolParallelism = par;
3069 dl 1.8 int n = par - 1; // precompute submit mask
3070     n |= n >>> 1; n |= n >>> 2; n |= n >>> 4;
3071     n |= n >>> 8; n |= n >>> 16;
3072     int mask = ((n + 1) << 1) - 1;
3073     commonPool = new ForkJoinPool(par, mask, fac, ueh);
3074 dl 1.7 } catch (Exception e) {
3075     throw new Error(e);
3076     }
3077 dl 1.1 }
3078    
3079     /**
3080     * Returns a sun.misc.Unsafe. Suitable for use in a 3rd party package.
3081     * Replace with a simple call to Unsafe.getUnsafe when integrating
3082     * into a jdk.
3083     *
3084     * @return a sun.misc.Unsafe
3085     */
3086     private static sun.misc.Unsafe getUnsafe() {
3087     try {
3088     return sun.misc.Unsafe.getUnsafe();
3089     } catch (SecurityException se) {
3090     try {
3091     return java.security.AccessController.doPrivileged
3092     (new java.security
3093     .PrivilegedExceptionAction<sun.misc.Unsafe>() {
3094     public sun.misc.Unsafe run() throws Exception {
3095     java.lang.reflect.Field f = sun.misc
3096     .Unsafe.class.getDeclaredField("theUnsafe");
3097     f.setAccessible(true);
3098     return (sun.misc.Unsafe) f.get(null);
3099     }});
3100     } catch (java.security.PrivilegedActionException e) {
3101     throw new RuntimeException("Could not initialize intrinsics",
3102     e.getCause());
3103     }
3104     }
3105     }
3106    
3107     }