ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinPool.java
Revision: 1.92
Committed: Tue Feb 21 00:19:23 2012 UTC (12 years, 3 months ago) by jsr166
Branch: MAIN
Changes since 1.91: +3 -3 lines
Log Message:
typos

File Contents

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