ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jsr166e/ForkJoinPool.java
Revision: 1.10
Committed: Tue Oct 30 16:05:35 2012 UTC (11 years, 6 months ago) by jsr166
Branch: MAIN
Changes since 1.9: +7 -7 lines
Log Message:
whitespace

File Contents

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