ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jsr166e/ForkJoinPool.java
Revision: 1.7
Committed: Sun Oct 28 22:35:45 2012 UTC (11 years, 6 months ago) by dl
Branch: MAIN
Changes since 1.6: +239 -73 lines
Log Message:
Introduce ForkJoinPool.commonPool

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